blob: 5137a2e13964ba3b6e2ceb2359730f7b3b8809d2 [file] [log] [blame]
Victor Hsieh42cc7762021-01-25 16:44:19 -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
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
Victor Hsieh4dc85c92021-03-15 11:01:23 -070028mod fsverity;
29
Victor Hsieh42cc7762021-01-25 16:44:19 -080030use std::cmp::min;
31use std::collections::BTreeMap;
32use std::convert::TryInto;
33use std::ffi::CString;
34use std::fs::File;
35use std::io;
36use std::os::unix::fs::FileExt;
Victor Hsieh4dc85c92021-03-15 11:01:23 -070037use std::os::unix::io::{AsRawFd, FromRawFd};
Victor Hsieh42cc7762021-01-25 16:44:19 -080038
39use anyhow::{bail, Context, Result};
Victor Hsieh2445e332021-06-04 16:44:53 -070040use binder::unstable_api::AsNative;
Victor Hsieh42cc7762021-01-25 16:44:19 -080041use log::{debug, error};
42
43use authfs_aidl_interface::aidl::com::android::virt::fs::IVirtFdService::{
44 BnVirtFdService, IVirtFdService, ERROR_IO, ERROR_UNKNOWN_FD, MAX_REQUESTING_DATA,
45};
46use authfs_aidl_interface::binder::{
Andrew Walbran4de28782021-04-13 14:51:43 +000047 add_service, BinderFeatures, ExceptionCode, Interface, ProcessState, Result as BinderResult,
48 Status, StatusCode, Strong,
Victor Hsieh42cc7762021-01-25 16:44:19 -080049};
50
51const SERVICE_NAME: &str = "authfs_fd_server";
Victor Hsieh2445e332021-06-04 16:44:53 -070052const RPC_SERVICE_PORT: u32 = 3264; // TODO: support dynamic port for multiple fd_server instances
Victor Hsieh42cc7762021-01-25 16:44:19 -080053
54fn new_binder_exception<T: AsRef<str>>(exception: ExceptionCode, message: T) -> Status {
55 Status::new_exception(exception, CString::new(message.as_ref()).as_deref().ok())
56}
57
58fn validate_and_cast_offset(offset: i64) -> Result<u64, Status> {
59 offset.try_into().map_err(|_| {
60 new_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT, format!("Invalid offset: {}", offset))
61 })
62}
63
64fn validate_and_cast_size(size: i32) -> Result<usize, Status> {
65 if size > MAX_REQUESTING_DATA {
66 Err(new_binder_exception(
67 ExceptionCode::ILLEGAL_ARGUMENT,
68 format!("Unexpectedly large size: {}", size),
69 ))
70 } else {
71 size.try_into().map_err(|_| {
72 new_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT, format!("Invalid size: {}", size))
73 })
74 }
75}
76
Victor Hsieh60acfd32021-02-23 13:08:13 -080077/// Configuration of a file descriptor to be served/exposed/shared.
78enum FdConfig {
79 /// A read-only file to serve by this server. The file is supposed to be verifiable with the
80 /// associated fs-verity metadata.
81 Readonly {
82 /// The file to read from. fs-verity metadata can be retrieved from this file's FD.
83 file: File,
Victor Hsieh42cc7762021-01-25 16:44:19 -080084
Victor Hsieh60acfd32021-02-23 13:08:13 -080085 /// Alternative Merkle tree stored in another file.
86 alt_merkle_tree: Option<File>,
Victor Hsieh42cc7762021-01-25 16:44:19 -080087
Victor Hsieh60acfd32021-02-23 13:08:13 -080088 /// Alternative signature stored in another file.
89 alt_signature: Option<File>,
90 },
91
92 /// A readable/writable file to serve by this server. This backing file should just be a
93 /// regular file and does not have any specific property.
94 ReadWrite(File),
Victor Hsieh42cc7762021-01-25 16:44:19 -080095}
96
97struct FdService {
Victor Hsieh60acfd32021-02-23 13:08:13 -080098 /// A pool of opened files, may be readonly or read-writable.
99 fd_pool: BTreeMap<i32, FdConfig>,
Victor Hsieh42cc7762021-01-25 16:44:19 -0800100}
101
102impl FdService {
Victor Hsieh60acfd32021-02-23 13:08:13 -0800103 pub fn new_binder(fd_pool: BTreeMap<i32, FdConfig>) -> Strong<dyn IVirtFdService> {
Andrew Walbran4de28782021-04-13 14:51:43 +0000104 BnVirtFdService::new_binder(FdService { fd_pool }, BinderFeatures::default())
Victor Hsieh42cc7762021-01-25 16:44:19 -0800105 }
106
Victor Hsieh60acfd32021-02-23 13:08:13 -0800107 fn get_file_config(&self, id: i32) -> BinderResult<&FdConfig> {
Victor Hsieh42cc7762021-01-25 16:44:19 -0800108 self.fd_pool.get(&id).ok_or_else(|| Status::from(ERROR_UNKNOWN_FD))
109 }
Victor Hsieh42cc7762021-01-25 16:44:19 -0800110}
111
112impl Interface for FdService {}
113
114impl IVirtFdService for FdService {
115 fn readFile(&self, id: i32, offset: i64, size: i32) -> BinderResult<Vec<u8>> {
116 let size: usize = validate_and_cast_size(size)?;
117 let offset: u64 = validate_and_cast_offset(offset)?;
118
Victor Hsieh60acfd32021-02-23 13:08:13 -0800119 match self.get_file_config(id)? {
120 FdConfig::Readonly { file, .. } | FdConfig::ReadWrite(file) => {
121 read_into_buf(&file, size, offset).map_err(|e| {
122 error!("readFile: read error: {}", e);
123 Status::from(ERROR_IO)
124 })
125 }
126 }
Victor Hsieh42cc7762021-01-25 16:44:19 -0800127 }
128
129 fn readFsverityMerkleTree(&self, id: i32, offset: i64, size: i32) -> BinderResult<Vec<u8>> {
130 let size: usize = validate_and_cast_size(size)?;
131 let offset: u64 = validate_and_cast_offset(offset)?;
132
Victor Hsieh60acfd32021-02-23 13:08:13 -0800133 match &self.get_file_config(id)? {
Victor Hsieh4dc85c92021-03-15 11:01:23 -0700134 FdConfig::Readonly { file, alt_merkle_tree, .. } => {
135 if let Some(tree_file) = &alt_merkle_tree {
136 read_into_buf(&tree_file, size, offset).map_err(|e| {
Victor Hsieh60acfd32021-02-23 13:08:13 -0800137 error!("readFsverityMerkleTree: read error: {}", e);
138 Status::from(ERROR_IO)
139 })
140 } else {
Victor Hsieh4dc85c92021-03-15 11:01:23 -0700141 let mut buf = vec![0; size];
142 let s = fsverity::read_merkle_tree(file.as_raw_fd(), offset, &mut buf)
143 .map_err(|e| {
144 error!("readFsverityMerkleTree: failed to retrieve merkle tree: {}", e);
145 Status::from(e.raw_os_error().unwrap_or(ERROR_IO))
146 })?;
147 debug_assert!(s <= buf.len(), "Shouldn't return more bytes than asked");
148 buf.truncate(s);
149 Ok(buf)
Victor Hsieh60acfd32021-02-23 13:08:13 -0800150 }
151 }
152 FdConfig::ReadWrite(_file) => {
153 // For a writable file, Merkle tree is not expected to be served since Auth FS
154 // doesn't trust it anyway. Auth FS may keep the Merkle tree privately for its own
155 // use.
156 Err(new_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION, "Unsupported"))
157 }
Victor Hsieh42cc7762021-01-25 16:44:19 -0800158 }
159 }
160
161 fn readFsveritySignature(&self, id: i32) -> BinderResult<Vec<u8>> {
Victor Hsieh60acfd32021-02-23 13:08:13 -0800162 match &self.get_file_config(id)? {
Victor Hsieh4dc85c92021-03-15 11:01:23 -0700163 FdConfig::Readonly { file, alt_signature, .. } => {
164 if let Some(sig_file) = &alt_signature {
Victor Hsieh60acfd32021-02-23 13:08:13 -0800165 // Supposedly big enough buffer size to store signature.
166 let size = MAX_REQUESTING_DATA as usize;
Victor Hsieh4dc85c92021-03-15 11:01:23 -0700167 let offset = 0;
168 read_into_buf(&sig_file, size, offset).map_err(|e| {
Victor Hsieh60acfd32021-02-23 13:08:13 -0800169 error!("readFsveritySignature: read error: {}", e);
170 Status::from(ERROR_IO)
171 })
172 } else {
Victor Hsieh4dc85c92021-03-15 11:01:23 -0700173 let mut buf = vec![0; MAX_REQUESTING_DATA as usize];
174 let s = fsverity::read_signature(file.as_raw_fd(), &mut buf).map_err(|e| {
175 error!("readFsverityMerkleTree: failed to retrieve merkle tree: {}", e);
176 Status::from(e.raw_os_error().unwrap_or(ERROR_IO))
177 })?;
178 debug_assert!(s <= buf.len(), "Shouldn't return more bytes than asked");
179 buf.truncate(s);
180 Ok(buf)
Victor Hsieh60acfd32021-02-23 13:08:13 -0800181 }
182 }
183 FdConfig::ReadWrite(_file) => {
184 // There is no signature for a writable file.
185 Err(new_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION, "Unsupported"))
186 }
187 }
188 }
189
190 fn writeFile(&self, id: i32, buf: &[u8], offset: i64) -> BinderResult<i32> {
191 match &self.get_file_config(id)? {
192 FdConfig::Readonly { .. } => Err(StatusCode::INVALID_OPERATION.into()),
193 FdConfig::ReadWrite(file) => {
194 let offset: u64 = offset.try_into().map_err(|_| {
195 new_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT, "Invalid offset")
196 })?;
197 // Check buffer size just to make `as i32` safe below.
198 if buf.len() > i32::MAX as usize {
199 return Err(new_binder_exception(
200 ExceptionCode::ILLEGAL_ARGUMENT,
201 "Buffer size is too big",
202 ));
203 }
204 Ok(file.write_at(buf, offset).map_err(|e| {
205 error!("writeFile: write error: {}", e);
206 Status::from(ERROR_IO)
207 })? as i32)
208 }
Victor Hsieh42cc7762021-01-25 16:44:19 -0800209 }
210 }
Victor Hsieh9d0ab622021-04-26 17:07:02 -0700211
212 fn resize(&self, id: i32, size: i64) -> BinderResult<()> {
213 match &self.get_file_config(id)? {
214 FdConfig::Readonly { .. } => Err(StatusCode::INVALID_OPERATION.into()),
215 FdConfig::ReadWrite(file) => {
216 if size < 0 {
217 return Err(new_binder_exception(
218 ExceptionCode::ILLEGAL_ARGUMENT,
219 "Invalid size to resize to",
220 ));
221 }
222 file.set_len(size as u64).map_err(|e| {
223 error!("resize: set_len error: {}", e);
224 Status::from(ERROR_IO)
225 })
226 }
227 }
228 }
Victor Hsieh42cc7762021-01-25 16:44:19 -0800229}
230
231fn read_into_buf(file: &File, max_size: usize, offset: u64) -> io::Result<Vec<u8>> {
232 let remaining = file.metadata()?.len().saturating_sub(offset);
233 let buf_size = min(remaining, max_size as u64) as usize;
234 let mut buf = vec![0; buf_size];
235 file.read_exact_at(&mut buf, offset)?;
236 Ok(buf)
237}
238
239fn is_fd_valid(fd: i32) -> bool {
240 // SAFETY: a query-only syscall
241 let retval = unsafe { libc::fcntl(fd, libc::F_GETFD) };
242 retval >= 0
243}
244
245fn fd_to_file(fd: i32) -> Result<File> {
246 if !is_fd_valid(fd) {
247 bail!("Bad FD: {}", fd);
248 }
249 // SAFETY: The caller is supposed to provide valid FDs to this process.
250 Ok(unsafe { File::from_raw_fd(fd) })
251}
252
Victor Hsieh60acfd32021-02-23 13:08:13 -0800253fn parse_arg_ro_fds(arg: &str) -> Result<(i32, FdConfig)> {
Victor Hsieh42cc7762021-01-25 16:44:19 -0800254 let result: Result<Vec<i32>, _> = arg.split(':').map(|x| x.parse::<i32>()).collect();
255 let fds = result?;
256 if fds.len() > 3 {
257 bail!("Too many options: {}", arg);
258 }
Victor Hsieh42cc7762021-01-25 16:44:19 -0800259 Ok((
260 fds[0],
Victor Hsieh60acfd32021-02-23 13:08:13 -0800261 FdConfig::Readonly {
Victor Hsieh42cc7762021-01-25 16:44:19 -0800262 file: fd_to_file(fds[0])?,
Victor Hsieh60acfd32021-02-23 13:08:13 -0800263 // Alternative Merkle tree, if provided
264 alt_merkle_tree: fds.get(1).map(|fd| fd_to_file(*fd)).transpose()?,
265 // Alternative signature, if provided
266 alt_signature: fds.get(2).map(|fd| fd_to_file(*fd)).transpose()?,
Victor Hsieh42cc7762021-01-25 16:44:19 -0800267 },
268 ))
269}
270
Victor Hsieh60acfd32021-02-23 13:08:13 -0800271fn parse_arg_rw_fds(arg: &str) -> Result<(i32, FdConfig)> {
272 let fd = arg.parse::<i32>()?;
273 let file = fd_to_file(fd)?;
274 if file.metadata()?.len() > 0 {
275 bail!("File is expected to be empty");
276 }
277 Ok((fd, FdConfig::ReadWrite(file)))
278}
279
Victor Hsieh2445e332021-06-04 16:44:53 -0700280fn parse_args() -> Result<(bool, BTreeMap<i32, FdConfig>)> {
Victor Hsieh42cc7762021-01-25 16:44:19 -0800281 #[rustfmt::skip]
282 let matches = clap::App::new("fd_server")
283 .arg(clap::Arg::with_name("ro-fds")
284 .long("ro-fds")
Victor Hsieh60acfd32021-02-23 13:08:13 -0800285 .multiple(true)
286 .number_of_values(1))
287 .arg(clap::Arg::with_name("rw-fds")
288 .long("rw-fds")
Victor Hsieh42cc7762021-01-25 16:44:19 -0800289 .multiple(true)
290 .number_of_values(1))
Victor Hsieh2445e332021-06-04 16:44:53 -0700291 .arg(clap::Arg::with_name("rpc-binder")
292 .long("rpc-binder"))
Victor Hsieh42cc7762021-01-25 16:44:19 -0800293 .get_matches();
294
295 let mut fd_pool = BTreeMap::new();
296 if let Some(args) = matches.values_of("ro-fds") {
297 for arg in args {
298 let (fd, config) = parse_arg_ro_fds(arg)?;
299 fd_pool.insert(fd, config);
300 }
301 }
Victor Hsieh60acfd32021-02-23 13:08:13 -0800302 if let Some(args) = matches.values_of("rw-fds") {
303 for arg in args {
304 let (fd, config) = parse_arg_rw_fds(arg)?;
305 fd_pool.insert(fd, config);
306 }
307 }
Victor Hsieh2445e332021-06-04 16:44:53 -0700308
309 let rpc_binder = matches.is_present("rpc-binder");
310 Ok((rpc_binder, fd_pool))
Victor Hsieh42cc7762021-01-25 16:44:19 -0800311}
312
313fn main() -> Result<()> {
Victor Hsieh60acfd32021-02-23 13:08:13 -0800314 android_logger::init_once(
315 android_logger::Config::default().with_tag("fd_server").with_min_level(log::Level::Debug),
316 );
317
Victor Hsieh2445e332021-06-04 16:44:53 -0700318 let (rpc_binder, fd_pool) = parse_args()?;
Victor Hsieh42cc7762021-01-25 16:44:19 -0800319
Victor Hsieh2445e332021-06-04 16:44:53 -0700320 if rpc_binder {
321 let mut service = FdService::new_binder(fd_pool).as_binder();
322 debug!("fd_server is starting as a rpc service.");
323 // SAFETY: Service ownership is transferring to the server and won't be valid afterward.
324 // Plus the binder objects are threadsafe.
325 let retval = unsafe {
326 binder_rpc_unstable_bindgen::RunRpcServer(
327 service.as_native_mut() as *mut binder_rpc_unstable_bindgen::AIBinder,
328 RPC_SERVICE_PORT,
329 )
330 };
331 if retval {
332 debug!("RPC server has shut down gracefully");
333 Ok(())
334 } else {
335 bail!("Premature termination of RPC server");
336 }
337 } else {
338 ProcessState::start_thread_pool();
339 let service = FdService::new_binder(fd_pool).as_binder();
340 add_service(SERVICE_NAME, service)
341 .with_context(|| format!("Failed to register service {}", SERVICE_NAME))?;
342 debug!("fd_server is running as a local service.");
343 ProcessState::join_thread_pool();
344 bail!("Unexpected exit after join_thread_pool")
345 }
Victor Hsieh42cc7762021-01-25 16:44:19 -0800346}