blob: 7e551a3248513347243f0f0b119a2e44a4db83dc [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;
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
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};
46
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
49fn new_binder_exception<T: AsRef<str>>(exception: ExceptionCode, message: T) -> Status {
50 Status::new_exception(exception, CString::new(message.as_ref()).as_deref().ok())
51}
52
53fn validate_and_cast_offset(offset: i64) -> Result<u64, Status> {
54 offset.try_into().map_err(|_| {
55 new_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT, format!("Invalid offset: {}", offset))
56 })
57}
58
59fn validate_and_cast_size(size: i32) -> Result<usize, Status> {
60 if size > MAX_REQUESTING_DATA {
61 Err(new_binder_exception(
62 ExceptionCode::ILLEGAL_ARGUMENT,
63 format!("Unexpectedly large size: {}", size),
64 ))
65 } else {
66 size.try_into().map_err(|_| {
67 new_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT, format!("Invalid size: {}", size))
68 })
69 }
70}
71
Victor Hsieh60acfd32021-02-23 13:08:13 -080072/// Configuration of a file descriptor to be served/exposed/shared.
73enum FdConfig {
74 /// A read-only file to serve by this server. The file is supposed to be verifiable with the
75 /// associated fs-verity metadata.
76 Readonly {
77 /// The file to read from. fs-verity metadata can be retrieved from this file's FD.
78 file: File,
Victor Hsieh42cc7762021-01-25 16:44:19 -080079
Victor Hsieh60acfd32021-02-23 13:08:13 -080080 /// Alternative Merkle tree stored in another file.
81 alt_merkle_tree: Option<File>,
Victor Hsieh42cc7762021-01-25 16:44:19 -080082
Victor Hsieh60acfd32021-02-23 13:08:13 -080083 /// Alternative signature stored in another file.
84 alt_signature: Option<File>,
85 },
86
87 /// A readable/writable file to serve by this server. This backing file should just be a
88 /// regular file and does not have any specific property.
89 ReadWrite(File),
Victor Hsieh42cc7762021-01-25 16:44:19 -080090}
91
92struct FdService {
Victor Hsieh60acfd32021-02-23 13:08:13 -080093 /// A pool of opened files, may be readonly or read-writable.
94 fd_pool: BTreeMap<i32, FdConfig>,
Victor Hsieh42cc7762021-01-25 16:44:19 -080095}
96
97impl FdService {
Victor Hsieh60acfd32021-02-23 13:08:13 -080098 pub fn new_binder(fd_pool: BTreeMap<i32, FdConfig>) -> Strong<dyn IVirtFdService> {
Andrew Walbran4de28782021-04-13 14:51:43 +000099 BnVirtFdService::new_binder(FdService { fd_pool }, BinderFeatures::default())
Victor Hsieh42cc7762021-01-25 16:44:19 -0800100 }
101
Victor Hsieh60acfd32021-02-23 13:08:13 -0800102 fn get_file_config(&self, id: i32) -> BinderResult<&FdConfig> {
Victor Hsieh42cc7762021-01-25 16:44:19 -0800103 self.fd_pool.get(&id).ok_or_else(|| Status::from(ERROR_UNKNOWN_FD))
104 }
Victor Hsieh42cc7762021-01-25 16:44:19 -0800105}
106
107impl Interface for FdService {}
108
109impl IVirtFdService for FdService {
110 fn readFile(&self, id: i32, offset: i64, size: i32) -> BinderResult<Vec<u8>> {
111 let size: usize = validate_and_cast_size(size)?;
112 let offset: u64 = validate_and_cast_offset(offset)?;
113
Victor Hsieh60acfd32021-02-23 13:08:13 -0800114 match self.get_file_config(id)? {
115 FdConfig::Readonly { file, .. } | FdConfig::ReadWrite(file) => {
Chris Wailes68c39f82021-07-27 16:03:44 -0700116 read_into_buf(file, size, offset).map_err(|e| {
Victor Hsieh60acfd32021-02-23 13:08:13 -0800117 error!("readFile: read error: {}", e);
118 Status::from(ERROR_IO)
119 })
120 }
121 }
Victor Hsieh42cc7762021-01-25 16:44:19 -0800122 }
123
124 fn readFsverityMerkleTree(&self, id: i32, offset: i64, size: i32) -> BinderResult<Vec<u8>> {
125 let size: usize = validate_and_cast_size(size)?;
126 let offset: u64 = validate_and_cast_offset(offset)?;
127
Victor Hsieh60acfd32021-02-23 13:08:13 -0800128 match &self.get_file_config(id)? {
Victor Hsieh4dc85c92021-03-15 11:01:23 -0700129 FdConfig::Readonly { file, alt_merkle_tree, .. } => {
130 if let Some(tree_file) = &alt_merkle_tree {
Chris Wailes68c39f82021-07-27 16:03:44 -0700131 read_into_buf(tree_file, size, offset).map_err(|e| {
Victor Hsieh60acfd32021-02-23 13:08:13 -0800132 error!("readFsverityMerkleTree: read error: {}", e);
133 Status::from(ERROR_IO)
134 })
135 } else {
Victor Hsieh4dc85c92021-03-15 11:01:23 -0700136 let mut buf = vec![0; size];
137 let s = fsverity::read_merkle_tree(file.as_raw_fd(), offset, &mut buf)
138 .map_err(|e| {
139 error!("readFsverityMerkleTree: failed to retrieve merkle tree: {}", e);
140 Status::from(e.raw_os_error().unwrap_or(ERROR_IO))
141 })?;
142 debug_assert!(s <= buf.len(), "Shouldn't return more bytes than asked");
143 buf.truncate(s);
144 Ok(buf)
Victor Hsieh60acfd32021-02-23 13:08:13 -0800145 }
146 }
147 FdConfig::ReadWrite(_file) => {
148 // For a writable file, Merkle tree is not expected to be served since Auth FS
149 // doesn't trust it anyway. Auth FS may keep the Merkle tree privately for its own
150 // use.
151 Err(new_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION, "Unsupported"))
152 }
Victor Hsieh42cc7762021-01-25 16:44:19 -0800153 }
154 }
155
156 fn readFsveritySignature(&self, id: i32) -> BinderResult<Vec<u8>> {
Victor Hsieh60acfd32021-02-23 13:08:13 -0800157 match &self.get_file_config(id)? {
Victor Hsieh4dc85c92021-03-15 11:01:23 -0700158 FdConfig::Readonly { file, alt_signature, .. } => {
159 if let Some(sig_file) = &alt_signature {
Victor Hsieh60acfd32021-02-23 13:08:13 -0800160 // Supposedly big enough buffer size to store signature.
161 let size = MAX_REQUESTING_DATA as usize;
Victor Hsieh4dc85c92021-03-15 11:01:23 -0700162 let offset = 0;
Chris Wailes68c39f82021-07-27 16:03:44 -0700163 read_into_buf(sig_file, size, offset).map_err(|e| {
Victor Hsieh60acfd32021-02-23 13:08:13 -0800164 error!("readFsveritySignature: read error: {}", e);
165 Status::from(ERROR_IO)
166 })
167 } else {
Victor Hsieh4dc85c92021-03-15 11:01:23 -0700168 let mut buf = vec![0; MAX_REQUESTING_DATA as usize];
169 let s = fsverity::read_signature(file.as_raw_fd(), &mut buf).map_err(|e| {
170 error!("readFsverityMerkleTree: failed to retrieve merkle tree: {}", e);
171 Status::from(e.raw_os_error().unwrap_or(ERROR_IO))
172 })?;
173 debug_assert!(s <= buf.len(), "Shouldn't return more bytes than asked");
174 buf.truncate(s);
175 Ok(buf)
Victor Hsieh60acfd32021-02-23 13:08:13 -0800176 }
177 }
178 FdConfig::ReadWrite(_file) => {
179 // There is no signature for a writable file.
180 Err(new_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION, "Unsupported"))
181 }
182 }
183 }
184
185 fn writeFile(&self, id: i32, buf: &[u8], offset: i64) -> BinderResult<i32> {
186 match &self.get_file_config(id)? {
187 FdConfig::Readonly { .. } => Err(StatusCode::INVALID_OPERATION.into()),
188 FdConfig::ReadWrite(file) => {
189 let offset: u64 = offset.try_into().map_err(|_| {
190 new_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT, "Invalid offset")
191 })?;
192 // Check buffer size just to make `as i32` safe below.
193 if buf.len() > i32::MAX as usize {
194 return Err(new_binder_exception(
195 ExceptionCode::ILLEGAL_ARGUMENT,
196 "Buffer size is too big",
197 ));
198 }
199 Ok(file.write_at(buf, offset).map_err(|e| {
200 error!("writeFile: write error: {}", e);
201 Status::from(ERROR_IO)
202 })? as i32)
203 }
Victor Hsieh42cc7762021-01-25 16:44:19 -0800204 }
205 }
Victor Hsieh9d0ab622021-04-26 17:07:02 -0700206
207 fn resize(&self, id: i32, size: i64) -> BinderResult<()> {
208 match &self.get_file_config(id)? {
209 FdConfig::Readonly { .. } => Err(StatusCode::INVALID_OPERATION.into()),
210 FdConfig::ReadWrite(file) => {
211 if size < 0 {
212 return Err(new_binder_exception(
213 ExceptionCode::ILLEGAL_ARGUMENT,
214 "Invalid size to resize to",
215 ));
216 }
217 file.set_len(size as u64).map_err(|e| {
218 error!("resize: set_len error: {}", e);
219 Status::from(ERROR_IO)
220 })
221 }
222 }
223 }
Victor Hsieh50d75ac2021-09-03 14:46:55 -0700224
225 fn getFileSize(&self, id: i32) -> BinderResult<i64> {
226 match &self.get_file_config(id)? {
227 FdConfig::Readonly { file, .. } => {
228 let size = file
229 .metadata()
230 .map_err(|e| {
231 error!("getFileSize error: {}", e);
232 Status::from(ERROR_IO)
233 })?
234 .len();
235 Ok(size.try_into().map_err(|e| {
236 error!("getFileSize: File too large: {}", e);
237 Status::from(ERROR_FILE_TOO_LARGE)
238 })?)
239 }
240 FdConfig::ReadWrite(_file) => {
241 // Content and metadata of a writable file needs to be tracked by authfs, since
242 // fd_server isn't considered trusted. So there is no point to support getFileSize
243 // for a writable file.
244 Err(new_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION, "Unsupported"))
245 }
246 }
247 }
Victor Hsieh42cc7762021-01-25 16:44:19 -0800248}
249
250fn read_into_buf(file: &File, max_size: usize, offset: u64) -> io::Result<Vec<u8>> {
251 let remaining = file.metadata()?.len().saturating_sub(offset);
252 let buf_size = min(remaining, max_size as u64) as usize;
253 let mut buf = vec![0; buf_size];
254 file.read_exact_at(&mut buf, offset)?;
255 Ok(buf)
256}
257
258fn is_fd_valid(fd: i32) -> bool {
259 // SAFETY: a query-only syscall
260 let retval = unsafe { libc::fcntl(fd, libc::F_GETFD) };
261 retval >= 0
262}
263
264fn fd_to_file(fd: i32) -> Result<File> {
265 if !is_fd_valid(fd) {
266 bail!("Bad FD: {}", fd);
267 }
268 // SAFETY: The caller is supposed to provide valid FDs to this process.
269 Ok(unsafe { File::from_raw_fd(fd) })
270}
271
Victor Hsieh60acfd32021-02-23 13:08:13 -0800272fn parse_arg_ro_fds(arg: &str) -> Result<(i32, FdConfig)> {
Victor Hsieh42cc7762021-01-25 16:44:19 -0800273 let result: Result<Vec<i32>, _> = arg.split(':').map(|x| x.parse::<i32>()).collect();
274 let fds = result?;
275 if fds.len() > 3 {
276 bail!("Too many options: {}", arg);
277 }
Victor Hsieh42cc7762021-01-25 16:44:19 -0800278 Ok((
279 fds[0],
Victor Hsieh60acfd32021-02-23 13:08:13 -0800280 FdConfig::Readonly {
Victor Hsieh42cc7762021-01-25 16:44:19 -0800281 file: fd_to_file(fds[0])?,
Victor Hsieh60acfd32021-02-23 13:08:13 -0800282 // Alternative Merkle tree, if provided
283 alt_merkle_tree: fds.get(1).map(|fd| fd_to_file(*fd)).transpose()?,
284 // Alternative signature, if provided
285 alt_signature: fds.get(2).map(|fd| fd_to_file(*fd)).transpose()?,
Victor Hsieh42cc7762021-01-25 16:44:19 -0800286 },
287 ))
288}
289
Victor Hsieh60acfd32021-02-23 13:08:13 -0800290fn parse_arg_rw_fds(arg: &str) -> Result<(i32, FdConfig)> {
291 let fd = arg.parse::<i32>()?;
292 let file = fd_to_file(fd)?;
293 if file.metadata()?.len() > 0 {
294 bail!("File is expected to be empty");
295 }
296 Ok((fd, FdConfig::ReadWrite(file)))
297}
298
Victor Hsieh1a8cd042021-09-03 16:29:45 -0700299fn parse_args() -> Result<BTreeMap<i32, FdConfig>> {
Victor Hsieh42cc7762021-01-25 16:44:19 -0800300 #[rustfmt::skip]
301 let matches = clap::App::new("fd_server")
302 .arg(clap::Arg::with_name("ro-fds")
303 .long("ro-fds")
Victor Hsieh60acfd32021-02-23 13:08:13 -0800304 .multiple(true)
305 .number_of_values(1))
306 .arg(clap::Arg::with_name("rw-fds")
307 .long("rw-fds")
Victor Hsieh42cc7762021-01-25 16:44:19 -0800308 .multiple(true)
309 .number_of_values(1))
310 .get_matches();
311
312 let mut fd_pool = BTreeMap::new();
313 if let Some(args) = matches.values_of("ro-fds") {
314 for arg in args {
315 let (fd, config) = parse_arg_ro_fds(arg)?;
316 fd_pool.insert(fd, config);
317 }
318 }
Victor Hsieh60acfd32021-02-23 13:08:13 -0800319 if let Some(args) = matches.values_of("rw-fds") {
320 for arg in args {
321 let (fd, config) = parse_arg_rw_fds(arg)?;
322 fd_pool.insert(fd, config);
323 }
324 }
Victor Hsieh2445e332021-06-04 16:44:53 -0700325
Victor Hsieh1a8cd042021-09-03 16:29:45 -0700326 Ok(fd_pool)
Victor Hsieh42cc7762021-01-25 16:44:19 -0800327}
328
329fn main() -> Result<()> {
Victor Hsieh60acfd32021-02-23 13:08:13 -0800330 android_logger::init_once(
331 android_logger::Config::default().with_tag("fd_server").with_min_level(log::Level::Debug),
332 );
333
Victor Hsieh1a8cd042021-09-03 16:29:45 -0700334 let fd_pool = parse_args()?;
Victor Hsieh42cc7762021-01-25 16:44:19 -0800335
Victor Hsieh1a8cd042021-09-03 16:29:45 -0700336 let mut service = FdService::new_binder(fd_pool).as_binder();
337 debug!("fd_server is starting as a rpc service.");
338 // SAFETY: Service ownership is transferring to the server and won't be valid afterward.
339 // Plus the binder objects are threadsafe.
340 let retval = unsafe {
341 binder_rpc_unstable_bindgen::RunRpcServer(
342 service.as_native_mut() as *mut binder_rpc_unstable_bindgen::AIBinder,
343 RPC_SERVICE_PORT,
344 )
345 };
346 if retval {
347 debug!("RPC server has shut down gracefully");
348 Ok(())
Victor Hsieh2445e332021-06-04 16:44:53 -0700349 } else {
Victor Hsieh1a8cd042021-09-03 16:29:45 -0700350 bail!("Premature termination of RPC server");
Victor Hsieh2445e332021-06-04 16:44:53 -0700351 }
Victor Hsieh42cc7762021-01-25 16:44:19 -0800352}