blob: d54b5be929704b378dbf5bbd3fb9d269331dc328 [file] [log] [blame]
Victor Hsieh88ac6ca2020-11-13 15:20:24 -08001/*
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
17use anyhow::Result;
Victor Hsieh9d0ab622021-04-26 17:07:02 -070018use log::{debug, warn};
Victor Hsieh88ac6ca2020-11-13 15:20:24 -080019use std::collections::BTreeMap;
20use std::convert::TryFrom;
21use std::ffi::CStr;
22use std::fs::OpenOptions;
23use std::io;
24use std::mem::MaybeUninit;
25use std::option::Option;
26use std::os::unix::io::AsRawFd;
27use std::path::Path;
28use std::time::Duration;
29
Victor Hsieh6a47e7f2021-03-03 15:53:49 -080030use fuse::filesystem::{
Victor Hsieh71f10032021-08-13 11:24:02 -070031 Context, DirEntry, DirectoryIterator, Entry, FileSystem, FsOptions, GetxattrReply,
32 SetattrValid, ZeroCopyReader, ZeroCopyWriter,
Victor Hsieh6a47e7f2021-03-03 15:53:49 -080033};
Victor Hsieh88ac6ca2020-11-13 15:20:24 -080034use fuse::mount::MountOption;
35
Victor Hsiehac4f3f42021-02-26 12:35:58 -080036use crate::common::{divide_roundup, ChunkedSizeIter, CHUNK_SIZE};
Victor Hsieh6a47e7f2021-03-03 15:53:49 -080037use crate::file::{
Victor Hsieh88e50172021-10-15 13:27:13 -070038 RandomWrite, ReadByChunk, RemoteFileEditor, RemoteFileReader, RemoteMerkleTreeReader,
Victor Hsieh6a47e7f2021-03-03 15:53:49 -080039};
40use crate::fsverity::{VerifiedFileEditor, VerifiedFileReader};
Victor Hsieh88ac6ca2020-11-13 15:20:24 -080041
Victor Hsieh88ac6ca2020-11-13 15:20:24 -080042const DEFAULT_METADATA_TIMEOUT: std::time::Duration = Duration::from_secs(5);
43
44pub type Inode = u64;
45type Handle = u64;
46
Victor Hsieh1bcf4112021-03-19 14:26:57 -070047/// `FileConfig` defines the file type supported by AuthFS.
Victor Hsieh88ac6ca2020-11-13 15:20:24 -080048pub enum FileConfig {
Victor Hsieh1bcf4112021-03-19 14:26:57 -070049 /// A file type that is verified against fs-verity signature (thus read-only). The file is
Victor Hsieh1bcf4112021-03-19 14:26:57 -070050 /// served from a remote server.
Victor Hsieh88e50172021-10-15 13:27:13 -070051 VerifiedReadonly {
Victor Hsieh1bcf4112021-03-19 14:26:57 -070052 reader: VerifiedFileReader<RemoteFileReader, RemoteMerkleTreeReader>,
53 file_size: u64,
54 },
55 /// A file type that is a read-only passthrough from a file on a remote serrver.
Victor Hsieh88e50172021-10-15 13:27:13 -070056 UnverifiedReadonly { reader: RemoteFileReader, file_size: u64 },
Victor Hsieh1bcf4112021-03-19 14:26:57 -070057 /// A file type that is initially empty, and the content is stored on a remote server. File
58 /// integrity is guaranteed with private Merkle tree.
Victor Hsieh88e50172021-10-15 13:27:13 -070059 VerifiedNew { editor: VerifiedFileEditor<RemoteFileEditor> },
Victor Hsieh88ac6ca2020-11-13 15:20:24 -080060}
61
62struct AuthFs {
63 /// Store `FileConfig`s using the `Inode` number as the search index.
64 ///
65 /// For further optimization to minimize the search cost, since Inode is integer, we may
66 /// consider storing them in a Vec if we can guarantee that the numbers are small and
67 /// consecutive.
68 file_pool: BTreeMap<Inode, FileConfig>,
69
70 /// Maximum bytes in the write transaction to the FUSE device. This limits the maximum size to
71 /// a read request (including FUSE protocol overhead).
72 max_write: u32,
73}
74
75impl AuthFs {
76 pub fn new(file_pool: BTreeMap<Inode, FileConfig>, max_write: u32) -> AuthFs {
77 AuthFs { file_pool, max_write }
78 }
79
80 fn get_file_config(&self, inode: &Inode) -> io::Result<&FileConfig> {
Chris Wailes68c39f82021-07-27 16:03:44 -070081 self.file_pool.get(inode).ok_or_else(|| io::Error::from_raw_os_error(libc::ENOENT))
Victor Hsieh88ac6ca2020-11-13 15:20:24 -080082 }
83}
84
85fn check_access_mode(flags: u32, mode: libc::c_int) -> io::Result<()> {
86 if (flags & libc::O_ACCMODE as u32) == mode as u32 {
87 Ok(())
88 } else {
89 Err(io::Error::from_raw_os_error(libc::EACCES))
90 }
91}
92
93cfg_if::cfg_if! {
94 if #[cfg(all(target_arch = "aarch64", target_pointer_width = "64"))] {
Victor Hsiehda3fbc42021-02-23 16:12:49 -080095 fn blk_size() -> libc::c_int { CHUNK_SIZE as libc::c_int }
Victor Hsieh88ac6ca2020-11-13 15:20:24 -080096 } else {
Victor Hsiehda3fbc42021-02-23 16:12:49 -080097 fn blk_size() -> libc::c_long { CHUNK_SIZE as libc::c_long }
Victor Hsieh88ac6ca2020-11-13 15:20:24 -080098 }
99}
100
Victor Hsieh6a47e7f2021-03-03 15:53:49 -0800101enum FileMode {
102 ReadOnly,
103 ReadWrite,
104}
105
106fn create_stat(ino: libc::ino_t, file_size: u64, file_mode: FileMode) -> io::Result<libc::stat64> {
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800107 let mut st = unsafe { MaybeUninit::<libc::stat64>::zeroed().assume_init() };
108
109 st.st_ino = ino;
Victor Hsieh6a47e7f2021-03-03 15:53:49 -0800110 st.st_mode = match file_mode {
111 // Until needed, let's just grant the owner access.
112 FileMode::ReadOnly => libc::S_IFREG | libc::S_IRUSR,
113 FileMode::ReadWrite => libc::S_IFREG | libc::S_IRUSR | libc::S_IWUSR,
114 };
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800115 st.st_dev = 0;
116 st.st_nlink = 1;
117 st.st_uid = 0;
118 st.st_gid = 0;
119 st.st_rdev = 0;
120 st.st_size = libc::off64_t::try_from(file_size)
121 .map_err(|_| io::Error::from_raw_os_error(libc::EFBIG))?;
122 st.st_blksize = blk_size();
123 // Per man stat(2), st_blocks is "Number of 512B blocks allocated".
124 st.st_blocks = libc::c_longlong::try_from(divide_roundup(file_size, 512))
125 .map_err(|_| io::Error::from_raw_os_error(libc::EFBIG))?;
126 Ok(st)
127}
128
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800129fn offset_to_chunk_index(offset: u64) -> u64 {
Victor Hsiehda3fbc42021-02-23 16:12:49 -0800130 offset / CHUNK_SIZE
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800131}
132
Victor Hsiehd0bb5d32021-03-19 12:48:03 -0700133fn read_chunks<W: io::Write, T: ReadByChunk>(
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800134 mut w: W,
135 file: &T,
136 file_size: u64,
137 offset: u64,
138 size: u32,
139) -> io::Result<usize> {
140 let remaining = file_size.saturating_sub(offset);
141 let size_to_read = std::cmp::min(size as usize, remaining as usize);
Victor Hsiehac4f3f42021-02-26 12:35:58 -0800142 let total = ChunkedSizeIter::new(size_to_read, offset, CHUNK_SIZE as usize).try_fold(
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800143 0,
144 |total, (current_offset, planned_data_size)| {
145 // TODO(victorhsieh): There might be a non-trivial way to avoid this copy. For example,
146 // instead of accepting a buffer, the writer could expose the final destination buffer
147 // for the reader to write to. It might not be generally applicable though, e.g. with
148 // virtio transport, the buffer may not be continuous.
Victor Hsiehda3fbc42021-02-23 16:12:49 -0800149 let mut buf = [0u8; CHUNK_SIZE as usize];
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800150 let read_size = file.read_chunk(offset_to_chunk_index(current_offset), &mut buf)?;
151 if read_size < planned_data_size {
152 return Err(io::Error::from_raw_os_error(libc::ENODATA));
153 }
154
Victor Hsiehda3fbc42021-02-23 16:12:49 -0800155 let begin = (current_offset % CHUNK_SIZE) as usize;
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800156 let end = begin + planned_data_size;
157 let s = w.write(&buf[begin..end])?;
158 if s != planned_data_size {
159 return Err(io::Error::from_raw_os_error(libc::EIO));
160 }
161 Ok(total + s)
162 },
163 )?;
164
165 Ok(total)
166}
167
168// No need to support enumerating directory entries.
169struct EmptyDirectoryIterator {}
170
171impl DirectoryIterator for EmptyDirectoryIterator {
172 fn next(&mut self) -> Option<DirEntry> {
173 None
174 }
175}
176
177impl FileSystem for AuthFs {
178 type Inode = Inode;
179 type Handle = Handle;
180 type DirIter = EmptyDirectoryIterator;
181
182 fn max_buffer_size(&self) -> u32 {
183 self.max_write
184 }
185
Victor Hsieh6a47e7f2021-03-03 15:53:49 -0800186 fn init(&self, _capable: FsOptions) -> io::Result<FsOptions> {
187 // Enable writeback cache for better performance especially since our bandwidth to the
188 // backend service is limited.
189 Ok(FsOptions::WRITEBACK_CACHE)
190 }
191
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800192 fn lookup(&self, _ctx: Context, _parent: Inode, name: &CStr) -> io::Result<Entry> {
193 // Only accept file name that looks like an integrer. Files in the pool are simply exposed
194 // by their inode number. Also, there is currently no directory structure.
195 let num = name.to_str().map_err(|_| io::Error::from_raw_os_error(libc::EINVAL))?;
196 // Normally, `lookup` is required to increase a reference count for the inode (while
197 // `forget` will decrease it). It is not necessary here since the files are configured to
198 // be static.
199 let inode = num.parse::<Inode>().map_err(|_| io::Error::from_raw_os_error(libc::ENOENT))?;
200 let st = match self.get_file_config(&inode)? {
Victor Hsieh88e50172021-10-15 13:27:13 -0700201 FileConfig::UnverifiedReadonly { file_size, .. }
202 | FileConfig::VerifiedReadonly { file_size, .. } => {
Victor Hsieh6a47e7f2021-03-03 15:53:49 -0800203 create_stat(inode, *file_size, FileMode::ReadOnly)?
204 }
Victor Hsieh88e50172021-10-15 13:27:13 -0700205 FileConfig::VerifiedNew { editor } => {
Victor Hsieh1bcf4112021-03-19 14:26:57 -0700206 create_stat(inode, editor.size(), FileMode::ReadWrite)?
Victor Hsieh09e26262021-03-03 16:00:55 -0800207 }
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800208 };
209 Ok(Entry {
210 inode,
211 generation: 0,
212 attr: st,
213 entry_timeout: DEFAULT_METADATA_TIMEOUT,
214 attr_timeout: DEFAULT_METADATA_TIMEOUT,
215 })
216 }
217
218 fn getattr(
219 &self,
220 _ctx: Context,
221 inode: Inode,
222 _handle: Option<Handle>,
223 ) -> io::Result<(libc::stat64, Duration)> {
224 Ok((
225 match self.get_file_config(&inode)? {
Victor Hsieh88e50172021-10-15 13:27:13 -0700226 FileConfig::UnverifiedReadonly { file_size, .. }
227 | FileConfig::VerifiedReadonly { file_size, .. } => {
Victor Hsieh6a47e7f2021-03-03 15:53:49 -0800228 create_stat(inode, *file_size, FileMode::ReadOnly)?
229 }
Victor Hsieh88e50172021-10-15 13:27:13 -0700230 FileConfig::VerifiedNew { editor } => {
Victor Hsieh1bcf4112021-03-19 14:26:57 -0700231 create_stat(inode, editor.size(), FileMode::ReadWrite)?
Victor Hsieh09e26262021-03-03 16:00:55 -0800232 }
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800233 },
234 DEFAULT_METADATA_TIMEOUT,
235 ))
236 }
237
238 fn open(
239 &self,
240 _ctx: Context,
241 inode: Self::Inode,
242 flags: u32,
243 ) -> io::Result<(Option<Self::Handle>, fuse::sys::OpenOptions)> {
244 // Since file handle is not really used in later operations (which use Inode directly),
Victor Hsieh09e26262021-03-03 16:00:55 -0800245 // return None as the handle.
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800246 match self.get_file_config(&inode)? {
Victor Hsieh88e50172021-10-15 13:27:13 -0700247 FileConfig::VerifiedReadonly { .. } | FileConfig::UnverifiedReadonly { .. } => {
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800248 check_access_mode(flags, libc::O_RDONLY)?;
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800249 }
Victor Hsieh88e50172021-10-15 13:27:13 -0700250 FileConfig::VerifiedNew { .. } => {
Victor Hsieh6a47e7f2021-03-03 15:53:49 -0800251 // No need to check access modes since all the modes are allowed to the
252 // read-writable file.
Victor Hsieh6a47e7f2021-03-03 15:53:49 -0800253 }
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800254 }
Victor Hsieh8e161b52021-04-26 17:47:19 -0700255 // Always cache the file content. There is currently no need to support direct I/O or avoid
256 // the cache buffer. Memory mapping is only possible with cache enabled.
257 Ok((None, fuse::sys::OpenOptions::KEEP_CACHE))
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800258 }
259
260 fn read<W: io::Write + ZeroCopyWriter>(
261 &self,
262 _ctx: Context,
263 inode: Inode,
264 _handle: Handle,
265 w: W,
266 size: u32,
267 offset: u64,
268 _lock_owner: Option<u64>,
269 _flags: u32,
270 ) -> io::Result<usize> {
271 match self.get_file_config(&inode)? {
Victor Hsieh88e50172021-10-15 13:27:13 -0700272 FileConfig::VerifiedReadonly { reader, file_size } => {
Victor Hsieh1bcf4112021-03-19 14:26:57 -0700273 read_chunks(w, reader, *file_size, offset, size)
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800274 }
Victor Hsieh88e50172021-10-15 13:27:13 -0700275 FileConfig::UnverifiedReadonly { reader, file_size } => {
Victor Hsieh1bcf4112021-03-19 14:26:57 -0700276 read_chunks(w, reader, *file_size, offset, size)
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800277 }
Victor Hsieh88e50172021-10-15 13:27:13 -0700278 FileConfig::VerifiedNew { editor } => {
Victor Hsieh6a47e7f2021-03-03 15:53:49 -0800279 // Note that with FsOptions::WRITEBACK_CACHE, it's possible for the kernel to
280 // request a read even if the file is open with O_WRONLY.
Victor Hsieh1bcf4112021-03-19 14:26:57 -0700281 read_chunks(w, editor, editor.size(), offset, size)
Victor Hsieh6a47e7f2021-03-03 15:53:49 -0800282 }
283 }
284 }
285
286 fn write<R: io::Read + ZeroCopyReader>(
287 &self,
288 _ctx: Context,
289 inode: Self::Inode,
290 _handle: Self::Handle,
291 mut r: R,
292 size: u32,
293 offset: u64,
294 _lock_owner: Option<u64>,
295 _delayed_write: bool,
296 _flags: u32,
297 ) -> io::Result<usize> {
298 match self.get_file_config(&inode)? {
Victor Hsieh88e50172021-10-15 13:27:13 -0700299 FileConfig::VerifiedNew { editor } => {
Victor Hsieh6a47e7f2021-03-03 15:53:49 -0800300 let mut buf = vec![0; size as usize];
301 r.read_exact(&mut buf)?;
Victor Hsieh1bcf4112021-03-19 14:26:57 -0700302 editor.write_at(&buf, offset)
Victor Hsieh6a47e7f2021-03-03 15:53:49 -0800303 }
304 _ => Err(io::Error::from_raw_os_error(libc::EBADF)),
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800305 }
306 }
Victor Hsieh9d0ab622021-04-26 17:07:02 -0700307
308 fn setattr(
309 &self,
310 _ctx: Context,
311 inode: Inode,
312 attr: libc::stat64,
313 _handle: Option<Handle>,
314 valid: SetattrValid,
315 ) -> io::Result<(libc::stat64, Duration)> {
316 match self.get_file_config(&inode)? {
Victor Hsieh88e50172021-10-15 13:27:13 -0700317 FileConfig::VerifiedNew { editor } => {
Victor Hsieh9d0ab622021-04-26 17:07:02 -0700318 // Initialize the default stat.
319 let mut new_attr = create_stat(inode, editor.size(), FileMode::ReadWrite)?;
320 // `valid` indicates what fields in `attr` are valid. Update to return correctly.
321 if valid.contains(SetattrValid::SIZE) {
322 // st_size is i64, but the cast should be safe since kernel should not give a
323 // negative size.
324 debug_assert!(attr.st_size >= 0);
325 new_attr.st_size = attr.st_size;
326 editor.resize(attr.st_size as u64)?;
327 }
328
329 if valid.contains(SetattrValid::MODE) {
330 warn!("Changing st_mode is not currently supported");
331 return Err(io::Error::from_raw_os_error(libc::ENOSYS));
332 }
333 if valid.contains(SetattrValid::UID) {
334 warn!("Changing st_uid is not currently supported");
335 return Err(io::Error::from_raw_os_error(libc::ENOSYS));
336 }
337 if valid.contains(SetattrValid::GID) {
338 warn!("Changing st_gid is not currently supported");
339 return Err(io::Error::from_raw_os_error(libc::ENOSYS));
340 }
341 if valid.contains(SetattrValid::CTIME) {
342 debug!("Ignoring ctime change as authfs does not maintain timestamp currently");
343 }
344 if valid.intersects(SetattrValid::ATIME | SetattrValid::ATIME_NOW) {
345 debug!("Ignoring atime change as authfs does not maintain timestamp currently");
346 }
347 if valid.intersects(SetattrValid::MTIME | SetattrValid::MTIME_NOW) {
348 debug!("Ignoring mtime change as authfs does not maintain timestamp currently");
349 }
350 Ok((new_attr, DEFAULT_METADATA_TIMEOUT))
351 }
352 _ => Err(io::Error::from_raw_os_error(libc::EBADF)),
353 }
354 }
Victor Hsieh71f10032021-08-13 11:24:02 -0700355
356 fn getxattr(
357 &self,
358 _ctx: Context,
359 inode: Self::Inode,
360 name: &CStr,
361 size: u32,
362 ) -> io::Result<GetxattrReply> {
363 match self.get_file_config(&inode)? {
Victor Hsieh88e50172021-10-15 13:27:13 -0700364 FileConfig::VerifiedNew { editor } => {
Victor Hsieh71f10032021-08-13 11:24:02 -0700365 // FUSE ioctl is limited, thus we can't implement fs-verity ioctls without a kernel
366 // change (see b/196635431). Until it's possible, use xattr to expose what we need
367 // as an authfs specific API.
368 if name != CStr::from_bytes_with_nul(b"authfs.fsverity.digest\0").unwrap() {
369 return Err(io::Error::from_raw_os_error(libc::ENODATA));
370 }
371
372 if size == 0 {
373 // Per protocol, when size is 0, return the value size.
374 Ok(GetxattrReply::Count(editor.get_fsverity_digest_size() as u32))
375 } else {
376 let digest = editor.calculate_fsverity_digest()?;
377 if digest.len() > size as usize {
378 Err(io::Error::from_raw_os_error(libc::ERANGE))
379 } else {
380 Ok(GetxattrReply::Value(digest.to_vec()))
381 }
382 }
383 }
384 _ => Err(io::Error::from_raw_os_error(libc::ENODATA)),
385 }
386 }
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800387}
388
389/// Mount and start the FUSE instance. This requires CAP_SYS_ADMIN.
390pub fn loop_forever(
391 file_pool: BTreeMap<Inode, FileConfig>,
392 mountpoint: &Path,
Victor Hsieh4cc3b792021-08-04 12:00:04 -0700393 extra_options: &Option<String>,
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800394) -> Result<(), fuse::Error> {
395 let max_read: u32 = 65536;
396 let max_write: u32 = 65536;
397 let dev_fuse = OpenOptions::new()
398 .read(true)
399 .write(true)
400 .open("/dev/fuse")
401 .expect("Failed to open /dev/fuse");
402
Victor Hsieh4cc3b792021-08-04 12:00:04 -0700403 let mut mount_options = vec![
404 MountOption::FD(dev_fuse.as_raw_fd()),
405 MountOption::RootMode(libc::S_IFDIR | libc::S_IXUSR | libc::S_IXGRP | libc::S_IXOTH),
406 MountOption::AllowOther,
407 MountOption::UserId(0),
408 MountOption::GroupId(0),
409 MountOption::MaxRead(max_read),
410 ];
411 if let Some(value) = extra_options {
412 mount_options.push(MountOption::Extra(value));
413 }
414
415 fuse::mount(mountpoint, "authfs", libc::MS_NOSUID | libc::MS_NODEV, &mount_options)
416 .expect("Failed to mount fuse");
Victor Hsieh88ac6ca2020-11-13 15:20:24 -0800417
418 fuse::worker::start_message_loop(
419 dev_fuse,
420 max_write,
421 max_read,
422 AuthFs::new(file_pool, max_write),
423 )
424}