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