1 /*
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 //! This program is a constrained file/FD server to serve file requests through a remote[1] binder
18 //! service. The file server is not designed to serve arbitrary file paths in the filesystem. On
19 //! the contrary, the server should be configured to start with already opened FDs, and serve the
20 //! client's request against the FDs
21 //!
22 //! For example, `exec 9</path/to/file fd_server --ro-fds 9` starts the binder service. A client
23 //! client can then request the content of file 9 by offset and size.
24 //!
25 //! [1] Since the remote binder is not ready, this currently implementation uses local binder
26 //!     first.
27 
28 mod fsverity;
29 
30 use std::cmp::min;
31 use std::collections::BTreeMap;
32 use std::convert::TryInto;
33 use std::ffi::CString;
34 use std::fs::File;
35 use std::io;
36 use std::os::unix::fs::FileExt;
37 use std::os::unix::io::{AsRawFd, FromRawFd};
38 
39 use anyhow::{bail, Context, Result};
40 use log::{debug, error};
41 
42 use authfs_aidl_interface::aidl::com::android::virt::fs::IVirtFdService::{
43     BnVirtFdService, IVirtFdService, ERROR_IO, ERROR_UNKNOWN_FD, MAX_REQUESTING_DATA,
44 };
45 use authfs_aidl_interface::binder::{
46     add_service, BinderFeatures, ExceptionCode, Interface, ProcessState, Result as BinderResult,
47     Status, StatusCode, Strong,
48 };
49 
50 const SERVICE_NAME: &str = "authfs_fd_server";
51 
52 fn new_binder_exception<T: AsRef<str>>(exception: ExceptionCode, message: T) -> Status {
53     Status::new_exception(exception, CString::new(message.as_ref()).as_deref().ok())
54 }
55 
56 fn validate_and_cast_offset(offset: i64) -> Result<u64, Status> {
57     offset.try_into().map_err(|_| {
58         new_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT, format!("Invalid offset: {}", offset))
59     })
60 }
61 
62 fn validate_and_cast_size(size: i32) -> Result<usize, Status> {
63     if size > MAX_REQUESTING_DATA {
64         Err(new_binder_exception(
65             ExceptionCode::ILLEGAL_ARGUMENT,
66             format!("Unexpectedly large size: {}", size),
67         ))
68     } else {
69         size.try_into().map_err(|_| {
70             new_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT, format!("Invalid size: {}", size))
71         })
72     }
73 }
74 
75 /// Configuration of a file descriptor to be served/exposed/shared.
76 enum FdConfig {
77     /// A read-only file to serve by this server. The file is supposed to be verifiable with the
78     /// associated fs-verity metadata.
79     Readonly {
80         /// The file to read from. fs-verity metadata can be retrieved from this file's FD.
81         file: File,
82 
83         /// Alternative Merkle tree stored in another file.
84         alt_merkle_tree: Option<File>,
85 
86         /// Alternative signature stored in another file.
87         alt_signature: Option<File>,
88     },
89 
90     /// A readable/writable file to serve by this server. This backing file should just be a
91     /// regular file and does not have any specific property.
92     ReadWrite(File),
93 }
94 
95 struct FdService {
96     /// A pool of opened files, may be readonly or read-writable.
97     fd_pool: BTreeMap<i32, FdConfig>,
98 }
99 
100 impl FdService {
101     pub fn new_binder(fd_pool: BTreeMap<i32, FdConfig>) -> Strong<dyn IVirtFdService> {
102         BnVirtFdService::new_binder(FdService { fd_pool }, BinderFeatures::default())
103     }
104 
105     fn get_file_config(&self, id: i32) -> BinderResult<&FdConfig> {
106         self.fd_pool.get(&id).ok_or_else(|| Status::from(ERROR_UNKNOWN_FD))
107     }
108 }
109 
110 impl Interface for FdService {}
111 
112 impl IVirtFdService for FdService {
113     fn readFile(&self, id: i32, offset: i64, size: i32) -> BinderResult<Vec<u8>> {
114         let size: usize = validate_and_cast_size(size)?;
115         let offset: u64 = validate_and_cast_offset(offset)?;
116 
117         match self.get_file_config(id)? {
118             FdConfig::Readonly { file, .. } | FdConfig::ReadWrite(file) => {
119                 read_into_buf(&file, size, offset).map_err(|e| {
120                     error!("readFile: read error: {}", e);
121                     Status::from(ERROR_IO)
122                 })
123             }
124         }
125     }
126 
127     fn readFsverityMerkleTree(&self, id: i32, offset: i64, size: i32) -> BinderResult<Vec<u8>> {
128         let size: usize = validate_and_cast_size(size)?;
129         let offset: u64 = validate_and_cast_offset(offset)?;
130 
131         match &self.get_file_config(id)? {
132             FdConfig::Readonly { file, alt_merkle_tree, .. } => {
133                 if let Some(tree_file) = &alt_merkle_tree {
134                     read_into_buf(&tree_file, size, offset).map_err(|e| {
135                         error!("readFsverityMerkleTree: read error: {}", e);
136                         Status::from(ERROR_IO)
137                     })
138                 } else {
139                     let mut buf = vec![0; size];
140                     let s = fsverity::read_merkle_tree(file.as_raw_fd(), offset, &mut buf)
141                         .map_err(|e| {
142                             error!("readFsverityMerkleTree: failed to retrieve merkle tree: {}", e);
143                             Status::from(e.raw_os_error().unwrap_or(ERROR_IO))
144                         })?;
145                     debug_assert!(s <= buf.len(), "Shouldn't return more bytes than asked");
146                     buf.truncate(s);
147                     Ok(buf)
148                 }
149             }
150             FdConfig::ReadWrite(_file) => {
151                 // For a writable file, Merkle tree is not expected to be served since Auth FS
152                 // doesn't trust it anyway. Auth FS may keep the Merkle tree privately for its own
153                 // use.
154                 Err(new_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION, "Unsupported"))
155             }
156         }
157     }
158 
159     fn readFsveritySignature(&self, id: i32) -> BinderResult<Vec<u8>> {
160         match &self.get_file_config(id)? {
161             FdConfig::Readonly { file, alt_signature, .. } => {
162                 if let Some(sig_file) = &alt_signature {
163                     // Supposedly big enough buffer size to store signature.
164                     let size = MAX_REQUESTING_DATA as usize;
165                     let offset = 0;
166                     read_into_buf(&sig_file, size, offset).map_err(|e| {
167                         error!("readFsveritySignature: read error: {}", e);
168                         Status::from(ERROR_IO)
169                     })
170                 } else {
171                     let mut buf = vec![0; MAX_REQUESTING_DATA as usize];
172                     let s = fsverity::read_signature(file.as_raw_fd(), &mut buf).map_err(|e| {
173                         error!("readFsverityMerkleTree: failed to retrieve merkle tree: {}", e);
174                         Status::from(e.raw_os_error().unwrap_or(ERROR_IO))
175                     })?;
176                     debug_assert!(s <= buf.len(), "Shouldn't return more bytes than asked");
177                     buf.truncate(s);
178                     Ok(buf)
179                 }
180             }
181             FdConfig::ReadWrite(_file) => {
182                 // There is no signature for a writable file.
183                 Err(new_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION, "Unsupported"))
184             }
185         }
186     }
187 
188     fn writeFile(&self, id: i32, buf: &[u8], offset: i64) -> BinderResult<i32> {
189         match &self.get_file_config(id)? {
190             FdConfig::Readonly { .. } => Err(StatusCode::INVALID_OPERATION.into()),
191             FdConfig::ReadWrite(file) => {
192                 let offset: u64 = offset.try_into().map_err(|_| {
193                     new_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT, "Invalid offset")
194                 })?;
195                 // Check buffer size just to make `as i32` safe below.
196                 if buf.len() > i32::MAX as usize {
197                     return Err(new_binder_exception(
198                         ExceptionCode::ILLEGAL_ARGUMENT,
199                         "Buffer size is too big",
200                     ));
201                 }
202                 Ok(file.write_at(buf, offset).map_err(|e| {
203                     error!("writeFile: write error: {}", e);
204                     Status::from(ERROR_IO)
205                 })? as i32)
206             }
207         }
208     }
209 
210     fn resize(&self, id: i32, size: i64) -> BinderResult<()> {
211         match &self.get_file_config(id)? {
212             FdConfig::Readonly { .. } => Err(StatusCode::INVALID_OPERATION.into()),
213             FdConfig::ReadWrite(file) => {
214                 if size < 0 {
215                     return Err(new_binder_exception(
216                         ExceptionCode::ILLEGAL_ARGUMENT,
217                         "Invalid size to resize to",
218                     ));
219                 }
220                 file.set_len(size as u64).map_err(|e| {
221                     error!("resize: set_len error: {}", e);
222                     Status::from(ERROR_IO)
223                 })
224             }
225         }
226     }
227 }
228 
229 fn read_into_buf(file: &File, max_size: usize, offset: u64) -> io::Result<Vec<u8>> {
230     let remaining = file.metadata()?.len().saturating_sub(offset);
231     let buf_size = min(remaining, max_size as u64) as usize;
232     let mut buf = vec![0; buf_size];
233     file.read_exact_at(&mut buf, offset)?;
234     Ok(buf)
235 }
236 
237 fn is_fd_valid(fd: i32) -> bool {
238     // SAFETY: a query-only syscall
239     let retval = unsafe { libc::fcntl(fd, libc::F_GETFD) };
240     retval >= 0
241 }
242 
243 fn fd_to_file(fd: i32) -> Result<File> {
244     if !is_fd_valid(fd) {
245         bail!("Bad FD: {}", fd);
246     }
247     // SAFETY: The caller is supposed to provide valid FDs to this process.
248     Ok(unsafe { File::from_raw_fd(fd) })
249 }
250 
251 fn parse_arg_ro_fds(arg: &str) -> Result<(i32, FdConfig)> {
252     let result: Result<Vec<i32>, _> = arg.split(':').map(|x| x.parse::<i32>()).collect();
253     let fds = result?;
254     if fds.len() > 3 {
255         bail!("Too many options: {}", arg);
256     }
257     Ok((
258         fds[0],
259         FdConfig::Readonly {
260             file: fd_to_file(fds[0])?,
261             // Alternative Merkle tree, if provided
262             alt_merkle_tree: fds.get(1).map(|fd| fd_to_file(*fd)).transpose()?,
263             // Alternative signature, if provided
264             alt_signature: fds.get(2).map(|fd| fd_to_file(*fd)).transpose()?,
265         },
266     ))
267 }
268 
269 fn parse_arg_rw_fds(arg: &str) -> Result<(i32, FdConfig)> {
270     let fd = arg.parse::<i32>()?;
271     let file = fd_to_file(fd)?;
272     if file.metadata()?.len() > 0 {
273         bail!("File is expected to be empty");
274     }
275     Ok((fd, FdConfig::ReadWrite(file)))
276 }
277 
278 fn parse_args() -> Result<BTreeMap<i32, FdConfig>> {
279     #[rustfmt::skip]
280     let matches = clap::App::new("fd_server")
281         .arg(clap::Arg::with_name("ro-fds")
282              .long("ro-fds")
283              .multiple(true)
284              .number_of_values(1))
285         .arg(clap::Arg::with_name("rw-fds")
286              .long("rw-fds")
287              .multiple(true)
288              .number_of_values(1))
289         .get_matches();
290 
291     let mut fd_pool = BTreeMap::new();
292     if let Some(args) = matches.values_of("ro-fds") {
293         for arg in args {
294             let (fd, config) = parse_arg_ro_fds(arg)?;
295             fd_pool.insert(fd, config);
296         }
297     }
298     if let Some(args) = matches.values_of("rw-fds") {
299         for arg in args {
300             let (fd, config) = parse_arg_rw_fds(arg)?;
301             fd_pool.insert(fd, config);
302         }
303     }
304     Ok(fd_pool)
305 }
306 
307 fn main() -> Result<()> {
308     android_logger::init_once(
309         android_logger::Config::default().with_tag("fd_server").with_min_level(log::Level::Debug),
310     );
311 
312     let fd_pool = parse_args()?;
313 
314     ProcessState::start_thread_pool();
315 
316     add_service(SERVICE_NAME, FdService::new_binder(fd_pool).as_binder())
317         .with_context(|| format!("Failed to register service {}", SERVICE_NAME))?;
318     debug!("fd_server is running.");
319 
320     ProcessState::join_thread_pool();
321     bail!("Unexpected exit after join_thread_pool")
322 }
323