blob: 12f013ce9d8abcbb6d631165d68104cd905dc912 [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;
35use std::os::unix::fs::FileExt;
Victor Hsieh4dc85c92021-03-15 11:01:23 -070036use std::os::unix::io::{AsRawFd, FromRawFd};
Victor Hsieh42cc7762021-01-25 16:44:19 -080037
Victor Hsieh42cc7762021-01-25 16:44:19 -080038use authfs_aidl_interface::aidl::com::android::virt::fs::IVirtFdService::{
Victor Hsieh50d75ac2021-09-03 14:46:55 -070039 BnVirtFdService, IVirtFdService, ERROR_FILE_TOO_LARGE, ERROR_IO, ERROR_UNKNOWN_FD,
40 MAX_REQUESTING_DATA,
Victor Hsieh42cc7762021-01-25 16:44:19 -080041};
42use authfs_aidl_interface::binder::{
Victor Hsieh1a8cd042021-09-03 16:29:45 -070043 BinderFeatures, ExceptionCode, Interface, Result as BinderResult, Status, StatusCode, Strong,
Victor Hsieh42cc7762021-01-25 16:44:19 -080044};
Alan Stokes3189af02021-09-30 17:51:19 +010045use binder_common::new_binder_exception;
Victor Hsieh42cc7762021-01-25 16:44:19 -080046
Victor Hsieh2445e332021-06-04 16:44:53 -070047const RPC_SERVICE_PORT: u32 = 3264; // TODO: support dynamic port for multiple fd_server instances
Victor Hsieh42cc7762021-01-25 16:44:19 -080048
Victor Hsieh42cc7762021-01-25 16:44:19 -080049fn validate_and_cast_offset(offset: i64) -> Result<u64, Status> {
50 offset.try_into().map_err(|_| {
51 new_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT, format!("Invalid offset: {}", offset))
52 })
53}
54
55fn validate_and_cast_size(size: i32) -> Result<usize, Status> {
56 if size > MAX_REQUESTING_DATA {
57 Err(new_binder_exception(
58 ExceptionCode::ILLEGAL_ARGUMENT,
59 format!("Unexpectedly large size: {}", size),
60 ))
61 } else {
62 size.try_into().map_err(|_| {
63 new_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT, format!("Invalid size: {}", size))
64 })
65 }
66}
67
Victor Hsieh60acfd32021-02-23 13:08:13 -080068/// Configuration of a file descriptor to be served/exposed/shared.
69enum FdConfig {
70 /// A read-only file to serve by this server. The file is supposed to be verifiable with the
71 /// associated fs-verity metadata.
72 Readonly {
73 /// The file to read from. fs-verity metadata can be retrieved from this file's FD.
74 file: File,
Victor Hsieh42cc7762021-01-25 16:44:19 -080075
Victor Hsieh60acfd32021-02-23 13:08:13 -080076 /// Alternative Merkle tree stored in another file.
77 alt_merkle_tree: Option<File>,
Victor Hsieh42cc7762021-01-25 16:44:19 -080078
Victor Hsieh60acfd32021-02-23 13:08:13 -080079 /// Alternative signature stored in another file.
80 alt_signature: Option<File>,
81 },
82
83 /// A readable/writable file to serve by this server. This backing file should just be a
84 /// regular file and does not have any specific property.
85 ReadWrite(File),
Victor Hsieh42cc7762021-01-25 16:44:19 -080086}
87
88struct FdService {
Victor Hsieh60acfd32021-02-23 13:08:13 -080089 /// A pool of opened files, may be readonly or read-writable.
90 fd_pool: BTreeMap<i32, FdConfig>,
Victor Hsieh42cc7762021-01-25 16:44:19 -080091}
92
93impl FdService {
Victor Hsieh60acfd32021-02-23 13:08:13 -080094 pub fn new_binder(fd_pool: BTreeMap<i32, FdConfig>) -> Strong<dyn IVirtFdService> {
Andrew Walbran4de28782021-04-13 14:51:43 +000095 BnVirtFdService::new_binder(FdService { fd_pool }, BinderFeatures::default())
Victor Hsieh42cc7762021-01-25 16:44:19 -080096 }
97
Victor Hsieh60acfd32021-02-23 13:08:13 -080098 fn get_file_config(&self, id: i32) -> BinderResult<&FdConfig> {
Victor Hsieh42cc7762021-01-25 16:44:19 -080099 self.fd_pool.get(&id).ok_or_else(|| Status::from(ERROR_UNKNOWN_FD))
100 }
Victor Hsieh42cc7762021-01-25 16:44:19 -0800101}
102
103impl Interface for FdService {}
104
105impl IVirtFdService for FdService {
106 fn readFile(&self, id: i32, offset: i64, size: i32) -> BinderResult<Vec<u8>> {
107 let size: usize = validate_and_cast_size(size)?;
108 let offset: u64 = validate_and_cast_offset(offset)?;
109
Victor Hsieh60acfd32021-02-23 13:08:13 -0800110 match self.get_file_config(id)? {
111 FdConfig::Readonly { file, .. } | FdConfig::ReadWrite(file) => {
Chris Wailes68c39f82021-07-27 16:03:44 -0700112 read_into_buf(file, size, offset).map_err(|e| {
Victor Hsieh60acfd32021-02-23 13:08:13 -0800113 error!("readFile: read error: {}", e);
114 Status::from(ERROR_IO)
115 })
116 }
117 }
Victor Hsieh42cc7762021-01-25 16:44:19 -0800118 }
119
120 fn readFsverityMerkleTree(&self, id: i32, offset: i64, size: i32) -> BinderResult<Vec<u8>> {
121 let size: usize = validate_and_cast_size(size)?;
122 let offset: u64 = validate_and_cast_offset(offset)?;
123
Victor Hsieh60acfd32021-02-23 13:08:13 -0800124 match &self.get_file_config(id)? {
Victor Hsieh4dc85c92021-03-15 11:01:23 -0700125 FdConfig::Readonly { file, alt_merkle_tree, .. } => {
126 if let Some(tree_file) = &alt_merkle_tree {
Chris Wailes68c39f82021-07-27 16:03:44 -0700127 read_into_buf(tree_file, size, offset).map_err(|e| {
Victor Hsieh60acfd32021-02-23 13:08:13 -0800128 error!("readFsverityMerkleTree: read error: {}", e);
129 Status::from(ERROR_IO)
130 })
131 } else {
Victor Hsieh4dc85c92021-03-15 11:01:23 -0700132 let mut buf = vec![0; size];
133 let s = fsverity::read_merkle_tree(file.as_raw_fd(), offset, &mut buf)
134 .map_err(|e| {
135 error!("readFsverityMerkleTree: failed to retrieve merkle tree: {}", e);
136 Status::from(e.raw_os_error().unwrap_or(ERROR_IO))
137 })?;
138 debug_assert!(s <= buf.len(), "Shouldn't return more bytes than asked");
139 buf.truncate(s);
140 Ok(buf)
Victor Hsieh60acfd32021-02-23 13:08:13 -0800141 }
142 }
143 FdConfig::ReadWrite(_file) => {
144 // For a writable file, Merkle tree is not expected to be served since Auth FS
145 // doesn't trust it anyway. Auth FS may keep the Merkle tree privately for its own
146 // use.
147 Err(new_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION, "Unsupported"))
148 }
Victor Hsieh42cc7762021-01-25 16:44:19 -0800149 }
150 }
151
152 fn readFsveritySignature(&self, id: i32) -> BinderResult<Vec<u8>> {
Victor Hsieh60acfd32021-02-23 13:08:13 -0800153 match &self.get_file_config(id)? {
Victor Hsieh4dc85c92021-03-15 11:01:23 -0700154 FdConfig::Readonly { file, alt_signature, .. } => {
155 if let Some(sig_file) = &alt_signature {
Victor Hsieh60acfd32021-02-23 13:08:13 -0800156 // Supposedly big enough buffer size to store signature.
157 let size = MAX_REQUESTING_DATA as usize;
Victor Hsieh4dc85c92021-03-15 11:01:23 -0700158 let offset = 0;
Chris Wailes68c39f82021-07-27 16:03:44 -0700159 read_into_buf(sig_file, size, offset).map_err(|e| {
Victor Hsieh60acfd32021-02-23 13:08:13 -0800160 error!("readFsveritySignature: read error: {}", e);
161 Status::from(ERROR_IO)
162 })
163 } else {
Victor Hsieh4dc85c92021-03-15 11:01:23 -0700164 let mut buf = vec![0; MAX_REQUESTING_DATA as usize];
165 let s = fsverity::read_signature(file.as_raw_fd(), &mut buf).map_err(|e| {
166 error!("readFsverityMerkleTree: failed to retrieve merkle tree: {}", e);
167 Status::from(e.raw_os_error().unwrap_or(ERROR_IO))
168 })?;
169 debug_assert!(s <= buf.len(), "Shouldn't return more bytes than asked");
170 buf.truncate(s);
171 Ok(buf)
Victor Hsieh60acfd32021-02-23 13:08:13 -0800172 }
173 }
174 FdConfig::ReadWrite(_file) => {
175 // There is no signature for a writable file.
176 Err(new_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION, "Unsupported"))
177 }
178 }
179 }
180
181 fn writeFile(&self, id: i32, buf: &[u8], offset: i64) -> BinderResult<i32> {
182 match &self.get_file_config(id)? {
183 FdConfig::Readonly { .. } => Err(StatusCode::INVALID_OPERATION.into()),
184 FdConfig::ReadWrite(file) => {
185 let offset: u64 = offset.try_into().map_err(|_| {
186 new_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT, "Invalid offset")
187 })?;
188 // Check buffer size just to make `as i32` safe below.
189 if buf.len() > i32::MAX as usize {
190 return Err(new_binder_exception(
191 ExceptionCode::ILLEGAL_ARGUMENT,
192 "Buffer size is too big",
193 ));
194 }
195 Ok(file.write_at(buf, offset).map_err(|e| {
196 error!("writeFile: write error: {}", e);
197 Status::from(ERROR_IO)
198 })? as i32)
199 }
Victor Hsieh42cc7762021-01-25 16:44:19 -0800200 }
201 }
Victor Hsieh9d0ab622021-04-26 17:07:02 -0700202
203 fn resize(&self, id: i32, size: i64) -> BinderResult<()> {
204 match &self.get_file_config(id)? {
205 FdConfig::Readonly { .. } => Err(StatusCode::INVALID_OPERATION.into()),
206 FdConfig::ReadWrite(file) => {
207 if size < 0 {
208 return Err(new_binder_exception(
209 ExceptionCode::ILLEGAL_ARGUMENT,
210 "Invalid size to resize to",
211 ));
212 }
213 file.set_len(size as u64).map_err(|e| {
214 error!("resize: set_len error: {}", e);
215 Status::from(ERROR_IO)
216 })
217 }
218 }
219 }
Victor Hsieh50d75ac2021-09-03 14:46:55 -0700220
221 fn getFileSize(&self, id: i32) -> BinderResult<i64> {
222 match &self.get_file_config(id)? {
223 FdConfig::Readonly { file, .. } => {
224 let size = file
225 .metadata()
226 .map_err(|e| {
227 error!("getFileSize error: {}", e);
228 Status::from(ERROR_IO)
229 })?
230 .len();
231 Ok(size.try_into().map_err(|e| {
232 error!("getFileSize: File too large: {}", e);
233 Status::from(ERROR_FILE_TOO_LARGE)
234 })?)
235 }
236 FdConfig::ReadWrite(_file) => {
237 // Content and metadata of a writable file needs to be tracked by authfs, since
238 // fd_server isn't considered trusted. So there is no point to support getFileSize
239 // for a writable file.
240 Err(new_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION, "Unsupported"))
241 }
242 }
243 }
Victor Hsieh42cc7762021-01-25 16:44:19 -0800244}
245
246fn read_into_buf(file: &File, max_size: usize, offset: u64) -> io::Result<Vec<u8>> {
247 let remaining = file.metadata()?.len().saturating_sub(offset);
248 let buf_size = min(remaining, max_size as u64) as usize;
249 let mut buf = vec![0; buf_size];
250 file.read_exact_at(&mut buf, offset)?;
251 Ok(buf)
252}
253
254fn is_fd_valid(fd: i32) -> bool {
255 // SAFETY: a query-only syscall
256 let retval = unsafe { libc::fcntl(fd, libc::F_GETFD) };
257 retval >= 0
258}
259
260fn fd_to_file(fd: i32) -> Result<File> {
261 if !is_fd_valid(fd) {
262 bail!("Bad FD: {}", fd);
263 }
264 // SAFETY: The caller is supposed to provide valid FDs to this process.
265 Ok(unsafe { File::from_raw_fd(fd) })
266}
267
Victor Hsieh60acfd32021-02-23 13:08:13 -0800268fn parse_arg_ro_fds(arg: &str) -> Result<(i32, FdConfig)> {
Victor Hsieh42cc7762021-01-25 16:44:19 -0800269 let result: Result<Vec<i32>, _> = arg.split(':').map(|x| x.parse::<i32>()).collect();
270 let fds = result?;
271 if fds.len() > 3 {
272 bail!("Too many options: {}", arg);
273 }
Victor Hsieh42cc7762021-01-25 16:44:19 -0800274 Ok((
275 fds[0],
Victor Hsieh60acfd32021-02-23 13:08:13 -0800276 FdConfig::Readonly {
Victor Hsieh42cc7762021-01-25 16:44:19 -0800277 file: fd_to_file(fds[0])?,
Victor Hsieh60acfd32021-02-23 13:08:13 -0800278 // Alternative Merkle tree, if provided
279 alt_merkle_tree: fds.get(1).map(|fd| fd_to_file(*fd)).transpose()?,
280 // Alternative signature, if provided
281 alt_signature: fds.get(2).map(|fd| fd_to_file(*fd)).transpose()?,
Victor Hsieh42cc7762021-01-25 16:44:19 -0800282 },
283 ))
284}
285
Victor Hsieh60acfd32021-02-23 13:08:13 -0800286fn parse_arg_rw_fds(arg: &str) -> Result<(i32, FdConfig)> {
287 let fd = arg.parse::<i32>()?;
288 let file = fd_to_file(fd)?;
289 if file.metadata()?.len() > 0 {
290 bail!("File is expected to be empty");
291 }
292 Ok((fd, FdConfig::ReadWrite(file)))
293}
294
Victor Hsieh1a8cd042021-09-03 16:29:45 -0700295fn parse_args() -> Result<BTreeMap<i32, FdConfig>> {
Victor Hsieh42cc7762021-01-25 16:44:19 -0800296 #[rustfmt::skip]
297 let matches = clap::App::new("fd_server")
298 .arg(clap::Arg::with_name("ro-fds")
299 .long("ro-fds")
Victor Hsieh60acfd32021-02-23 13:08:13 -0800300 .multiple(true)
301 .number_of_values(1))
302 .arg(clap::Arg::with_name("rw-fds")
303 .long("rw-fds")
Victor Hsieh42cc7762021-01-25 16:44:19 -0800304 .multiple(true)
305 .number_of_values(1))
306 .get_matches();
307
308 let mut fd_pool = BTreeMap::new();
309 if let Some(args) = matches.values_of("ro-fds") {
310 for arg in args {
311 let (fd, config) = parse_arg_ro_fds(arg)?;
312 fd_pool.insert(fd, config);
313 }
314 }
Victor Hsieh60acfd32021-02-23 13:08:13 -0800315 if let Some(args) = matches.values_of("rw-fds") {
316 for arg in args {
317 let (fd, config) = parse_arg_rw_fds(arg)?;
318 fd_pool.insert(fd, config);
319 }
320 }
Victor Hsieh2445e332021-06-04 16:44:53 -0700321
Victor Hsieh1a8cd042021-09-03 16:29:45 -0700322 Ok(fd_pool)
Victor Hsieh42cc7762021-01-25 16:44:19 -0800323}
324
325fn main() -> Result<()> {
Victor Hsieh60acfd32021-02-23 13:08:13 -0800326 android_logger::init_once(
327 android_logger::Config::default().with_tag("fd_server").with_min_level(log::Level::Debug),
328 );
329
Victor Hsieh1a8cd042021-09-03 16:29:45 -0700330 let fd_pool = parse_args()?;
Victor Hsieh42cc7762021-01-25 16:44:19 -0800331
Victor Hsieh1a8cd042021-09-03 16:29:45 -0700332 let mut service = FdService::new_binder(fd_pool).as_binder();
333 debug!("fd_server is starting as a rpc service.");
334 // SAFETY: Service ownership is transferring to the server and won't be valid afterward.
335 // Plus the binder objects are threadsafe.
336 let retval = unsafe {
337 binder_rpc_unstable_bindgen::RunRpcServer(
338 service.as_native_mut() as *mut binder_rpc_unstable_bindgen::AIBinder,
339 RPC_SERVICE_PORT,
340 )
341 };
342 if retval {
343 debug!("RPC server has shut down gracefully");
344 Ok(())
Victor Hsieh2445e332021-06-04 16:44:53 -0700345 } else {
Victor Hsieh1a8cd042021-09-03 16:29:45 -0700346 bail!("Premature termination of RPC server");
Victor Hsieh2445e332021-06-04 16:44:53 -0700347 }
Victor Hsieh42cc7762021-01-25 16:44:19 -0800348}