blob: 32ffc0a20299eb3a923074776d7aa37e8c538ebd [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
Victor Hsieh1a8cd042021-09-03 16:29:45 -070017//! This program is a constrained file/FD server to serve file requests through a remote binder
Victor Hsieh42cc7762021-01-25 16:44:19 -080018//! 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.
Victor Hsieh42cc7762021-01-25 16:44:19 -080024
Victor Hsieh4dc85c92021-03-15 11:01:23 -070025mod fsverity;
26
Victor Hsieh1a8cd042021-09-03 16:29:45 -070027use anyhow::{bail, Result};
Victor Hsieh50d75ac2021-09-03 14:46:55 -070028use binder::unstable_api::AsNative;
29use log::{debug, error};
Victor Hsieh42cc7762021-01-25 16:44:19 -080030use std::cmp::min;
31use std::collections::BTreeMap;
32use std::convert::TryInto;
Victor Hsieh42cc7762021-01-25 16:44:19 -080033use std::fs::File;
34use std::io;
Alan Stokese1b6e1c2021-10-01 12:44:49 +010035use std::os::raw;
Victor Hsieh42cc7762021-01-25 16:44:19 -080036use 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
Victor Hsieh42cc7762021-01-25 16:44:19 -080039use authfs_aidl_interface::aidl::com::android::virt::fs::IVirtFdService::{
Victor Hsieh50d75ac2021-09-03 14:46:55 -070040 BnVirtFdService, IVirtFdService, ERROR_FILE_TOO_LARGE, ERROR_IO, ERROR_UNKNOWN_FD,
41 MAX_REQUESTING_DATA,
Victor Hsieh42cc7762021-01-25 16:44:19 -080042};
43use authfs_aidl_interface::binder::{
Victor Hsieh1a8cd042021-09-03 16:29:45 -070044 BinderFeatures, ExceptionCode, Interface, Result as BinderResult, Status, StatusCode, Strong,
Victor Hsieh42cc7762021-01-25 16:44:19 -080045};
Alan Stokes3189af02021-09-30 17:51:19 +010046use binder_common::new_binder_exception;
Victor Hsieh42cc7762021-01-25 16:44:19 -080047
Victor Hsieh2445e332021-06-04 16:44:53 -070048const RPC_SERVICE_PORT: u32 = 3264; // TODO: support dynamic port for multiple fd_server instances
Victor Hsieh42cc7762021-01-25 16:44:19 -080049
Victor Hsieh42cc7762021-01-25 16:44:19 -080050fn validate_and_cast_offset(offset: i64) -> Result<u64, Status> {
51 offset.try_into().map_err(|_| {
52 new_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT, format!("Invalid offset: {}", offset))
53 })
54}
55
56fn validate_and_cast_size(size: i32) -> Result<usize, Status> {
57 if size > MAX_REQUESTING_DATA {
58 Err(new_binder_exception(
59 ExceptionCode::ILLEGAL_ARGUMENT,
60 format!("Unexpectedly large size: {}", size),
61 ))
62 } else {
63 size.try_into().map_err(|_| {
64 new_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT, format!("Invalid size: {}", size))
65 })
66 }
67}
68
Victor Hsieh60acfd32021-02-23 13:08:13 -080069/// Configuration of a file descriptor to be served/exposed/shared.
70enum FdConfig {
71 /// A read-only file to serve by this server. The file is supposed to be verifiable with the
72 /// associated fs-verity metadata.
73 Readonly {
74 /// The file to read from. fs-verity metadata can be retrieved from this file's FD.
75 file: File,
Victor Hsieh42cc7762021-01-25 16:44:19 -080076
Victor Hsieh60acfd32021-02-23 13:08:13 -080077 /// Alternative Merkle tree stored in another file.
78 alt_merkle_tree: Option<File>,
Victor Hsieh42cc7762021-01-25 16:44:19 -080079
Victor Hsieh60acfd32021-02-23 13:08:13 -080080 /// Alternative signature stored in another file.
81 alt_signature: Option<File>,
82 },
83
84 /// A readable/writable file to serve by this server. This backing file should just be a
85 /// regular file and does not have any specific property.
86 ReadWrite(File),
Victor Hsieh42cc7762021-01-25 16:44:19 -080087}
88
89struct FdService {
Victor Hsieh60acfd32021-02-23 13:08:13 -080090 /// A pool of opened files, may be readonly or read-writable.
91 fd_pool: BTreeMap<i32, FdConfig>,
Victor Hsieh42cc7762021-01-25 16:44:19 -080092}
93
94impl FdService {
Victor Hsieh60acfd32021-02-23 13:08:13 -080095 pub fn new_binder(fd_pool: BTreeMap<i32, FdConfig>) -> Strong<dyn IVirtFdService> {
Andrew Walbran4de28782021-04-13 14:51:43 +000096 BnVirtFdService::new_binder(FdService { fd_pool }, BinderFeatures::default())
Victor Hsieh42cc7762021-01-25 16:44:19 -080097 }
98
Victor Hsieh60acfd32021-02-23 13:08:13 -080099 fn get_file_config(&self, id: i32) -> BinderResult<&FdConfig> {
Victor Hsieh42cc7762021-01-25 16:44:19 -0800100 self.fd_pool.get(&id).ok_or_else(|| Status::from(ERROR_UNKNOWN_FD))
101 }
Victor Hsieh42cc7762021-01-25 16:44:19 -0800102}
103
104impl Interface for FdService {}
105
106impl IVirtFdService for FdService {
107 fn readFile(&self, id: i32, offset: i64, size: i32) -> BinderResult<Vec<u8>> {
108 let size: usize = validate_and_cast_size(size)?;
109 let offset: u64 = validate_and_cast_offset(offset)?;
110
Victor Hsieh60acfd32021-02-23 13:08:13 -0800111 match self.get_file_config(id)? {
112 FdConfig::Readonly { file, .. } | FdConfig::ReadWrite(file) => {
Chris Wailes68c39f82021-07-27 16:03:44 -0700113 read_into_buf(file, size, offset).map_err(|e| {
Victor Hsieh60acfd32021-02-23 13:08:13 -0800114 error!("readFile: read error: {}", e);
115 Status::from(ERROR_IO)
116 })
117 }
118 }
Victor Hsieh42cc7762021-01-25 16:44:19 -0800119 }
120
121 fn readFsverityMerkleTree(&self, id: i32, offset: i64, size: i32) -> BinderResult<Vec<u8>> {
122 let size: usize = validate_and_cast_size(size)?;
123 let offset: u64 = validate_and_cast_offset(offset)?;
124
Victor Hsieh60acfd32021-02-23 13:08:13 -0800125 match &self.get_file_config(id)? {
Victor Hsieh4dc85c92021-03-15 11:01:23 -0700126 FdConfig::Readonly { file, alt_merkle_tree, .. } => {
127 if let Some(tree_file) = &alt_merkle_tree {
Chris Wailes68c39f82021-07-27 16:03:44 -0700128 read_into_buf(tree_file, size, offset).map_err(|e| {
Victor Hsieh60acfd32021-02-23 13:08:13 -0800129 error!("readFsverityMerkleTree: read error: {}", e);
130 Status::from(ERROR_IO)
131 })
132 } else {
Victor Hsieh4dc85c92021-03-15 11:01:23 -0700133 let mut buf = vec![0; size];
134 let s = fsverity::read_merkle_tree(file.as_raw_fd(), offset, &mut buf)
135 .map_err(|e| {
136 error!("readFsverityMerkleTree: failed to retrieve merkle tree: {}", e);
137 Status::from(e.raw_os_error().unwrap_or(ERROR_IO))
138 })?;
139 debug_assert!(s <= buf.len(), "Shouldn't return more bytes than asked");
140 buf.truncate(s);
141 Ok(buf)
Victor Hsieh60acfd32021-02-23 13:08:13 -0800142 }
143 }
144 FdConfig::ReadWrite(_file) => {
145 // For a writable file, Merkle tree is not expected to be served since Auth FS
146 // doesn't trust it anyway. Auth FS may keep the Merkle tree privately for its own
147 // use.
148 Err(new_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION, "Unsupported"))
149 }
Victor Hsieh42cc7762021-01-25 16:44:19 -0800150 }
151 }
152
153 fn readFsveritySignature(&self, id: i32) -> BinderResult<Vec<u8>> {
Victor Hsieh60acfd32021-02-23 13:08:13 -0800154 match &self.get_file_config(id)? {
Victor Hsieh4dc85c92021-03-15 11:01:23 -0700155 FdConfig::Readonly { file, alt_signature, .. } => {
156 if let Some(sig_file) = &alt_signature {
Victor Hsieh60acfd32021-02-23 13:08:13 -0800157 // Supposedly big enough buffer size to store signature.
158 let size = MAX_REQUESTING_DATA as usize;
Victor Hsieh4dc85c92021-03-15 11:01:23 -0700159 let offset = 0;
Chris Wailes68c39f82021-07-27 16:03:44 -0700160 read_into_buf(sig_file, size, offset).map_err(|e| {
Victor Hsieh60acfd32021-02-23 13:08:13 -0800161 error!("readFsveritySignature: read error: {}", e);
162 Status::from(ERROR_IO)
163 })
164 } else {
Victor Hsieh4dc85c92021-03-15 11:01:23 -0700165 let mut buf = vec![0; MAX_REQUESTING_DATA as usize];
166 let s = fsverity::read_signature(file.as_raw_fd(), &mut buf).map_err(|e| {
167 error!("readFsverityMerkleTree: failed to retrieve merkle tree: {}", e);
168 Status::from(e.raw_os_error().unwrap_or(ERROR_IO))
169 })?;
170 debug_assert!(s <= buf.len(), "Shouldn't return more bytes than asked");
171 buf.truncate(s);
172 Ok(buf)
Victor Hsieh60acfd32021-02-23 13:08:13 -0800173 }
174 }
175 FdConfig::ReadWrite(_file) => {
176 // There is no signature for a writable file.
177 Err(new_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION, "Unsupported"))
178 }
179 }
180 }
181
182 fn writeFile(&self, id: i32, buf: &[u8], offset: i64) -> BinderResult<i32> {
183 match &self.get_file_config(id)? {
184 FdConfig::Readonly { .. } => Err(StatusCode::INVALID_OPERATION.into()),
185 FdConfig::ReadWrite(file) => {
186 let offset: u64 = offset.try_into().map_err(|_| {
187 new_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT, "Invalid offset")
188 })?;
189 // Check buffer size just to make `as i32` safe below.
190 if buf.len() > i32::MAX as usize {
191 return Err(new_binder_exception(
192 ExceptionCode::ILLEGAL_ARGUMENT,
193 "Buffer size is too big",
194 ));
195 }
196 Ok(file.write_at(buf, offset).map_err(|e| {
197 error!("writeFile: write error: {}", e);
198 Status::from(ERROR_IO)
199 })? as i32)
200 }
Victor Hsieh42cc7762021-01-25 16:44:19 -0800201 }
202 }
Victor Hsieh9d0ab622021-04-26 17:07:02 -0700203
204 fn resize(&self, id: i32, size: i64) -> BinderResult<()> {
205 match &self.get_file_config(id)? {
206 FdConfig::Readonly { .. } => Err(StatusCode::INVALID_OPERATION.into()),
207 FdConfig::ReadWrite(file) => {
208 if size < 0 {
209 return Err(new_binder_exception(
210 ExceptionCode::ILLEGAL_ARGUMENT,
211 "Invalid size to resize to",
212 ));
213 }
214 file.set_len(size as u64).map_err(|e| {
215 error!("resize: set_len error: {}", e);
216 Status::from(ERROR_IO)
217 })
218 }
219 }
220 }
Victor Hsieh50d75ac2021-09-03 14:46:55 -0700221
222 fn getFileSize(&self, id: i32) -> BinderResult<i64> {
223 match &self.get_file_config(id)? {
224 FdConfig::Readonly { file, .. } => {
225 let size = file
226 .metadata()
227 .map_err(|e| {
228 error!("getFileSize error: {}", e);
229 Status::from(ERROR_IO)
230 })?
231 .len();
232 Ok(size.try_into().map_err(|e| {
233 error!("getFileSize: File too large: {}", e);
234 Status::from(ERROR_FILE_TOO_LARGE)
235 })?)
236 }
237 FdConfig::ReadWrite(_file) => {
238 // Content and metadata of a writable file needs to be tracked by authfs, since
239 // fd_server isn't considered trusted. So there is no point to support getFileSize
240 // for a writable file.
241 Err(new_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION, "Unsupported"))
242 }
243 }
244 }
Victor Hsieh42cc7762021-01-25 16:44:19 -0800245}
246
247fn read_into_buf(file: &File, max_size: usize, offset: u64) -> io::Result<Vec<u8>> {
248 let remaining = file.metadata()?.len().saturating_sub(offset);
249 let buf_size = min(remaining, max_size as u64) as usize;
250 let mut buf = vec![0; buf_size];
251 file.read_exact_at(&mut buf, offset)?;
252 Ok(buf)
253}
254
255fn is_fd_valid(fd: i32) -> bool {
256 // SAFETY: a query-only syscall
257 let retval = unsafe { libc::fcntl(fd, libc::F_GETFD) };
258 retval >= 0
259}
260
261fn fd_to_file(fd: i32) -> Result<File> {
262 if !is_fd_valid(fd) {
263 bail!("Bad FD: {}", fd);
264 }
265 // SAFETY: The caller is supposed to provide valid FDs to this process.
266 Ok(unsafe { File::from_raw_fd(fd) })
267}
268
Victor Hsieh60acfd32021-02-23 13:08:13 -0800269fn parse_arg_ro_fds(arg: &str) -> Result<(i32, FdConfig)> {
Victor Hsieh42cc7762021-01-25 16:44:19 -0800270 let result: Result<Vec<i32>, _> = arg.split(':').map(|x| x.parse::<i32>()).collect();
271 let fds = result?;
272 if fds.len() > 3 {
273 bail!("Too many options: {}", arg);
274 }
Victor Hsieh42cc7762021-01-25 16:44:19 -0800275 Ok((
276 fds[0],
Victor Hsieh60acfd32021-02-23 13:08:13 -0800277 FdConfig::Readonly {
Victor Hsieh42cc7762021-01-25 16:44:19 -0800278 file: fd_to_file(fds[0])?,
Victor Hsieh60acfd32021-02-23 13:08:13 -0800279 // Alternative Merkle tree, if provided
280 alt_merkle_tree: fds.get(1).map(|fd| fd_to_file(*fd)).transpose()?,
281 // Alternative signature, if provided
282 alt_signature: fds.get(2).map(|fd| fd_to_file(*fd)).transpose()?,
Victor Hsieh42cc7762021-01-25 16:44:19 -0800283 },
284 ))
285}
286
Victor Hsieh60acfd32021-02-23 13:08:13 -0800287fn parse_arg_rw_fds(arg: &str) -> Result<(i32, FdConfig)> {
288 let fd = arg.parse::<i32>()?;
289 let file = fd_to_file(fd)?;
290 if file.metadata()?.len() > 0 {
291 bail!("File is expected to be empty");
292 }
293 Ok((fd, FdConfig::ReadWrite(file)))
294}
295
Alan Stokese1b6e1c2021-10-01 12:44:49 +0100296struct Args {
297 fd_pool: BTreeMap<i32, FdConfig>,
298 ready_fd: Option<File>,
299}
300
301fn parse_args() -> Result<Args> {
Victor Hsieh42cc7762021-01-25 16:44:19 -0800302 #[rustfmt::skip]
303 let matches = clap::App::new("fd_server")
304 .arg(clap::Arg::with_name("ro-fds")
305 .long("ro-fds")
Victor Hsieh60acfd32021-02-23 13:08:13 -0800306 .multiple(true)
307 .number_of_values(1))
308 .arg(clap::Arg::with_name("rw-fds")
309 .long("rw-fds")
Victor Hsieh42cc7762021-01-25 16:44:19 -0800310 .multiple(true)
311 .number_of_values(1))
Alan Stokese1b6e1c2021-10-01 12:44:49 +0100312 .arg(clap::Arg::with_name("ready-fd")
313 .long("ready-fd")
314 .takes_value(true))
Victor Hsieh42cc7762021-01-25 16:44:19 -0800315 .get_matches();
316
317 let mut fd_pool = BTreeMap::new();
318 if let Some(args) = matches.values_of("ro-fds") {
319 for arg in args {
320 let (fd, config) = parse_arg_ro_fds(arg)?;
321 fd_pool.insert(fd, config);
322 }
323 }
Victor Hsieh60acfd32021-02-23 13:08:13 -0800324 if let Some(args) = matches.values_of("rw-fds") {
325 for arg in args {
326 let (fd, config) = parse_arg_rw_fds(arg)?;
327 fd_pool.insert(fd, config);
328 }
329 }
Alan Stokese1b6e1c2021-10-01 12:44:49 +0100330 let ready_fd = if let Some(arg) = matches.value_of("ready-fd") {
331 let fd = arg.parse::<i32>()?;
332 Some(fd_to_file(fd)?)
333 } else {
334 None
335 };
336 Ok(Args { fd_pool, ready_fd })
Victor Hsieh42cc7762021-01-25 16:44:19 -0800337}
338
339fn main() -> Result<()> {
Victor Hsieh60acfd32021-02-23 13:08:13 -0800340 android_logger::init_once(
341 android_logger::Config::default().with_tag("fd_server").with_min_level(log::Level::Debug),
342 );
343
Alan Stokese1b6e1c2021-10-01 12:44:49 +0100344 let args = parse_args()?;
Victor Hsieh42cc7762021-01-25 16:44:19 -0800345
Alan Stokese1b6e1c2021-10-01 12:44:49 +0100346 let mut service = FdService::new_binder(args.fd_pool).as_binder();
347 let mut ready_notifier = ReadyNotifier(args.ready_fd);
348
Victor Hsieh1a8cd042021-09-03 16:29:45 -0700349 debug!("fd_server is starting as a rpc service.");
350 // SAFETY: Service ownership is transferring to the server and won't be valid afterward.
351 // Plus the binder objects are threadsafe.
Alan Stokese1b6e1c2021-10-01 12:44:49 +0100352 // RunRpcServerCallback does not retain a reference to ready_callback, and only ever
353 // calls it with the param we provide during the lifetime of ready_notifier.
Victor Hsieh1a8cd042021-09-03 16:29:45 -0700354 let retval = unsafe {
Alan Stokese1b6e1c2021-10-01 12:44:49 +0100355 binder_rpc_unstable_bindgen::RunRpcServerCallback(
Victor Hsieh1a8cd042021-09-03 16:29:45 -0700356 service.as_native_mut() as *mut binder_rpc_unstable_bindgen::AIBinder,
357 RPC_SERVICE_PORT,
Alan Stokese1b6e1c2021-10-01 12:44:49 +0100358 Some(ReadyNotifier::ready_callback),
359 ready_notifier.as_void_ptr(),
Victor Hsieh1a8cd042021-09-03 16:29:45 -0700360 )
361 };
362 if retval {
363 debug!("RPC server has shut down gracefully");
364 Ok(())
Victor Hsieh2445e332021-06-04 16:44:53 -0700365 } else {
Victor Hsieh1a8cd042021-09-03 16:29:45 -0700366 bail!("Premature termination of RPC server");
Victor Hsieh2445e332021-06-04 16:44:53 -0700367 }
Victor Hsieh42cc7762021-01-25 16:44:19 -0800368}
Alan Stokese1b6e1c2021-10-01 12:44:49 +0100369
370struct ReadyNotifier(Option<File>);
371
372impl ReadyNotifier {
373 fn notify(&mut self) {
374 debug!("fd_server is ready");
375 // Close the ready-fd if we were given one to signal our readiness.
376 drop(self.0.take());
377 }
378
379 fn as_void_ptr(&mut self) -> *mut raw::c_void {
380 self as *mut _ as *mut raw::c_void
381 }
382
383 unsafe extern "C" fn ready_callback(param: *mut raw::c_void) {
384 // SAFETY: This is only ever called by RunRpcServerCallback, within the lifetime of the
385 // ReadyNotifier, with param taking the value returned by as_void_ptr (so a properly aligned
386 // non-null pointer to an initialized instance).
387 let ready_notifier = param as *mut Self;
388 ready_notifier.as_mut().unwrap().notify()
389 }
390}