blob: bdca5b41867d49c512528dd9af88bd8cd9785b69 [file] [log] [blame]
Victor Hsieh88ac6ca2020-11-13 15:20:24 -08001/*
2 * Copyright (C) 2020 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//! This crate implements AuthFS, a FUSE-based, non-generic filesystem where file access is
18//! authenticated. This filesystem assumes the underlying layer is not trusted, e.g. file may be
19//! provided by an untrusted host/VM, so that the content can't be simply trusted. However, with a
Victor Hsieh5deba522022-01-10 17:18:40 -080020//! known file hash from trusted party, this filesystem can still verify a (read-only) file even if
21//! the host/VM as the blob provider is malicious. With the Merkle tree, each read of file block can
22//! be verified individually only when needed.
Victor Hsieh88ac6ca2020-11-13 15:20:24 -080023//!
Victor Hsieh5deba522022-01-10 17:18:40 -080024//! AuthFS only serve files that are specifically configured. Each remote file can be configured to
25//! appear as a local file at the mount point. A file configuration may include its remote file
26//! identifier and its verification method (e.g. by known digest).
27//!
28//! AuthFS also support remote directories. A remote directory may be defined by a manifest file,
29//! which contains file paths and their corresponding digests.
30//!
31//! AuthFS can also be configured for write, in which case the remote file server is treated as a
32//! (untrusted) storage. The file/directory integrity is maintained in memory in the VM. Currently,
33//! the state is not persistent, thus only new file/directory are supported.
Victor Hsieh88ac6ca2020-11-13 15:20:24 -080034
Victor Hsieh99782572022-01-05 15:38:33 -080035use anyhow::{anyhow, bail, Result};
Alan Stokese1b6e1c2021-10-01 12:44:49 +010036use log::error;
Victor Hsieh99782572022-01-05 15:38:33 -080037use protobuf::Message;
Victor Hsieh50d75ac2021-09-03 14:46:55 -070038use std::convert::TryInto;
Victor Hsieh99782572022-01-05 15:38:33 -080039use std::fs::File;
Victor Hsiehd18b9752021-11-09 16:03:34 -080040use std::path::{Path, PathBuf};
Victor Hsieh88ac6ca2020-11-13 15:20:24 -080041use structopt::StructOpt;
42
Victor Hsieh88ac6ca2020-11-13 15:20:24 -080043mod common;
44mod crypto;
Victor Hsieh09e26262021-03-03 16:00:55 -080045mod file;
Victor Hsiehf7fc3d32021-11-22 10:20:33 -080046mod fsstat;
Victor Hsieh88ac6ca2020-11-13 15:20:24 -080047mod fsverity;
48mod fusefs;
Victor Hsieh88ac6ca2020-11-13 15:20:24 -080049
Victor Hsiehe8137e32022-02-11 22:14:12 +000050use file::{Attr, InMemoryDir, RemoteDirEditor, RemoteFileEditor, RemoteFileReader};
Victor Hsiehf7fc3d32021-11-22 10:20:33 -080051use fsstat::RemoteFsStatsReader;
Victor Hsiehe8137e32022-02-11 22:14:12 +000052use fsverity::VerifiedFileEditor;
Victor Hsieh99782572022-01-05 15:38:33 -080053use fsverity_digests_proto::fsverity_digests::FSVerityDigests;
Victor Hsiehe8137e32022-02-11 22:14:12 +000054use fusefs::{AuthFs, AuthFsEntry, LazyVerifiedReadonlyFile};
Victor Hsieh88ac6ca2020-11-13 15:20:24 -080055
56#[derive(StructOpt)]
Victor Hsiehf01f3232020-12-11 13:31:31 -080057struct Args {
Victor Hsieh88ac6ca2020-11-13 15:20:24 -080058 /// Mount point of AuthFS.
59 #[structopt(parse(from_os_str))]
60 mount_point: PathBuf,
61
Victor Hsieh2445e332021-06-04 16:44:53 -070062 /// CID of the VM where the service runs.
63 #[structopt(long)]
Victor Hsieh1a8cd042021-09-03 16:29:45 -070064 cid: u32,
Victor Hsieh2445e332021-06-04 16:44:53 -070065
Victor Hsieh4cc3b792021-08-04 12:00:04 -070066 /// Extra options to FUSE
67 #[structopt(short = "o")]
68 extra_options: Option<String>,
69
Victor Hsieh09e26262021-03-03 16:00:55 -080070 /// A read-only remote file with integrity check. Can be multiple.
Victor Hsiehf01f3232020-12-11 13:31:31 -080071 ///
Victor Hsieh5deba522022-01-10 17:18:40 -080072 /// For example, `--remote-ro-file 5:sha256-1234abcd` tells the filesystem to associate the
73 /// file $MOUNTPOINT/5 with a remote FD 5, and has a fs-verity digest with sha256 of the hex
74 /// value 1234abcd.
Victor Hsieh09e26262021-03-03 16:00:55 -080075 #[structopt(long, parse(try_from_str = parse_remote_ro_file_option))]
76 remote_ro_file: Vec<OptionRemoteRoFile>,
Victor Hsiehf01f3232020-12-11 13:31:31 -080077
Victor Hsieh09e26262021-03-03 16:00:55 -080078 /// A read-only remote file without integrity check. Can be multiple.
Victor Hsiehf01f3232020-12-11 13:31:31 -080079 ///
Victor Hsiehb3588ce2021-11-02 15:02:32 -070080 /// For example, `--remote-ro-file-unverified 5` tells the filesystem to associate the file
81 /// $MOUNTPOINT/5 with a remote FD 5.
82 #[structopt(long)]
83 remote_ro_file_unverified: Vec<i32>,
Victor Hsiehf01f3232020-12-11 13:31:31 -080084
Victor Hsieh6a47e7f2021-03-03 15:53:49 -080085 /// A new read-writable remote file with integrity check. Can be multiple.
86 ///
Victor Hsiehb3588ce2021-11-02 15:02:32 -070087 /// For example, `--remote-new-rw-file 5` tells the filesystem to associate the file
88 /// $MOUNTPOINT/5 with a remote FD 5.
89 #[structopt(long)]
90 remote_new_rw_file: Vec<i32>,
Victor Hsieh6a47e7f2021-03-03 15:53:49 -080091
Victor Hsiehd18b9752021-11-09 16:03:34 -080092 /// A read-only directory that represents a remote directory. The directory view is constructed
93 /// and finalized during the filesystem initialization based on the provided mapping file
94 /// (which is a serialized protobuf of android.security.fsverity.FSVerityDigests, which
95 /// essentially provides <file path, fs-verity digest> mappings of exported files). The mapping
96 /// file is supposed to come from a trusted location in order to provide a trusted view as well
97 /// as verified access of included files with their fs-verity digest. Not all files on the
98 /// remote host may be included in the mapping file, so the directory view may be partial. The
99 /// directory structure won't change throughout the filesystem lifetime.
100 ///
Victor Hsieh99782572022-01-05 15:38:33 -0800101 /// For example, `--remote-ro-dir 5:/path/to/mapping:prefix/` tells the filesystem to
Victor Hsiehd18b9752021-11-09 16:03:34 -0800102 /// construct a directory structure defined in the mapping file at $MOUNTPOINT/5, which may
Victor Hsieh99782572022-01-05 15:38:33 -0800103 /// include a file like /5/system/framework/framework.jar. "prefix/" tells the filesystem to
104 /// strip the path (e.g. "system/") from the mount point to match the expected location of the
Victor Hsiehd18b9752021-11-09 16:03:34 -0800105 /// remote FD (e.g. a directory FD of "/system" in the remote).
106 #[structopt(long, parse(try_from_str = parse_remote_new_ro_dir_option))]
107 remote_ro_dir: Vec<OptionRemoteRoDir>,
108
Victor Hsieh45636232021-10-15 17:52:51 -0700109 /// A new directory that is assumed empty in the backing filesystem. New files created in this
110 /// directory are integrity-protected in the same way as --remote-new-verified-file. Can be
111 /// multiple.
112 ///
Victor Hsiehb3588ce2021-11-02 15:02:32 -0700113 /// For example, `--remote-new-rw-dir 5` tells the filesystem to associate $MOUNTPOINT/5
114 /// with a remote dir FD 5.
115 #[structopt(long)]
116 remote_new_rw_dir: Vec<i32>,
Victor Hsieh45636232021-10-15 17:52:51 -0700117
Victor Hsieh9d0ab622021-04-26 17:07:02 -0700118 /// Enable debugging features.
119 #[structopt(long)]
120 debug: bool,
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800121}
122
Victor Hsieh09e26262021-03-03 16:00:55 -0800123struct OptionRemoteRoFile {
Victor Hsiehf01f3232020-12-11 13:31:31 -0800124 /// ID to refer to the remote file.
Victor Hsiehb3588ce2021-11-02 15:02:32 -0700125 remote_fd: i32,
Victor Hsiehf01f3232020-12-11 13:31:31 -0800126
Victor Hsieh5deba522022-01-10 17:18:40 -0800127 /// Expected fs-verity digest (with sha256) for the remote file.
128 digest: String,
Victor Hsiehf01f3232020-12-11 13:31:31 -0800129}
130
Victor Hsiehd18b9752021-11-09 16:03:34 -0800131struct OptionRemoteRoDir {
132 /// ID to refer to the remote dir.
133 remote_dir_fd: i32,
134
135 /// A mapping file that describes the expecting file/directory structure and integrity metadata
136 /// in the remote directory. The file contains serialized protobuf of
137 /// android.security.fsverity.FSVerityDigests.
Victor Hsiehd18b9752021-11-09 16:03:34 -0800138 mapping_file_path: PathBuf,
139
Victor Hsieh99782572022-01-05 15:38:33 -0800140 prefix: String,
Victor Hsiehd18b9752021-11-09 16:03:34 -0800141}
142
Victor Hsieh09e26262021-03-03 16:00:55 -0800143fn parse_remote_ro_file_option(option: &str) -> Result<OptionRemoteRoFile> {
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800144 let strs: Vec<&str> = option.split(':').collect();
Victor Hsiehb3588ce2021-11-02 15:02:32 -0700145 if strs.len() != 2 {
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800146 bail!("Invalid option: {}", option);
147 }
Victor Hsieh5deba522022-01-10 17:18:40 -0800148 if let Some(digest) = strs[1].strip_prefix("sha256-") {
149 Ok(OptionRemoteRoFile { remote_fd: strs[0].parse::<i32>()?, digest: String::from(digest) })
150 } else {
151 bail!("Unsupported hash algorithm or invalid format: {}", strs[1]);
152 }
Victor Hsieh45636232021-10-15 17:52:51 -0700153}
154
Victor Hsiehd18b9752021-11-09 16:03:34 -0800155fn parse_remote_new_ro_dir_option(option: &str) -> Result<OptionRemoteRoDir> {
156 let strs: Vec<&str> = option.split(':').collect();
157 if strs.len() != 3 {
158 bail!("Invalid option: {}", option);
159 }
160 Ok(OptionRemoteRoDir {
161 remote_dir_fd: strs[0].parse::<i32>().unwrap(),
162 mapping_file_path: PathBuf::from(strs[1]),
Victor Hsieh99782572022-01-05 15:38:33 -0800163 prefix: String::from(strs[2]),
Victor Hsiehd18b9752021-11-09 16:03:34 -0800164 })
165}
166
Victor Hsieh5deba522022-01-10 17:18:40 -0800167fn from_hex_string(s: &str) -> Result<Vec<u8>> {
168 if s.len() % 2 == 1 {
169 bail!("Incomplete hex string: {}", s);
170 } else {
171 let results = (0..s.len())
172 .step_by(2)
173 .map(|i| {
174 u8::from_str_radix(&s[i..i + 2], 16)
175 .map_err(|e| anyhow!("Cannot parse hex {}: {}", &s[i..i + 2], e))
176 })
177 .collect::<Result<Vec<_>>>();
178 Ok(results?)
179 }
180}
181
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700182fn new_remote_verified_file_entry(
Victor Hsieh2445e332021-06-04 16:44:53 -0700183 service: file::VirtFdService,
Victor Hsiehb3588ce2021-11-02 15:02:32 -0700184 remote_fd: i32,
Victor Hsieh5deba522022-01-10 17:18:40 -0800185 expected_digest: &str,
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700186) -> Result<AuthFsEntry> {
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700187 Ok(AuthFsEntry::VerifiedReadonly {
Victor Hsiehe8137e32022-02-11 22:14:12 +0000188 reader: LazyVerifiedReadonlyFile::prepare_by_fd(
189 service,
190 remote_fd,
191 from_hex_string(expected_digest)?,
192 ),
Victor Hsieh1bcf4112021-03-19 14:26:57 -0700193 })
Victor Hsiehf01f3232020-12-11 13:31:31 -0800194}
195
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700196fn new_remote_unverified_file_entry(
Victor Hsieh2445e332021-06-04 16:44:53 -0700197 service: file::VirtFdService,
Victor Hsiehb3588ce2021-11-02 15:02:32 -0700198 remote_fd: i32,
Victor Hsieh2445e332021-06-04 16:44:53 -0700199 file_size: u64,
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700200) -> Result<AuthFsEntry> {
Victor Hsiehb3588ce2021-11-02 15:02:32 -0700201 let reader = RemoteFileReader::new(service, remote_fd);
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700202 Ok(AuthFsEntry::UnverifiedReadonly { reader, file_size })
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800203}
204
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700205fn new_remote_new_verified_file_entry(
Victor Hsieh2445e332021-06-04 16:44:53 -0700206 service: file::VirtFdService,
Victor Hsiehb3588ce2021-11-02 15:02:32 -0700207 remote_fd: i32,
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700208) -> Result<AuthFsEntry> {
Victor Hsiehf393a722021-12-08 13:04:27 -0800209 let remote_file = RemoteFileEditor::new(service.clone(), remote_fd);
210 Ok(AuthFsEntry::VerifiedNew {
211 editor: VerifiedFileEditor::new(remote_file),
212 attr: Attr::new_file(service, remote_fd),
213 })
Victor Hsieh6a47e7f2021-03-03 15:53:49 -0800214}
215
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700216fn new_remote_new_verified_dir_entry(
Victor Hsieh45636232021-10-15 17:52:51 -0700217 service: file::VirtFdService,
Victor Hsiehb3588ce2021-11-02 15:02:32 -0700218 remote_fd: i32,
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700219) -> Result<AuthFsEntry> {
Victor Hsiehf393a722021-12-08 13:04:27 -0800220 let dir = RemoteDirEditor::new(service.clone(), remote_fd);
221 let attr = Attr::new_dir(service, remote_fd);
222 Ok(AuthFsEntry::VerifiedNewDirectory { dir, attr })
Victor Hsieh45636232021-10-15 17:52:51 -0700223}
224
Victor Hsiehf7fc3d32021-11-22 10:20:33 -0800225fn prepare_root_dir_entries(
226 service: file::VirtFdService,
227 authfs: &mut AuthFs,
228 args: &Args,
229) -> Result<()> {
Victor Hsieh88e50172021-10-15 13:27:13 -0700230 for config in &args.remote_ro_file {
Victor Hsieh4d6b9d42021-11-08 15:53:49 -0800231 authfs.add_entry_at_root_dir(
Victor Hsieh60c2f412021-11-03 13:02:19 -0700232 remote_fd_to_path_buf(config.remote_fd),
Victor Hsiehe8137e32022-02-11 22:14:12 +0000233 new_remote_verified_file_entry(service.clone(), config.remote_fd, &config.digest)?,
Victor Hsieh4d6b9d42021-11-08 15:53:49 -0800234 )?;
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800235 }
236
Victor Hsiehb3588ce2021-11-02 15:02:32 -0700237 for remote_fd in &args.remote_ro_file_unverified {
238 let remote_fd = *remote_fd;
Victor Hsieh4d6b9d42021-11-08 15:53:49 -0800239 authfs.add_entry_at_root_dir(
Victor Hsieh60c2f412021-11-03 13:02:19 -0700240 remote_fd_to_path_buf(remote_fd),
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700241 new_remote_unverified_file_entry(
Victor Hsieh88e50172021-10-15 13:27:13 -0700242 service.clone(),
Victor Hsiehb3588ce2021-11-02 15:02:32 -0700243 remote_fd,
244 service.getFileSize(remote_fd)?.try_into()?,
Victor Hsieh88e50172021-10-15 13:27:13 -0700245 )?,
Victor Hsieh4d6b9d42021-11-08 15:53:49 -0800246 )?;
Victor Hsieh88e50172021-10-15 13:27:13 -0700247 }
248
Victor Hsiehb3588ce2021-11-02 15:02:32 -0700249 for remote_fd in &args.remote_new_rw_file {
250 let remote_fd = *remote_fd;
Victor Hsieh4d6b9d42021-11-08 15:53:49 -0800251 authfs.add_entry_at_root_dir(
Victor Hsieh60c2f412021-11-03 13:02:19 -0700252 remote_fd_to_path_buf(remote_fd),
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700253 new_remote_new_verified_file_entry(service.clone(), remote_fd)?,
Victor Hsieh4d6b9d42021-11-08 15:53:49 -0800254 )?;
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800255 }
256
Victor Hsiehb3588ce2021-11-02 15:02:32 -0700257 for remote_fd in &args.remote_new_rw_dir {
258 let remote_fd = *remote_fd;
Victor Hsieh4d6b9d42021-11-08 15:53:49 -0800259 authfs.add_entry_at_root_dir(
Victor Hsieh60c2f412021-11-03 13:02:19 -0700260 remote_fd_to_path_buf(remote_fd),
Victor Hsieh26cea2f2021-11-03 10:28:33 -0700261 new_remote_new_verified_dir_entry(service.clone(), remote_fd)?,
Victor Hsieh4d6b9d42021-11-08 15:53:49 -0800262 )?;
Victor Hsieh45636232021-10-15 17:52:51 -0700263 }
264
Victor Hsiehd18b9752021-11-09 16:03:34 -0800265 for config in &args.remote_ro_dir {
266 let dir_root_inode = authfs.add_entry_at_root_dir(
267 remote_fd_to_path_buf(config.remote_dir_fd),
268 AuthFsEntry::ReadonlyDirectory { dir: InMemoryDir::new() },
269 )?;
270
Victor Hsieh99782572022-01-05 15:38:33 -0800271 // Build the directory tree based on the mapping file.
272 let mut reader = File::open(&config.mapping_file_path)?;
273 let proto = FSVerityDigests::parse_from_reader(&mut reader)?;
Victor Hsieh5deba522022-01-10 17:18:40 -0800274 for (path_str, digest) in &proto.digests {
275 if digest.hash_alg != "sha256" {
276 bail!("Unsupported hash algorithm: {}", digest.hash_alg);
277 }
278
Victor Hsiehd18b9752021-11-09 16:03:34 -0800279 let file_entry = {
Victor Hsieh99782572022-01-05 15:38:33 -0800280 let remote_path_str = path_str.strip_prefix(&config.prefix).ok_or_else(|| {
281 anyhow!("Expect path {} to match prefix {}", path_str, config.prefix)
282 })?;
Victor Hsieh5deba522022-01-10 17:18:40 -0800283 AuthFsEntry::VerifiedReadonly {
Victor Hsiehe8137e32022-02-11 22:14:12 +0000284 reader: LazyVerifiedReadonlyFile::prepare_by_path(
285 service.clone(),
286 config.remote_dir_fd,
287 PathBuf::from(remote_path_str),
288 digest.digest.clone(),
289 ),
Victor Hsieh5deba522022-01-10 17:18:40 -0800290 }
Victor Hsiehd18b9752021-11-09 16:03:34 -0800291 };
Victor Hsieh99782572022-01-05 15:38:33 -0800292 authfs.add_entry_at_ro_dir_by_path(dir_root_inode, Path::new(path_str), file_entry)?;
Victor Hsiehd18b9752021-11-09 16:03:34 -0800293 }
294 }
295
Victor Hsieh4d6b9d42021-11-08 15:53:49 -0800296 Ok(())
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800297}
298
Victor Hsieh60c2f412021-11-03 13:02:19 -0700299fn remote_fd_to_path_buf(fd: i32) -> PathBuf {
300 PathBuf::from(fd.to_string())
301}
302
Alan Stokese1b6e1c2021-10-01 12:44:49 +0100303fn try_main() -> Result<()> {
Victor Hsieh2442abc2021-11-17 13:25:02 -0800304 let args = Args::from_args_safe()?;
Victor Hsieh9d0ab622021-04-26 17:07:02 -0700305
306 let log_level = if args.debug { log::Level::Debug } else { log::Level::Info };
307 android_logger::init_once(
308 android_logger::Config::default().with_tag("authfs").with_min_level(log_level),
309 );
310
Victor Hsiehf7fc3d32021-11-22 10:20:33 -0800311 let service = file::get_rpc_binder_service(args.cid)?;
312 let mut authfs = AuthFs::new(RemoteFsStatsReader::new(service.clone()));
313 prepare_root_dir_entries(service, &mut authfs, &args)?;
314
Victor Hsieh79f296b2021-12-02 15:38:08 -0800315 fusefs::mount_and_enter_message_loop(authfs, &args.mount_point, &args.extra_options)?;
Victor Hsiehf01f3232020-12-11 13:31:31 -0800316 bail!("Unexpected exit after the handler loop")
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800317}
Alan Stokese1b6e1c2021-10-01 12:44:49 +0100318
319fn main() {
320 if let Err(e) = try_main() {
321 error!("failed with {:?}", e);
322 std::process::exit(1);
323 }
324}
Victor Hsieh5deba522022-01-10 17:18:40 -0800325
326#[cfg(test)]
327mod tests {
328 use super::*;
329
330 #[test]
331 fn parse_hex_string() {
332 assert_eq!(from_hex_string("deadbeef").unwrap(), vec![0xde, 0xad, 0xbe, 0xef]);
333 assert_eq!(from_hex_string("DEADBEEF").unwrap(), vec![0xde, 0xad, 0xbe, 0xef]);
334 assert_eq!(from_hex_string("").unwrap(), Vec::<u8>::new());
335
336 assert!(from_hex_string("deadbee").is_err());
337 assert!(from_hex_string("X").is_err());
338 }
339}