blob: 50b6069bc7af03ab8e9fabeae5bc0d0861d5b7c1 [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
Jiyong Park86c9b082021-06-04 19:03:48 +090024use anyhow::{bail, Context, Result};
Alice Wang1bf3d782022-09-28 07:56:36 +000025use apkverify::{HashAlgorithm, V4Signature};
Andrew Walbranaa1efc42022-08-10 13:33:57 +000026use clap::{arg, Arg, ArgAction, Command};
Shikha Panwarb278b1c2022-10-14 12:38:32 +000027use dm::loopdevice;
Shikha Panwar414ea892022-10-12 13:45:52 +000028use dm::util;
29use dm::verity::{DmVerityHashAlgorithm, DmVerityTargetBuilder};
Inseob Kim217038e2021-11-25 11:15:06 +090030use itertools::Itertools;
Jiyong Park86c9b082021-06-04 19:03:48 +090031use std::fmt::Debug;
32use std::fs;
Jiyong Park86c9b082021-06-04 19:03:48 +090033use std::os::unix::fs::FileTypeExt;
34use std::path::{Path, PathBuf};
35
36fn main() -> Result<()> {
Andrew Walbranaa1efc42022-08-10 13:33:57 +000037 let matches = clap_command().get_matches();
Jiyong Park86c9b082021-06-04 19:03:48 +090038
Andrew Walbranaa1efc42022-08-10 13:33:57 +000039 let apks = matches.get_many::<String>("apk").unwrap();
Inseob Kim197748b2021-12-01 19:49:00 +090040 assert!(apks.len() % 4 == 0);
Inseob Kim217038e2021-11-25 11:15:06 +090041
Andrew Walbranaa1efc42022-08-10 13:33:57 +000042 let verbose = matches.get_flag("verbose");
Inseob Kim217038e2021-11-25 11:15:06 +090043
Inseob Kim197748b2021-12-01 19:49:00 +090044 for (apk, idsig, name, roothash) in apks.tuples() {
45 let roothash = if roothash != "none" {
46 Some(util::parse_hexstring(roothash).expect("failed to parse roothash"))
47 } else {
48 None
49 };
Inseob Kim217038e2021-11-25 11:15:06 +090050 let ret = enable_verity(apk, idsig, name, roothash.as_deref())?;
51 if verbose {
52 println!(
53 "data_device: {:?}, hash_device: {:?}, mapper_device: {:?}",
54 ret.data_device, ret.hash_device, ret.mapper_device
55 );
56 }
Jiyong Park99a35b82021-06-07 10:13:44 +090057 }
Jiyong Park86c9b082021-06-04 19:03:48 +090058 Ok(())
59}
60
Andrew Walbranaa1efc42022-08-10 13:33:57 +000061fn clap_command() -> Command {
62 Command::new("apkdmverity")
63 .about("Creates a dm-verity block device out of APK signed with APK signature scheme V4.")
64 .arg(
65 arg!(--apk ...
66 "Input APK file, idsig file, name of the block device, and root hash. \
67 The APK file must be signed using the APK signature scheme 4. The \
68 block device is created at \"/dev/mapper/<name>\".' root_hash is \
69 optional; idsig file's root hash will be used if specified as \"none\"."
70 )
71 .action(ArgAction::Append)
72 .value_names(&["apk_path", "idsig_path", "name", "root_hash"]),
73 )
74 .arg(
75 Arg::new("verbose")
76 .short('v')
77 .long("verbose")
78 .action(ArgAction::SetTrue)
79 .help("Shows verbose output"),
80 )
81}
82
Jiyong Park86c9b082021-06-04 19:03:48 +090083struct VerityResult {
84 data_device: PathBuf,
85 hash_device: PathBuf,
86 mapper_device: PathBuf,
87}
88
89const BLOCK_SIZE: u64 = 4096;
90
91// Makes a dm-verity block device out of `apk` and its accompanying `idsig` files.
Jiyong Parkbb4a9872021-09-06 15:59:21 +090092fn enable_verity<P: AsRef<Path> + Debug>(
93 apk: P,
94 idsig: P,
95 name: &str,
96 roothash: Option<&[u8]>,
97) -> Result<VerityResult> {
Jiyong Park86c9b082021-06-04 19:03:48 +090098 // Attach the apk file to a loop device if the apk file is a regular file. If not (i.e. block
99 // device), we only need to get the size and use the block device as it is.
100 let (data_device, apk_size) = if fs::metadata(&apk)?.file_type().is_block_device() {
101 (apk.as_ref().to_path_buf(), util::blkgetsize64(apk.as_ref())?)
102 } else {
103 let apk_size = fs::metadata(&apk)?.len();
104 if apk_size % BLOCK_SIZE != 0 {
105 bail!("The size of {:?} is not multiple of {}.", &apk, BLOCK_SIZE)
106 }
Jooyung Han1b00bd22022-04-15 15:29:25 +0900107 (
Shikha Panwar743454c2022-10-18 12:50:30 +0000108 loopdevice::attach(&apk, 0, apk_size, /*direct_io*/ true, /*writable*/ false)
Jooyung Han1b00bd22022-04-15 15:29:25 +0900109 .context("Failed to attach APK to a loop device")?,
110 apk_size,
111 )
Jiyong Park86c9b082021-06-04 19:03:48 +0900112 };
113
114 // Parse the idsig file to locate the merkle tree in it, then attach the file to a loop device
115 // with the offset so that the start of the merkle tree becomes the beginning of the loop
116 // device.
Alice Wang89cff012022-09-26 10:05:16 +0000117 let sig = V4Signature::from_idsig_path(&idsig)?;
Jiyong Park86c9b082021-06-04 19:03:48 +0900118 let offset = sig.merkle_tree_offset;
119 let size = sig.merkle_tree_size as u64;
Jooyung Han1b00bd22022-04-15 15:29:25 +0900120 // Due to unknown reason(b/191344832), we can't enable "direct IO" for the IDSIG file (backing
121 // the hash). For now we don't use "direct IO" but it seems OK since the IDSIG file is very
122 // small and the benefit of direct-IO would be negliable.
Shikha Panwar743454c2022-10-18 12:50:30 +0000123 let hash_device =
124 loopdevice::attach(&idsig, offset, size, /*direct_io*/ false, /*writable*/ false)
125 .context("Failed to attach idsig to a loop device")?;
Jiyong Park86c9b082021-06-04 19:03:48 +0900126
127 // Build a dm-verity target spec from the information from the idsig file. The apk and the
128 // idsig files are used as the data device and the hash device, respectively.
Shikha Panwar414ea892022-10-12 13:45:52 +0000129 let target = DmVerityTargetBuilder::default()
Jiyong Park86c9b082021-06-04 19:03:48 +0900130 .data_device(&data_device, apk_size)
131 .hash_device(&hash_device)
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900132 .root_digest(if let Some(roothash) = roothash {
133 roothash
134 } else {
135 &sig.hashing_info.raw_root_hash
136 })
Jiyong Park86c9b082021-06-04 19:03:48 +0900137 .hash_algorithm(match sig.hashing_info.hash_algorithm {
Shikha Panwar414ea892022-10-12 13:45:52 +0000138 HashAlgorithm::SHA256 => DmVerityHashAlgorithm::SHA256,
Jiyong Park86c9b082021-06-04 19:03:48 +0900139 })
140 .salt(&sig.hashing_info.salt)
141 .build()
142 .context(format!("Merkle tree in {:?} is not compatible with dm-verity", &idsig))?;
143
144 // Actually create a dm-verity block device using the spec.
145 let dm = dm::DeviceMapper::new()?;
146 let mapper_device =
Shikha Panwar414ea892022-10-12 13:45:52 +0000147 dm.create_verity_device(name, &target).context("Failed to create dm-verity device")?;
Jiyong Park86c9b082021-06-04 19:03:48 +0900148
149 Ok(VerityResult { data_device, hash_device, mapper_device })
150}
151
152#[cfg(test)]
153mod tests {
154 use crate::*;
Alice Wang89cff012022-09-26 10:05:16 +0000155 use std::fs::{File, OpenOptions};
156 use std::io::Write;
Jiyong Park86c9b082021-06-04 19:03:48 +0900157 use std::os::unix::fs::FileExt;
158
159 struct TestContext<'a> {
160 data_backing_file: &'a Path,
161 hash_backing_file: &'a Path,
162 result: &'a VerityResult,
163 }
164
Jiyong Parkd17ff4b2021-07-15 12:32:25 +0900165 // On Android, skip the test on devices that doesn't have the virt APEX
166 // (b/193612136)
167 #[cfg(target_os = "android")]
168 fn should_skip() -> bool {
169 !Path::new("/apex/com.android.virt").exists()
170 }
171 #[cfg(not(target_os = "android"))]
172 fn should_skip() -> bool {
173 false
174 }
175
Jiyong Park86c9b082021-06-04 19:03:48 +0900176 fn create_block_aligned_file(path: &Path, data: &[u8]) {
Chris Wailes9b866f02022-11-16 15:17:16 -0800177 let mut f = File::create(path).unwrap();
Jiyong Park86c9b082021-06-04 19:03:48 +0900178 f.write_all(data).unwrap();
179
180 // Add padding so that the size of the file is multiple of 4096.
181 let aligned_size = (data.len() as u64 + BLOCK_SIZE - 1) & !(BLOCK_SIZE - 1);
182 let padding = aligned_size - data.len() as u64;
183 f.write_all(vec![0; padding as usize].as_slice()).unwrap();
184 }
185
186 fn prepare_inputs(test_dir: &Path, apk: &[u8], idsig: &[u8]) -> (PathBuf, PathBuf) {
187 let apk_path = test_dir.join("test.apk");
188 let idsig_path = test_dir.join("test.apk.idsig");
189 create_block_aligned_file(&apk_path, apk);
190 create_block_aligned_file(&idsig_path, idsig);
191 (apk_path, idsig_path)
192 }
193
194 fn run_test(apk: &[u8], idsig: &[u8], name: &str, check: fn(TestContext)) {
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900195 run_test_with_hash(apk, idsig, name, None, check);
196 }
197
198 fn run_test_with_hash(
199 apk: &[u8],
200 idsig: &[u8],
201 name: &str,
202 roothash: Option<&[u8]>,
203 check: fn(TestContext),
204 ) {
Jiyong Parkd17ff4b2021-07-15 12:32:25 +0900205 if should_skip() {
206 return;
207 }
Jiyong Park86c9b082021-06-04 19:03:48 +0900208 let test_dir = tempfile::TempDir::new().unwrap();
Chris Wailes68c39f82021-07-27 16:03:44 -0700209 let (apk_path, idsig_path) = prepare_inputs(test_dir.path(), apk, idsig);
Jiyong Park86c9b082021-06-04 19:03:48 +0900210
211 // Run the program and register clean-ups.
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900212 let ret = enable_verity(&apk_path, &idsig_path, name, roothash).unwrap();
Jiyong Park86c9b082021-06-04 19:03:48 +0900213 let ret = scopeguard::guard(ret, |ret| {
214 loopdevice::detach(ret.data_device).unwrap();
215 loopdevice::detach(ret.hash_device).unwrap();
216 let dm = dm::DeviceMapper::new().unwrap();
217 dm.delete_device_deferred(name).unwrap();
218 });
219
220 check(TestContext {
221 data_backing_file: &apk_path,
222 hash_backing_file: &idsig_path,
223 result: &ret,
224 });
225 }
226
227 #[test]
228 fn correct_inputs() {
229 let apk = include_bytes!("../testdata/test.apk");
230 let idsig = include_bytes!("../testdata/test.apk.idsig");
231 run_test(apk.as_ref(), idsig.as_ref(), "correct", |ctx| {
232 let verity = fs::read(&ctx.result.mapper_device).unwrap();
233 let original = fs::read(&ctx.result.data_device).unwrap();
234 assert_eq!(verity.len(), original.len()); // fail fast
235 assert_eq!(verity.as_slice(), original.as_slice());
236 });
237 }
238
239 // A single byte change in the APK file causes an IO error
240 #[test]
241 fn incorrect_apk() {
242 let apk = include_bytes!("../testdata/test.apk");
243 let idsig = include_bytes!("../testdata/test.apk.idsig");
244
245 let mut modified_apk = Vec::new();
246 modified_apk.extend_from_slice(apk);
247 if let Some(byte) = modified_apk.get_mut(100) {
248 *byte = 1;
249 }
250
251 run_test(modified_apk.as_slice(), idsig.as_ref(), "incorrect_apk", |ctx| {
Jiyong Park7b08c572021-09-14 07:28:56 +0900252 fs::read(&ctx.result.mapper_device).expect_err("Should fail");
Jiyong Park86c9b082021-06-04 19:03:48 +0900253 });
254 }
255
256 // A single byte change in the merkle tree also causes an IO error
257 #[test]
258 fn incorrect_merkle_tree() {
259 let apk = include_bytes!("../testdata/test.apk");
260 let idsig = include_bytes!("../testdata/test.apk.idsig");
261
262 // Make a single-byte change to the merkle tree
Alice Wang89cff012022-09-26 10:05:16 +0000263 let offset = V4Signature::from_idsig_path("testdata/test.apk.idsig")
264 .unwrap()
265 .merkle_tree_offset as usize;
Jiyong Park86c9b082021-06-04 19:03:48 +0900266
267 let mut modified_idsig = Vec::new();
268 modified_idsig.extend_from_slice(idsig);
269 if let Some(byte) = modified_idsig.get_mut(offset + 10) {
270 *byte = 1;
271 }
272
273 run_test(apk.as_ref(), modified_idsig.as_slice(), "incorrect_merkle_tree", |ctx| {
Jiyong Park7b08c572021-09-14 07:28:56 +0900274 fs::read(&ctx.result.mapper_device).expect_err("Should fail");
Jiyong Park86c9b082021-06-04 19:03:48 +0900275 });
276 }
277
278 // APK is not altered when the verity device is created, but later modified. IO error should
279 // occur when trying to read the data around the modified location. This is the main scenario
280 // that we'd like to protect.
281 #[test]
282 fn tampered_apk() {
283 let apk = include_bytes!("../testdata/test.apk");
284 let idsig = include_bytes!("../testdata/test.apk.idsig");
285
286 run_test(apk.as_ref(), idsig.as_ref(), "tampered_apk", |ctx| {
287 // At this moment, the verity device is created. Then let's change 10 bytes in the
288 // backing data file.
289 const MODIFIED_OFFSET: u64 = 10000;
290 let f = OpenOptions::new().read(true).write(true).open(ctx.data_backing_file).unwrap();
291 f.write_at(&[0, 1], MODIFIED_OFFSET).unwrap();
292
293 // Read around the modified location causes an error
294 let f = File::open(&ctx.result.mapper_device).unwrap();
295 let mut buf = vec![0; 10]; // just read 10 bytes
Jiyong Park7b08c572021-09-14 07:28:56 +0900296 f.read_at(&mut buf, MODIFIED_OFFSET).expect_err("Should fail");
Jiyong Park86c9b082021-06-04 19:03:48 +0900297 });
298 }
299
300 // idsig file is not alread when the verity device is created, but later modified. Unlike to
301 // the APK case, this doesn't occur IO error because the merkle tree is already cached.
302 #[test]
303 fn tampered_idsig() {
304 let apk = include_bytes!("../testdata/test.apk");
305 let idsig = include_bytes!("../testdata/test.apk.idsig");
306 run_test(apk.as_ref(), idsig.as_ref(), "tampered_idsig", |ctx| {
307 // Change 10 bytes in the merkle tree.
308 let f = OpenOptions::new().read(true).write(true).open(ctx.hash_backing_file).unwrap();
309 f.write_at(&[0, 10], 100).unwrap();
310
311 let verity = fs::read(&ctx.result.mapper_device).unwrap();
312 let original = fs::read(&ctx.result.data_device).unwrap();
313 assert_eq!(verity.len(), original.len());
314 assert_eq!(verity.as_slice(), original.as_slice());
315 });
316 }
317
318 // test if both files are already block devices
319 #[test]
320 fn inputs_are_block_devices() {
Jiyong Parkd17ff4b2021-07-15 12:32:25 +0900321 if should_skip() {
322 return;
323 }
324
Jiyong Park86c9b082021-06-04 19:03:48 +0900325 use std::ops::Deref;
326 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
374 #[test]
375 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
396 #[test]
397 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}