blob: dbf31319491231b1d2874c54515cdecfaffa4d45 [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 +090024mod dm;
25mod loopdevice;
26mod util;
27
Jiyong Park86c9b082021-06-04 19:03:48 +090028use anyhow::{bail, Context, Result};
29use clap::{App, Arg};
Jiyong Parkbde94ab2021-08-11 18:32:01 +090030use idsig::{HashAlgorithm, V4Signature};
Inseob Kim217038e2021-11-25 11:15:06 +090031use itertools::Itertools;
Jiyong Park86c9b082021-06-04 19:03:48 +090032use std::fmt::Debug;
33use std::fs;
34use std::fs::File;
35use std::os::unix::fs::FileTypeExt;
36use std::path::{Path, PathBuf};
37
38fn main() -> Result<()> {
Jooyung Han7ce2e532021-06-16 16:52:02 +090039 let matches = App::new("apkdmverity")
Jiyong Park86c9b082021-06-04 19:03:48 +090040 .about("Creates a dm-verity block device out of APK signed with APK signature scheme V4.")
Inseob Kim217038e2021-11-25 11:15:06 +090041 .arg(Arg::from_usage(
Inseob Kim197748b2021-12-01 19:49:00 +090042 "--apk... <apk_path> <idsig_path> <name> <root_hash> \
43 'Input APK file, idsig file, name of the block device, and root hash. \
44 The APK file must be signed using the APK signature scheme 4. The \
45 block device is created at \"/dev/mapper/<name>\".' root_hash is \
46 optional; idsig file's root hash will be used if specified as \"none\"."
47 ))
Jiyong Park99a35b82021-06-07 10:13:44 +090048 .arg(Arg::with_name("verbose").short("v").long("verbose").help("Shows verbose output"))
Jiyong Park86c9b082021-06-04 19:03:48 +090049 .get_matches();
50
Inseob Kim217038e2021-11-25 11:15:06 +090051 let apks = matches.values_of("apk").unwrap();
Inseob Kim197748b2021-12-01 19:49:00 +090052 assert!(apks.len() % 4 == 0);
Inseob Kim217038e2021-11-25 11:15:06 +090053
54 let verbose = matches.is_present("verbose");
55
Inseob Kim197748b2021-12-01 19:49:00 +090056 for (apk, idsig, name, roothash) in apks.tuples() {
57 let roothash = if roothash != "none" {
58 Some(util::parse_hexstring(roothash).expect("failed to parse roothash"))
59 } else {
60 None
61 };
Inseob Kim217038e2021-11-25 11:15:06 +090062 let ret = enable_verity(apk, idsig, name, roothash.as_deref())?;
63 if verbose {
64 println!(
65 "data_device: {:?}, hash_device: {:?}, mapper_device: {:?}",
66 ret.data_device, ret.hash_device, ret.mapper_device
67 );
68 }
Jiyong Park99a35b82021-06-07 10:13:44 +090069 }
Jiyong Park86c9b082021-06-04 19:03:48 +090070 Ok(())
71}
72
73struct VerityResult {
74 data_device: PathBuf,
75 hash_device: PathBuf,
76 mapper_device: PathBuf,
77}
78
79const BLOCK_SIZE: u64 = 4096;
80
81// Makes a dm-verity block device out of `apk` and its accompanying `idsig` files.
Jiyong Parkbb4a9872021-09-06 15:59:21 +090082fn enable_verity<P: AsRef<Path> + Debug>(
83 apk: P,
84 idsig: P,
85 name: &str,
86 roothash: Option<&[u8]>,
87) -> Result<VerityResult> {
Jiyong Park86c9b082021-06-04 19:03:48 +090088 // Attach the apk file to a loop device if the apk file is a regular file. If not (i.e. block
89 // device), we only need to get the size and use the block device as it is.
90 let (data_device, apk_size) = if fs::metadata(&apk)?.file_type().is_block_device() {
91 (apk.as_ref().to_path_buf(), util::blkgetsize64(apk.as_ref())?)
92 } else {
93 let apk_size = fs::metadata(&apk)?.len();
94 if apk_size % BLOCK_SIZE != 0 {
95 bail!("The size of {:?} is not multiple of {}.", &apk, BLOCK_SIZE)
96 }
97 (loopdevice::attach(&apk, 0, apk_size)?, apk_size)
98 };
99
100 // Parse the idsig file to locate the merkle tree in it, then attach the file to a loop device
101 // with the offset so that the start of the merkle tree becomes the beginning of the loop
102 // device.
Jiyong Park0553ff22021-07-15 12:25:36 +0900103 let sig = V4Signature::from(
104 File::open(&idsig).context(format!("Failed to open idsig file {:?}", &idsig))?,
105 )?;
Jiyong Park86c9b082021-06-04 19:03:48 +0900106 let offset = sig.merkle_tree_offset;
107 let size = sig.merkle_tree_size as u64;
108 let hash_device = loopdevice::attach(&idsig, offset, size)?;
109
110 // Build a dm-verity target spec from the information from the idsig file. The apk and the
111 // idsig files are used as the data device and the hash device, respectively.
112 let target = dm::DmVerityTargetBuilder::default()
113 .data_device(&data_device, apk_size)
114 .hash_device(&hash_device)
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900115 .root_digest(if let Some(roothash) = roothash {
116 roothash
117 } else {
118 &sig.hashing_info.raw_root_hash
119 })
Jiyong Park86c9b082021-06-04 19:03:48 +0900120 .hash_algorithm(match sig.hashing_info.hash_algorithm {
Jiyong Parkbde94ab2021-08-11 18:32:01 +0900121 HashAlgorithm::SHA256 => dm::DmVerityHashAlgorithm::SHA256,
Jiyong Park86c9b082021-06-04 19:03:48 +0900122 })
123 .salt(&sig.hashing_info.salt)
124 .build()
125 .context(format!("Merkle tree in {:?} is not compatible with dm-verity", &idsig))?;
126
127 // Actually create a dm-verity block device using the spec.
128 let dm = dm::DeviceMapper::new()?;
129 let mapper_device =
Chris Wailes68c39f82021-07-27 16:03:44 -0700130 dm.create_device(name, &target).context("Failed to create dm-verity device")?;
Jiyong Park86c9b082021-06-04 19:03:48 +0900131
132 Ok(VerityResult { data_device, hash_device, mapper_device })
133}
134
135#[cfg(test)]
136mod tests {
137 use crate::*;
138 use std::fs::OpenOptions;
139 use std::io::{Cursor, Write};
140 use std::os::unix::fs::FileExt;
141
142 struct TestContext<'a> {
143 data_backing_file: &'a Path,
144 hash_backing_file: &'a Path,
145 result: &'a VerityResult,
146 }
147
Jiyong Parkd17ff4b2021-07-15 12:32:25 +0900148 // On Android, skip the test on devices that doesn't have the virt APEX
149 // (b/193612136)
150 #[cfg(target_os = "android")]
151 fn should_skip() -> bool {
152 !Path::new("/apex/com.android.virt").exists()
153 }
154 #[cfg(not(target_os = "android"))]
155 fn should_skip() -> bool {
156 false
157 }
158
Jiyong Park86c9b082021-06-04 19:03:48 +0900159 fn create_block_aligned_file(path: &Path, data: &[u8]) {
160 let mut f = File::create(&path).unwrap();
161 f.write_all(data).unwrap();
162
163 // Add padding so that the size of the file is multiple of 4096.
164 let aligned_size = (data.len() as u64 + BLOCK_SIZE - 1) & !(BLOCK_SIZE - 1);
165 let padding = aligned_size - data.len() as u64;
166 f.write_all(vec![0; padding as usize].as_slice()).unwrap();
167 }
168
169 fn prepare_inputs(test_dir: &Path, apk: &[u8], idsig: &[u8]) -> (PathBuf, PathBuf) {
170 let apk_path = test_dir.join("test.apk");
171 let idsig_path = test_dir.join("test.apk.idsig");
172 create_block_aligned_file(&apk_path, apk);
173 create_block_aligned_file(&idsig_path, idsig);
174 (apk_path, idsig_path)
175 }
176
177 fn run_test(apk: &[u8], idsig: &[u8], name: &str, check: fn(TestContext)) {
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900178 run_test_with_hash(apk, idsig, name, None, check);
179 }
180
181 fn run_test_with_hash(
182 apk: &[u8],
183 idsig: &[u8],
184 name: &str,
185 roothash: Option<&[u8]>,
186 check: fn(TestContext),
187 ) {
Jiyong Parkd17ff4b2021-07-15 12:32:25 +0900188 if should_skip() {
189 return;
190 }
Jiyong Park86c9b082021-06-04 19:03:48 +0900191 let test_dir = tempfile::TempDir::new().unwrap();
Chris Wailes68c39f82021-07-27 16:03:44 -0700192 let (apk_path, idsig_path) = prepare_inputs(test_dir.path(), apk, idsig);
Jiyong Park86c9b082021-06-04 19:03:48 +0900193
194 // Run the program and register clean-ups.
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900195 let ret = enable_verity(&apk_path, &idsig_path, name, roothash).unwrap();
Jiyong Park86c9b082021-06-04 19:03:48 +0900196 let ret = scopeguard::guard(ret, |ret| {
197 loopdevice::detach(ret.data_device).unwrap();
198 loopdevice::detach(ret.hash_device).unwrap();
199 let dm = dm::DeviceMapper::new().unwrap();
200 dm.delete_device_deferred(name).unwrap();
201 });
202
203 check(TestContext {
204 data_backing_file: &apk_path,
205 hash_backing_file: &idsig_path,
206 result: &ret,
207 });
208 }
209
210 #[test]
211 fn correct_inputs() {
212 let apk = include_bytes!("../testdata/test.apk");
213 let idsig = include_bytes!("../testdata/test.apk.idsig");
214 run_test(apk.as_ref(), idsig.as_ref(), "correct", |ctx| {
215 let verity = fs::read(&ctx.result.mapper_device).unwrap();
216 let original = fs::read(&ctx.result.data_device).unwrap();
217 assert_eq!(verity.len(), original.len()); // fail fast
218 assert_eq!(verity.as_slice(), original.as_slice());
219 });
220 }
221
222 // A single byte change in the APK file causes an IO error
223 #[test]
224 fn incorrect_apk() {
225 let apk = include_bytes!("../testdata/test.apk");
226 let idsig = include_bytes!("../testdata/test.apk.idsig");
227
228 let mut modified_apk = Vec::new();
229 modified_apk.extend_from_slice(apk);
230 if let Some(byte) = modified_apk.get_mut(100) {
231 *byte = 1;
232 }
233
234 run_test(modified_apk.as_slice(), idsig.as_ref(), "incorrect_apk", |ctx| {
Jiyong Park7b08c572021-09-14 07:28:56 +0900235 fs::read(&ctx.result.mapper_device).expect_err("Should fail");
Jiyong Park86c9b082021-06-04 19:03:48 +0900236 });
237 }
238
239 // A single byte change in the merkle tree also causes an IO error
240 #[test]
241 fn incorrect_merkle_tree() {
242 let apk = include_bytes!("../testdata/test.apk");
243 let idsig = include_bytes!("../testdata/test.apk.idsig");
244
245 // Make a single-byte change to the merkle tree
246 let offset = V4Signature::from(Cursor::new(&idsig)).unwrap().merkle_tree_offset as usize;
247
248 let mut modified_idsig = Vec::new();
249 modified_idsig.extend_from_slice(idsig);
250 if let Some(byte) = modified_idsig.get_mut(offset + 10) {
251 *byte = 1;
252 }
253
254 run_test(apk.as_ref(), modified_idsig.as_slice(), "incorrect_merkle_tree", |ctx| {
Jiyong Park7b08c572021-09-14 07:28:56 +0900255 fs::read(&ctx.result.mapper_device).expect_err("Should fail");
Jiyong Park86c9b082021-06-04 19:03:48 +0900256 });
257 }
258
259 // APK is not altered when the verity device is created, but later modified. IO error should
260 // occur when trying to read the data around the modified location. This is the main scenario
261 // that we'd like to protect.
262 #[test]
263 fn tampered_apk() {
264 let apk = include_bytes!("../testdata/test.apk");
265 let idsig = include_bytes!("../testdata/test.apk.idsig");
266
267 run_test(apk.as_ref(), idsig.as_ref(), "tampered_apk", |ctx| {
268 // At this moment, the verity device is created. Then let's change 10 bytes in the
269 // backing data file.
270 const MODIFIED_OFFSET: u64 = 10000;
271 let f = OpenOptions::new().read(true).write(true).open(ctx.data_backing_file).unwrap();
272 f.write_at(&[0, 1], MODIFIED_OFFSET).unwrap();
273
274 // Read around the modified location causes an error
275 let f = File::open(&ctx.result.mapper_device).unwrap();
276 let mut buf = vec![0; 10]; // just read 10 bytes
Jiyong Park7b08c572021-09-14 07:28:56 +0900277 f.read_at(&mut buf, MODIFIED_OFFSET).expect_err("Should fail");
Jiyong Park86c9b082021-06-04 19:03:48 +0900278 });
279 }
280
281 // idsig file is not alread when the verity device is created, but later modified. Unlike to
282 // the APK case, this doesn't occur IO error because the merkle tree is already cached.
283 #[test]
284 fn tampered_idsig() {
285 let apk = include_bytes!("../testdata/test.apk");
286 let idsig = include_bytes!("../testdata/test.apk.idsig");
287 run_test(apk.as_ref(), idsig.as_ref(), "tampered_idsig", |ctx| {
288 // Change 10 bytes in the merkle tree.
289 let f = OpenOptions::new().read(true).write(true).open(ctx.hash_backing_file).unwrap();
290 f.write_at(&[0, 10], 100).unwrap();
291
292 let verity = fs::read(&ctx.result.mapper_device).unwrap();
293 let original = fs::read(&ctx.result.data_device).unwrap();
294 assert_eq!(verity.len(), original.len());
295 assert_eq!(verity.as_slice(), original.as_slice());
296 });
297 }
298
299 // test if both files are already block devices
300 #[test]
301 fn inputs_are_block_devices() {
Jiyong Parkd17ff4b2021-07-15 12:32:25 +0900302 if should_skip() {
303 return;
304 }
305
Jiyong Park86c9b082021-06-04 19:03:48 +0900306 use std::ops::Deref;
307 let apk = include_bytes!("../testdata/test.apk");
308 let idsig = include_bytes!("../testdata/test.apk.idsig");
309
310 let test_dir = tempfile::TempDir::new().unwrap();
Chris Wailes68c39f82021-07-27 16:03:44 -0700311 let (apk_path, idsig_path) = prepare_inputs(test_dir.path(), apk, idsig);
Jiyong Park86c9b082021-06-04 19:03:48 +0900312
313 // attach the files to loop devices to make them block devices
314 let apk_size = fs::metadata(&apk_path).unwrap().len();
315 let idsig_size = fs::metadata(&idsig_path).unwrap().len();
316
317 // Note that apk_loop_device is not detatched. This is because, when the apk file is
318 // already a block device, `enable_verity` uses the block device as it is. The detatching
319 // of the data device is done in the scopeguard for the return value of `enable_verity`
320 // below. Only the idsig_loop_device needs detatching.
321 let apk_loop_device = loopdevice::attach(&apk_path, 0, apk_size).unwrap();
322 let idsig_loop_device =
323 scopeguard::guard(loopdevice::attach(&idsig_path, 0, idsig_size).unwrap(), |dev| {
324 loopdevice::detach(dev).unwrap()
325 });
326
327 let name = "loop_as_input";
328 // Run the program WITH the loop devices, not the regular files.
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900329 let ret =
330 enable_verity(apk_loop_device.deref(), idsig_loop_device.deref(), name, None).unwrap();
Jiyong Park86c9b082021-06-04 19:03:48 +0900331 let ret = scopeguard::guard(ret, |ret| {
332 loopdevice::detach(ret.data_device).unwrap();
333 loopdevice::detach(ret.hash_device).unwrap();
334 let dm = dm::DeviceMapper::new().unwrap();
335 dm.delete_device_deferred(name).unwrap();
336 });
337
338 let verity = fs::read(&ret.mapper_device).unwrap();
339 let original = fs::read(&apk_path).unwrap();
340 assert_eq!(verity.len(), original.len()); // fail fast
341 assert_eq!(verity.as_slice(), original.as_slice());
342 }
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900343
344 // test with custom roothash
345 #[test]
346 fn correct_custom_roothash() {
347 let apk = include_bytes!("../testdata/test.apk");
348 let idsig = include_bytes!("../testdata/test.apk.idsig");
349 let roothash = V4Signature::from(Cursor::new(&idsig)).unwrap().hashing_info.raw_root_hash;
Jiyong Parka204c762021-09-14 17:27:12 +0900350 run_test_with_hash(
351 apk.as_ref(),
352 idsig.as_ref(),
353 "correct_custom_roothash",
354 Some(&roothash),
355 |ctx| {
356 let verity = fs::read(&ctx.result.mapper_device).unwrap();
357 let original = fs::read(&ctx.result.data_device).unwrap();
358 assert_eq!(verity.len(), original.len()); // fail fast
359 assert_eq!(verity.as_slice(), original.as_slice());
360 },
361 );
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900362 }
Jiyong Park86c9b082021-06-04 19:03:48 +0900363}