blob: cabeb3522dbb02b5a7b00c72312d4ea36e7c64e1 [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};
Jiyong Parkbb4a9872021-09-06 15:59:21 +090031use rustutils::system_properties;
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.")
41 .arg(
42 Arg::with_name("apk")
43 .help("Input APK file. Must be signed using the APK signature scheme V4.")
44 .required(true),
45 )
46 .arg(
47 Arg::with_name("idsig")
48 .help("The idsig file having the merkle tree and the signing info.")
49 .required(true),
50 )
51 .arg(
52 Arg::with_name("name")
53 .help(
54 "Name of the dm-verity block device. The block device is created at \
55 \"/dev/mapper/<name>\".",
56 )
57 .required(true),
58 )
Jiyong Park99a35b82021-06-07 10:13:44 +090059 .arg(Arg::with_name("verbose").short("v").long("verbose").help("Shows verbose output"))
Jiyong Park86c9b082021-06-04 19:03:48 +090060 .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();
Jooyung Han6606ce32021-09-08 14:31:39 +090065 let roothash = if let Ok(val) = system_properties::read("microdroid_manager.apk_root_hash") {
Jiyong Parkbb4a9872021-09-06 15:59:21 +090066 Some(util::parse_hexstring(&val)?)
67 } else {
68 // This failure is not an error. We will use the roothash read from the idsig file.
69 None
70 };
71 let ret = enable_verity(apk, idsig, name, roothash.as_deref())?;
Jiyong Park99a35b82021-06-07 10:13:44 +090072 if matches.is_present("verbose") {
73 println!(
74 "data_device: {:?}, hash_device: {:?}, mapper_device: {:?}",
75 ret.data_device, ret.hash_device, ret.mapper_device
76 );
77 }
Jiyong Park86c9b082021-06-04 19:03:48 +090078 Ok(())
79}
80
81struct VerityResult {
82 data_device: PathBuf,
83 hash_device: PathBuf,
84 mapper_device: PathBuf,
85}
86
87const BLOCK_SIZE: u64 = 4096;
88
89// Makes a dm-verity block device out of `apk` and its accompanying `idsig` files.
Jiyong Parkbb4a9872021-09-06 15:59:21 +090090fn enable_verity<P: AsRef<Path> + Debug>(
91 apk: P,
92 idsig: P,
93 name: &str,
94 roothash: Option<&[u8]>,
95) -> Result<VerityResult> {
Jiyong Park86c9b082021-06-04 19:03:48 +090096 // Attach the apk file to a loop device if the apk file is a regular file. If not (i.e. block
97 // device), we only need to get the size and use the block device as it is.
98 let (data_device, apk_size) = if fs::metadata(&apk)?.file_type().is_block_device() {
99 (apk.as_ref().to_path_buf(), util::blkgetsize64(apk.as_ref())?)
100 } else {
101 let apk_size = fs::metadata(&apk)?.len();
102 if apk_size % BLOCK_SIZE != 0 {
103 bail!("The size of {:?} is not multiple of {}.", &apk, BLOCK_SIZE)
104 }
105 (loopdevice::attach(&apk, 0, apk_size)?, apk_size)
106 };
107
108 // Parse the idsig file to locate the merkle tree in it, then attach the file to a loop device
109 // with the offset so that the start of the merkle tree becomes the beginning of the loop
110 // device.
Jiyong Park0553ff22021-07-15 12:25:36 +0900111 let sig = V4Signature::from(
112 File::open(&idsig).context(format!("Failed to open idsig file {:?}", &idsig))?,
113 )?;
Jiyong Park86c9b082021-06-04 19:03:48 +0900114 let offset = sig.merkle_tree_offset;
115 let size = sig.merkle_tree_size as u64;
116 let hash_device = loopdevice::attach(&idsig, offset, size)?;
117
118 // Build a dm-verity target spec from the information from the idsig file. The apk and the
119 // idsig files are used as the data device and the hash device, respectively.
120 let target = dm::DmVerityTargetBuilder::default()
121 .data_device(&data_device, apk_size)
122 .hash_device(&hash_device)
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900123 .root_digest(if let Some(roothash) = roothash {
124 roothash
125 } else {
126 &sig.hashing_info.raw_root_hash
127 })
Jiyong Park86c9b082021-06-04 19:03:48 +0900128 .hash_algorithm(match sig.hashing_info.hash_algorithm {
Jiyong Parkbde94ab2021-08-11 18:32:01 +0900129 HashAlgorithm::SHA256 => dm::DmVerityHashAlgorithm::SHA256,
Jiyong Park86c9b082021-06-04 19:03:48 +0900130 })
131 .salt(&sig.hashing_info.salt)
132 .build()
133 .context(format!("Merkle tree in {:?} is not compatible with dm-verity", &idsig))?;
134
135 // Actually create a dm-verity block device using the spec.
136 let dm = dm::DeviceMapper::new()?;
137 let mapper_device =
Chris Wailes68c39f82021-07-27 16:03:44 -0700138 dm.create_device(name, &target).context("Failed to create dm-verity device")?;
Jiyong Park86c9b082021-06-04 19:03:48 +0900139
140 Ok(VerityResult { data_device, hash_device, mapper_device })
141}
142
143#[cfg(test)]
144mod tests {
145 use crate::*;
146 use std::fs::OpenOptions;
147 use std::io::{Cursor, Write};
148 use std::os::unix::fs::FileExt;
149
150 struct TestContext<'a> {
151 data_backing_file: &'a Path,
152 hash_backing_file: &'a Path,
153 result: &'a VerityResult,
154 }
155
Jiyong Parkd17ff4b2021-07-15 12:32:25 +0900156 // On Android, skip the test on devices that doesn't have the virt APEX
157 // (b/193612136)
158 #[cfg(target_os = "android")]
159 fn should_skip() -> bool {
160 !Path::new("/apex/com.android.virt").exists()
161 }
162 #[cfg(not(target_os = "android"))]
163 fn should_skip() -> bool {
164 false
165 }
166
Jiyong Park86c9b082021-06-04 19:03:48 +0900167 fn create_block_aligned_file(path: &Path, data: &[u8]) {
168 let mut f = File::create(&path).unwrap();
169 f.write_all(data).unwrap();
170
171 // Add padding so that the size of the file is multiple of 4096.
172 let aligned_size = (data.len() as u64 + BLOCK_SIZE - 1) & !(BLOCK_SIZE - 1);
173 let padding = aligned_size - data.len() as u64;
174 f.write_all(vec![0; padding as usize].as_slice()).unwrap();
175 }
176
177 fn prepare_inputs(test_dir: &Path, apk: &[u8], idsig: &[u8]) -> (PathBuf, PathBuf) {
178 let apk_path = test_dir.join("test.apk");
179 let idsig_path = test_dir.join("test.apk.idsig");
180 create_block_aligned_file(&apk_path, apk);
181 create_block_aligned_file(&idsig_path, idsig);
182 (apk_path, idsig_path)
183 }
184
185 fn run_test(apk: &[u8], idsig: &[u8], name: &str, check: fn(TestContext)) {
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900186 run_test_with_hash(apk, idsig, name, None, check);
187 }
188
189 fn run_test_with_hash(
190 apk: &[u8],
191 idsig: &[u8],
192 name: &str,
193 roothash: Option<&[u8]>,
194 check: fn(TestContext),
195 ) {
Jiyong Parkd17ff4b2021-07-15 12:32:25 +0900196 if should_skip() {
197 return;
198 }
Jiyong Park86c9b082021-06-04 19:03:48 +0900199 let test_dir = tempfile::TempDir::new().unwrap();
Chris Wailes68c39f82021-07-27 16:03:44 -0700200 let (apk_path, idsig_path) = prepare_inputs(test_dir.path(), apk, idsig);
Jiyong Park86c9b082021-06-04 19:03:48 +0900201
202 // Run the program and register clean-ups.
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900203 let ret = enable_verity(&apk_path, &idsig_path, name, roothash).unwrap();
Jiyong Park86c9b082021-06-04 19:03:48 +0900204 let ret = scopeguard::guard(ret, |ret| {
205 loopdevice::detach(ret.data_device).unwrap();
206 loopdevice::detach(ret.hash_device).unwrap();
207 let dm = dm::DeviceMapper::new().unwrap();
208 dm.delete_device_deferred(name).unwrap();
209 });
210
211 check(TestContext {
212 data_backing_file: &apk_path,
213 hash_backing_file: &idsig_path,
214 result: &ret,
215 });
216 }
217
218 #[test]
219 fn correct_inputs() {
220 let apk = include_bytes!("../testdata/test.apk");
221 let idsig = include_bytes!("../testdata/test.apk.idsig");
222 run_test(apk.as_ref(), idsig.as_ref(), "correct", |ctx| {
223 let verity = fs::read(&ctx.result.mapper_device).unwrap();
224 let original = fs::read(&ctx.result.data_device).unwrap();
225 assert_eq!(verity.len(), original.len()); // fail fast
226 assert_eq!(verity.as_slice(), original.as_slice());
227 });
228 }
229
230 // A single byte change in the APK file causes an IO error
231 #[test]
232 fn incorrect_apk() {
233 let apk = include_bytes!("../testdata/test.apk");
234 let idsig = include_bytes!("../testdata/test.apk.idsig");
235
236 let mut modified_apk = Vec::new();
237 modified_apk.extend_from_slice(apk);
238 if let Some(byte) = modified_apk.get_mut(100) {
239 *byte = 1;
240 }
241
242 run_test(modified_apk.as_slice(), idsig.as_ref(), "incorrect_apk", |ctx| {
243 let ret = fs::read(&ctx.result.mapper_device).map_err(|e| e.kind());
244 assert_eq!(ret, Err(std::io::ErrorKind::Other));
245 });
246 }
247
248 // A single byte change in the merkle tree also causes an IO error
249 #[test]
250 fn incorrect_merkle_tree() {
251 let apk = include_bytes!("../testdata/test.apk");
252 let idsig = include_bytes!("../testdata/test.apk.idsig");
253
254 // Make a single-byte change to the merkle tree
255 let offset = V4Signature::from(Cursor::new(&idsig)).unwrap().merkle_tree_offset as usize;
256
257 let mut modified_idsig = Vec::new();
258 modified_idsig.extend_from_slice(idsig);
259 if let Some(byte) = modified_idsig.get_mut(offset + 10) {
260 *byte = 1;
261 }
262
263 run_test(apk.as_ref(), modified_idsig.as_slice(), "incorrect_merkle_tree", |ctx| {
264 let ret = fs::read(&ctx.result.mapper_device).map_err(|e| e.kind());
265 assert_eq!(ret, Err(std::io::ErrorKind::Other));
266 });
267 }
268
269 // APK is not altered when the verity device is created, but later modified. IO error should
270 // occur when trying to read the data around the modified location. This is the main scenario
271 // that we'd like to protect.
272 #[test]
273 fn tampered_apk() {
274 let apk = include_bytes!("../testdata/test.apk");
275 let idsig = include_bytes!("../testdata/test.apk.idsig");
276
277 run_test(apk.as_ref(), idsig.as_ref(), "tampered_apk", |ctx| {
278 // At this moment, the verity device is created. Then let's change 10 bytes in the
279 // backing data file.
280 const MODIFIED_OFFSET: u64 = 10000;
281 let f = OpenOptions::new().read(true).write(true).open(ctx.data_backing_file).unwrap();
282 f.write_at(&[0, 1], MODIFIED_OFFSET).unwrap();
283
284 // Read around the modified location causes an error
285 let f = File::open(&ctx.result.mapper_device).unwrap();
286 let mut buf = vec![0; 10]; // just read 10 bytes
287 let ret = f.read_at(&mut buf, MODIFIED_OFFSET).map_err(|e| e.kind());
288 assert!(ret.is_err());
289 assert_eq!(ret, Err(std::io::ErrorKind::Other));
290 });
291 }
292
293 // idsig file is not alread when the verity device is created, but later modified. Unlike to
294 // the APK case, this doesn't occur IO error because the merkle tree is already cached.
295 #[test]
296 fn tampered_idsig() {
297 let apk = include_bytes!("../testdata/test.apk");
298 let idsig = include_bytes!("../testdata/test.apk.idsig");
299 run_test(apk.as_ref(), idsig.as_ref(), "tampered_idsig", |ctx| {
300 // Change 10 bytes in the merkle tree.
301 let f = OpenOptions::new().read(true).write(true).open(ctx.hash_backing_file).unwrap();
302 f.write_at(&[0, 10], 100).unwrap();
303
304 let verity = fs::read(&ctx.result.mapper_device).unwrap();
305 let original = fs::read(&ctx.result.data_device).unwrap();
306 assert_eq!(verity.len(), original.len());
307 assert_eq!(verity.as_slice(), original.as_slice());
308 });
309 }
310
311 // test if both files are already block devices
312 #[test]
313 fn inputs_are_block_devices() {
Jiyong Parkd17ff4b2021-07-15 12:32:25 +0900314 if should_skip() {
315 return;
316 }
317
Jiyong Park86c9b082021-06-04 19:03:48 +0900318 use std::ops::Deref;
319 let apk = include_bytes!("../testdata/test.apk");
320 let idsig = include_bytes!("../testdata/test.apk.idsig");
321
322 let test_dir = tempfile::TempDir::new().unwrap();
Chris Wailes68c39f82021-07-27 16:03:44 -0700323 let (apk_path, idsig_path) = prepare_inputs(test_dir.path(), apk, idsig);
Jiyong Park86c9b082021-06-04 19:03:48 +0900324
325 // attach the files to loop devices to make them block devices
326 let apk_size = fs::metadata(&apk_path).unwrap().len();
327 let idsig_size = fs::metadata(&idsig_path).unwrap().len();
328
329 // Note that apk_loop_device is not detatched. This is because, when the apk file is
330 // already a block device, `enable_verity` uses the block device as it is. The detatching
331 // of the data device is done in the scopeguard for the return value of `enable_verity`
332 // below. Only the idsig_loop_device needs detatching.
333 let apk_loop_device = loopdevice::attach(&apk_path, 0, apk_size).unwrap();
334 let idsig_loop_device =
335 scopeguard::guard(loopdevice::attach(&idsig_path, 0, idsig_size).unwrap(), |dev| {
336 loopdevice::detach(dev).unwrap()
337 });
338
339 let name = "loop_as_input";
340 // Run the program WITH the loop devices, not the regular files.
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900341 let ret =
342 enable_verity(apk_loop_device.deref(), idsig_loop_device.deref(), name, None).unwrap();
Jiyong Park86c9b082021-06-04 19:03:48 +0900343 let ret = scopeguard::guard(ret, |ret| {
344 loopdevice::detach(ret.data_device).unwrap();
345 loopdevice::detach(ret.hash_device).unwrap();
346 let dm = dm::DeviceMapper::new().unwrap();
347 dm.delete_device_deferred(name).unwrap();
348 });
349
350 let verity = fs::read(&ret.mapper_device).unwrap();
351 let original = fs::read(&apk_path).unwrap();
352 assert_eq!(verity.len(), original.len()); // fail fast
353 assert_eq!(verity.as_slice(), original.as_slice());
354 }
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900355
356 // test with custom roothash
357 #[test]
358 fn correct_custom_roothash() {
359 let apk = include_bytes!("../testdata/test.apk");
360 let idsig = include_bytes!("../testdata/test.apk.idsig");
361 let roothash = V4Signature::from(Cursor::new(&idsig)).unwrap().hashing_info.raw_root_hash;
362 run_test_with_hash(apk.as_ref(), idsig.as_ref(), "correct", Some(&roothash), |ctx| {
363 let verity = fs::read(&ctx.result.mapper_device).unwrap();
364 let original = fs::read(&ctx.result.data_device).unwrap();
365 assert_eq!(verity.len(), original.len()); // fail fast
366 assert_eq!(verity.as_slice(), original.as_slice());
367 });
368 }
Jiyong Park86c9b082021-06-04 19:03:48 +0900369}