blob: d9e9e2b11615e75f1b7eec0f62a86b6b26875eac [file] [log] [blame]
Jiyong Park86c9b082021-06-04 19:03:48 +09001/*
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
Andrew Walbranf714eeb2022-11-30 11:15:56 +000024#![cfg_attr(test, allow(unused))]
25
Jiyong Park86c9b082021-06-04 19:03:48 +090026use anyhow::{bail, Context, Result};
Alice Wang1bf3d782022-09-28 07:56:36 +000027use apkverify::{HashAlgorithm, V4Signature};
Andrew Walbranaa1efc42022-08-10 13:33:57 +000028use clap::{arg, Arg, ArgAction, Command};
Shikha Panwarb278b1c2022-10-14 12:38:32 +000029use dm::loopdevice;
Shikha Panwar414ea892022-10-12 13:45:52 +000030use dm::util;
31use dm::verity::{DmVerityHashAlgorithm, DmVerityTargetBuilder};
Inseob Kim217038e2021-11-25 11:15:06 +090032use itertools::Itertools;
Jiyong Park86c9b082021-06-04 19:03:48 +090033use std::fmt::Debug;
34use std::fs;
Jiyong Park86c9b082021-06-04 19:03:48 +090035use std::os::unix::fs::FileTypeExt;
36use std::path::{Path, PathBuf};
37
Andrew Walbranf714eeb2022-11-30 11:15:56 +000038#[cfg(not(test))]
Jiyong Park86c9b082021-06-04 19:03:48 +090039fn main() -> Result<()> {
Andrew Walbranaa1efc42022-08-10 13:33:57 +000040 let matches = clap_command().get_matches();
Jiyong Park86c9b082021-06-04 19:03:48 +090041
Andrew Walbranaa1efc42022-08-10 13:33:57 +000042 let apks = matches.get_many::<String>("apk").unwrap();
Inseob Kim197748b2021-12-01 19:49:00 +090043 assert!(apks.len() % 4 == 0);
Inseob Kim217038e2021-11-25 11:15:06 +090044
Andrew Walbranaa1efc42022-08-10 13:33:57 +000045 let verbose = matches.get_flag("verbose");
Inseob Kim217038e2021-11-25 11:15:06 +090046
Inseob Kim197748b2021-12-01 19:49:00 +090047 for (apk, idsig, name, roothash) in apks.tuples() {
48 let roothash = if roothash != "none" {
49 Some(util::parse_hexstring(roothash).expect("failed to parse roothash"))
50 } else {
51 None
52 };
Inseob Kim217038e2021-11-25 11:15:06 +090053 let ret = enable_verity(apk, idsig, name, roothash.as_deref())?;
54 if verbose {
55 println!(
56 "data_device: {:?}, hash_device: {:?}, mapper_device: {:?}",
57 ret.data_device, ret.hash_device, ret.mapper_device
58 );
59 }
Jiyong Park99a35b82021-06-07 10:13:44 +090060 }
Jiyong Park86c9b082021-06-04 19:03:48 +090061 Ok(())
62}
63
Andrew Walbranaa1efc42022-08-10 13:33:57 +000064fn clap_command() -> Command {
65 Command::new("apkdmverity")
66 .about("Creates a dm-verity block device out of APK signed with APK signature scheme V4.")
67 .arg(
68 arg!(--apk ...
69 "Input APK file, idsig file, name of the block device, and root hash. \
70 The APK file must be signed using the APK signature scheme 4. The \
71 block device is created at \"/dev/mapper/<name>\".' root_hash is \
72 optional; idsig file's root hash will be used if specified as \"none\"."
73 )
74 .action(ArgAction::Append)
Chris Wailes75269622022-12-05 23:01:44 -080075 .value_names(["apk_path", "idsig_path", "name", "root_hash"]),
Andrew Walbranaa1efc42022-08-10 13:33:57 +000076 )
77 .arg(
78 Arg::new("verbose")
79 .short('v')
80 .long("verbose")
81 .action(ArgAction::SetTrue)
82 .help("Shows verbose output"),
83 )
84}
85
Jiyong Park86c9b082021-06-04 19:03:48 +090086struct VerityResult {
87 data_device: PathBuf,
88 hash_device: PathBuf,
89 mapper_device: PathBuf,
90}
91
92const BLOCK_SIZE: u64 = 4096;
93
94// Makes a dm-verity block device out of `apk` and its accompanying `idsig` files.
Jiyong Parkbb4a9872021-09-06 15:59:21 +090095fn enable_verity<P: AsRef<Path> + Debug>(
96 apk: P,
97 idsig: P,
98 name: &str,
99 roothash: Option<&[u8]>,
100) -> Result<VerityResult> {
Jiyong Park86c9b082021-06-04 19:03:48 +0900101 // Attach the apk file to a loop device if the apk file is a regular file. If not (i.e. block
102 // device), we only need to get the size and use the block device as it is.
103 let (data_device, apk_size) = if fs::metadata(&apk)?.file_type().is_block_device() {
104 (apk.as_ref().to_path_buf(), util::blkgetsize64(apk.as_ref())?)
105 } else {
106 let apk_size = fs::metadata(&apk)?.len();
107 if apk_size % BLOCK_SIZE != 0 {
108 bail!("The size of {:?} is not multiple of {}.", &apk, BLOCK_SIZE)
109 }
Jooyung Han1b00bd22022-04-15 15:29:25 +0900110 (
Shikha Panwar743454c2022-10-18 12:50:30 +0000111 loopdevice::attach(&apk, 0, apk_size, /*direct_io*/ true, /*writable*/ false)
Jooyung Han1b00bd22022-04-15 15:29:25 +0900112 .context("Failed to attach APK to a loop device")?,
113 apk_size,
114 )
Jiyong Park86c9b082021-06-04 19:03:48 +0900115 };
116
117 // Parse the idsig file to locate the merkle tree in it, then attach the file to a loop device
118 // with the offset so that the start of the merkle tree becomes the beginning of the loop
119 // device.
Alice Wang89cff012022-09-26 10:05:16 +0000120 let sig = V4Signature::from_idsig_path(&idsig)?;
Jiyong Park86c9b082021-06-04 19:03:48 +0900121 let offset = sig.merkle_tree_offset;
122 let size = sig.merkle_tree_size as u64;
Jooyung Han1b00bd22022-04-15 15:29:25 +0900123 // Due to unknown reason(b/191344832), we can't enable "direct IO" for the IDSIG file (backing
124 // the hash). For now we don't use "direct IO" but it seems OK since the IDSIG file is very
125 // small and the benefit of direct-IO would be negliable.
Shikha Panwar743454c2022-10-18 12:50:30 +0000126 let hash_device =
127 loopdevice::attach(&idsig, offset, size, /*direct_io*/ false, /*writable*/ false)
128 .context("Failed to attach idsig to a loop device")?;
Jiyong Park86c9b082021-06-04 19:03:48 +0900129
130 // Build a dm-verity target spec from the information from the idsig file. The apk and the
131 // idsig files are used as the data device and the hash device, respectively.
Shikha Panwar414ea892022-10-12 13:45:52 +0000132 let target = DmVerityTargetBuilder::default()
Jiyong Park86c9b082021-06-04 19:03:48 +0900133 .data_device(&data_device, apk_size)
134 .hash_device(&hash_device)
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900135 .root_digest(if let Some(roothash) = roothash {
136 roothash
137 } else {
138 &sig.hashing_info.raw_root_hash
139 })
Jiyong Park86c9b082021-06-04 19:03:48 +0900140 .hash_algorithm(match sig.hashing_info.hash_algorithm {
Shikha Panwar414ea892022-10-12 13:45:52 +0000141 HashAlgorithm::SHA256 => DmVerityHashAlgorithm::SHA256,
Jiyong Park86c9b082021-06-04 19:03:48 +0900142 })
143 .salt(&sig.hashing_info.salt)
144 .build()
145 .context(format!("Merkle tree in {:?} is not compatible with dm-verity", &idsig))?;
146
147 // Actually create a dm-verity block device using the spec.
148 let dm = dm::DeviceMapper::new()?;
149 let mapper_device =
Shikha Panwar414ea892022-10-12 13:45:52 +0000150 dm.create_verity_device(name, &target).context("Failed to create dm-verity device")?;
Jiyong Park86c9b082021-06-04 19:03:48 +0900151
152 Ok(VerityResult { data_device, hash_device, mapper_device })
153}
154
155#[cfg(test)]
Andrew Walbran31e059b2023-06-29 16:33:54 +0000156rdroidtest::test_main!();
Andrew Walbranf714eeb2022-11-30 11:15:56 +0000157
158#[cfg(test)]
Jiyong Park86c9b082021-06-04 19:03:48 +0900159mod tests {
160 use crate::*;
Andrew Walbran31e059b2023-06-29 16:33:54 +0000161 use rdroidtest::test;
Alice Wang89cff012022-09-26 10:05:16 +0000162 use std::fs::{File, OpenOptions};
163 use std::io::Write;
Andrew Walbranf714eeb2022-11-30 11:15:56 +0000164 use std::ops::Deref;
Jiyong Park86c9b082021-06-04 19:03:48 +0900165 use std::os::unix::fs::FileExt;
166
167 struct TestContext<'a> {
168 data_backing_file: &'a Path,
169 hash_backing_file: &'a Path,
170 result: &'a VerityResult,
171 }
172
Jiyong Parkd17ff4b2021-07-15 12:32:25 +0900173 // On Android, skip the test on devices that doesn't have the virt APEX
174 // (b/193612136)
175 #[cfg(target_os = "android")]
176 fn should_skip() -> bool {
177 !Path::new("/apex/com.android.virt").exists()
178 }
179 #[cfg(not(target_os = "android"))]
180 fn should_skip() -> bool {
181 false
182 }
183
Jiyong Park86c9b082021-06-04 19:03:48 +0900184 fn create_block_aligned_file(path: &Path, data: &[u8]) {
Chris Wailes9b866f02022-11-16 15:17:16 -0800185 let mut f = File::create(path).unwrap();
Jiyong Park86c9b082021-06-04 19:03:48 +0900186 f.write_all(data).unwrap();
187
188 // Add padding so that the size of the file is multiple of 4096.
189 let aligned_size = (data.len() as u64 + BLOCK_SIZE - 1) & !(BLOCK_SIZE - 1);
190 let padding = aligned_size - data.len() as u64;
191 f.write_all(vec![0; padding as usize].as_slice()).unwrap();
192 }
193
194 fn prepare_inputs(test_dir: &Path, apk: &[u8], idsig: &[u8]) -> (PathBuf, PathBuf) {
195 let apk_path = test_dir.join("test.apk");
196 let idsig_path = test_dir.join("test.apk.idsig");
197 create_block_aligned_file(&apk_path, apk);
198 create_block_aligned_file(&idsig_path, idsig);
199 (apk_path, idsig_path)
200 }
201
202 fn run_test(apk: &[u8], idsig: &[u8], name: &str, check: fn(TestContext)) {
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900203 run_test_with_hash(apk, idsig, name, None, check);
204 }
205
206 fn run_test_with_hash(
207 apk: &[u8],
208 idsig: &[u8],
209 name: &str,
210 roothash: Option<&[u8]>,
211 check: fn(TestContext),
212 ) {
Jiyong Park86c9b082021-06-04 19:03:48 +0900213 let test_dir = tempfile::TempDir::new().unwrap();
Chris Wailes68c39f82021-07-27 16:03:44 -0700214 let (apk_path, idsig_path) = prepare_inputs(test_dir.path(), apk, idsig);
Jiyong Park86c9b082021-06-04 19:03:48 +0900215
216 // Run the program and register clean-ups.
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900217 let ret = enable_verity(&apk_path, &idsig_path, name, roothash).unwrap();
Jiyong Park86c9b082021-06-04 19:03:48 +0900218 let ret = scopeguard::guard(ret, |ret| {
219 loopdevice::detach(ret.data_device).unwrap();
220 loopdevice::detach(ret.hash_device).unwrap();
221 let dm = dm::DeviceMapper::new().unwrap();
222 dm.delete_device_deferred(name).unwrap();
223 });
224
225 check(TestContext {
226 data_backing_file: &apk_path,
227 hash_backing_file: &idsig_path,
228 result: &ret,
229 });
230 }
231
Andrew Walbranf714eeb2022-11-30 11:15:56 +0000232 test!(correct_inputs, ignore_if: should_skip());
Jiyong Park86c9b082021-06-04 19:03:48 +0900233 fn correct_inputs() {
234 let apk = include_bytes!("../testdata/test.apk");
235 let idsig = include_bytes!("../testdata/test.apk.idsig");
236 run_test(apk.as_ref(), idsig.as_ref(), "correct", |ctx| {
237 let verity = fs::read(&ctx.result.mapper_device).unwrap();
238 let original = fs::read(&ctx.result.data_device).unwrap();
239 assert_eq!(verity.len(), original.len()); // fail fast
240 assert_eq!(verity.as_slice(), original.as_slice());
241 });
242 }
243
244 // A single byte change in the APK file causes an IO error
Andrew Walbranf714eeb2022-11-30 11:15:56 +0000245 test!(incorrect_apk, ignore_if: should_skip());
Jiyong Park86c9b082021-06-04 19:03:48 +0900246 fn incorrect_apk() {
247 let apk = include_bytes!("../testdata/test.apk");
248 let idsig = include_bytes!("../testdata/test.apk.idsig");
249
250 let mut modified_apk = Vec::new();
251 modified_apk.extend_from_slice(apk);
252 if let Some(byte) = modified_apk.get_mut(100) {
253 *byte = 1;
254 }
255
256 run_test(modified_apk.as_slice(), idsig.as_ref(), "incorrect_apk", |ctx| {
Jiyong Park7b08c572021-09-14 07:28:56 +0900257 fs::read(&ctx.result.mapper_device).expect_err("Should fail");
Jiyong Park86c9b082021-06-04 19:03:48 +0900258 });
259 }
260
261 // A single byte change in the merkle tree also causes an IO error
Andrew Walbranf714eeb2022-11-30 11:15:56 +0000262 test!(incorrect_merkle_tree, ignore_if: should_skip());
Jiyong Park86c9b082021-06-04 19:03:48 +0900263 fn incorrect_merkle_tree() {
264 let apk = include_bytes!("../testdata/test.apk");
265 let idsig = include_bytes!("../testdata/test.apk.idsig");
266
267 // Make a single-byte change to the merkle tree
Alice Wang89cff012022-09-26 10:05:16 +0000268 let offset = V4Signature::from_idsig_path("testdata/test.apk.idsig")
269 .unwrap()
270 .merkle_tree_offset as usize;
Jiyong Park86c9b082021-06-04 19:03:48 +0900271
272 let mut modified_idsig = Vec::new();
273 modified_idsig.extend_from_slice(idsig);
274 if let Some(byte) = modified_idsig.get_mut(offset + 10) {
275 *byte = 1;
276 }
277
278 run_test(apk.as_ref(), modified_idsig.as_slice(), "incorrect_merkle_tree", |ctx| {
Jiyong Park7b08c572021-09-14 07:28:56 +0900279 fs::read(&ctx.result.mapper_device).expect_err("Should fail");
Jiyong Park86c9b082021-06-04 19:03:48 +0900280 });
281 }
282
283 // APK is not altered when the verity device is created, but later modified. IO error should
284 // occur when trying to read the data around the modified location. This is the main scenario
285 // that we'd like to protect.
Andrew Walbranf714eeb2022-11-30 11:15:56 +0000286 test!(tampered_apk, ignore_if: should_skip());
Jiyong Park86c9b082021-06-04 19:03:48 +0900287 fn tampered_apk() {
288 let apk = include_bytes!("../testdata/test.apk");
289 let idsig = include_bytes!("../testdata/test.apk.idsig");
290
291 run_test(apk.as_ref(), idsig.as_ref(), "tampered_apk", |ctx| {
292 // At this moment, the verity device is created. Then let's change 10 bytes in the
293 // backing data file.
294 const MODIFIED_OFFSET: u64 = 10000;
295 let f = OpenOptions::new().read(true).write(true).open(ctx.data_backing_file).unwrap();
296 f.write_at(&[0, 1], MODIFIED_OFFSET).unwrap();
297
298 // Read around the modified location causes an error
299 let f = File::open(&ctx.result.mapper_device).unwrap();
300 let mut buf = vec![0; 10]; // just read 10 bytes
Jiyong Park7b08c572021-09-14 07:28:56 +0900301 f.read_at(&mut buf, MODIFIED_OFFSET).expect_err("Should fail");
Jiyong Park86c9b082021-06-04 19:03:48 +0900302 });
303 }
304
305 // idsig file is not alread when the verity device is created, but later modified. Unlike to
306 // the APK case, this doesn't occur IO error because the merkle tree is already cached.
Andrew Walbranf714eeb2022-11-30 11:15:56 +0000307 test!(tampered_idsig, ignore_if: should_skip());
Jiyong Park86c9b082021-06-04 19:03:48 +0900308 fn tampered_idsig() {
309 let apk = include_bytes!("../testdata/test.apk");
310 let idsig = include_bytes!("../testdata/test.apk.idsig");
311 run_test(apk.as_ref(), idsig.as_ref(), "tampered_idsig", |ctx| {
312 // Change 10 bytes in the merkle tree.
313 let f = OpenOptions::new().read(true).write(true).open(ctx.hash_backing_file).unwrap();
314 f.write_at(&[0, 10], 100).unwrap();
315
316 let verity = fs::read(&ctx.result.mapper_device).unwrap();
317 let original = fs::read(&ctx.result.data_device).unwrap();
318 assert_eq!(verity.len(), original.len());
319 assert_eq!(verity.as_slice(), original.as_slice());
320 });
321 }
322
323 // test if both files are already block devices
Andrew Walbranf714eeb2022-11-30 11:15:56 +0000324 test!(inputs_are_block_devices, ignore_if: should_skip());
Jiyong Park86c9b082021-06-04 19:03:48 +0900325 fn inputs_are_block_devices() {
Jiyong Park86c9b082021-06-04 19:03:48 +0900326 let apk = include_bytes!("../testdata/test.apk");
327 let idsig = include_bytes!("../testdata/test.apk.idsig");
328
329 let test_dir = tempfile::TempDir::new().unwrap();
Chris Wailes68c39f82021-07-27 16:03:44 -0700330 let (apk_path, idsig_path) = prepare_inputs(test_dir.path(), apk, idsig);
Jiyong Park86c9b082021-06-04 19:03:48 +0900331
332 // attach the files to loop devices to make them block devices
333 let apk_size = fs::metadata(&apk_path).unwrap().len();
334 let idsig_size = fs::metadata(&idsig_path).unwrap().len();
335
336 // Note that apk_loop_device is not detatched. This is because, when the apk file is
337 // already a block device, `enable_verity` uses the block device as it is. The detatching
338 // of the data device is done in the scopeguard for the return value of `enable_verity`
339 // below. Only the idsig_loop_device needs detatching.
Shikha Panwar743454c2022-10-18 12:50:30 +0000340 let apk_loop_device = loopdevice::attach(
341 &apk_path, 0, apk_size, /*direct_io*/ true, /*writable*/ false,
342 )
343 .unwrap();
Jooyung Han1b00bd22022-04-15 15:29:25 +0900344 let idsig_loop_device = scopeguard::guard(
Shikha Panwar743454c2022-10-18 12:50:30 +0000345 loopdevice::attach(
346 &idsig_path,
347 0,
348 idsig_size,
349 /*direct_io*/ false,
350 /*writable*/ false,
351 )
352 .unwrap(),
Jooyung Han1b00bd22022-04-15 15:29:25 +0900353 |dev| loopdevice::detach(dev).unwrap(),
354 );
Jiyong Park86c9b082021-06-04 19:03:48 +0900355
356 let name = "loop_as_input";
357 // Run the program WITH the loop devices, not the regular files.
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900358 let ret =
359 enable_verity(apk_loop_device.deref(), idsig_loop_device.deref(), name, None).unwrap();
Jiyong Park86c9b082021-06-04 19:03:48 +0900360 let ret = scopeguard::guard(ret, |ret| {
361 loopdevice::detach(ret.data_device).unwrap();
362 loopdevice::detach(ret.hash_device).unwrap();
363 let dm = dm::DeviceMapper::new().unwrap();
364 dm.delete_device_deferred(name).unwrap();
365 });
366
367 let verity = fs::read(&ret.mapper_device).unwrap();
368 let original = fs::read(&apk_path).unwrap();
369 assert_eq!(verity.len(), original.len()); // fail fast
370 assert_eq!(verity.as_slice(), original.as_slice());
371 }
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900372
373 // test with custom roothash
Andrew Walbranf714eeb2022-11-30 11:15:56 +0000374 test!(correct_custom_roothash, ignore_if: should_skip());
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900375 fn correct_custom_roothash() {
376 let apk = include_bytes!("../testdata/test.apk");
377 let idsig = include_bytes!("../testdata/test.apk.idsig");
Alice Wang89cff012022-09-26 10:05:16 +0000378 let roothash = V4Signature::from_idsig_path("testdata/test.apk.idsig")
379 .unwrap()
380 .hashing_info
381 .raw_root_hash;
Jiyong Parka204c762021-09-14 17:27:12 +0900382 run_test_with_hash(
383 apk.as_ref(),
384 idsig.as_ref(),
385 "correct_custom_roothash",
386 Some(&roothash),
387 |ctx| {
388 let verity = fs::read(&ctx.result.mapper_device).unwrap();
389 let original = fs::read(&ctx.result.data_device).unwrap();
390 assert_eq!(verity.len(), original.len()); // fail fast
391 assert_eq!(verity.as_slice(), original.as_slice());
392 },
393 );
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900394 }
Andrew Walbranaa1efc42022-08-10 13:33:57 +0000395
Andrew Walbranf714eeb2022-11-30 11:15:56 +0000396 test!(verify_command);
Andrew Walbranaa1efc42022-08-10 13:33:57 +0000397 fn verify_command() {
398 // Check that the command parsing has been configured in a valid way.
399 clap_command().debug_assert();
400 }
Jiyong Park86c9b082021-06-04 19:03:48 +0900401}