blob: d35feb12c4f3c013569ced10e79d73c8ee8dd2c7 [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};
Andrew Walbranbb49b442021-03-16 13:53:05 +000040use binder::IBinderInternal; // TODO(178852354): remove once set_requesting_sid is exposed in the API.
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::{
Victor Hsieh60acfd32021-02-23 13:08:13 -080047 add_service, ExceptionCode, Interface, ProcessState, Result as BinderResult, Status,
48 StatusCode, Strong,
Victor Hsieh42cc7762021-01-25 16:44:19 -080049};
50
51const SERVICE_NAME: &str = "authfs_fd_server";
52
53fn new_binder_exception<T: AsRef<str>>(exception: ExceptionCode, message: T) -> Status {
54 Status::new_exception(exception, CString::new(message.as_ref()).as_deref().ok())
55}
56
57fn validate_and_cast_offset(offset: i64) -> Result<u64, Status> {
58 offset.try_into().map_err(|_| {
59 new_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT, format!("Invalid offset: {}", offset))
60 })
61}
62
63fn validate_and_cast_size(size: i32) -> Result<usize, Status> {
64 if size > MAX_REQUESTING_DATA {
65 Err(new_binder_exception(
66 ExceptionCode::ILLEGAL_ARGUMENT,
67 format!("Unexpectedly large size: {}", size),
68 ))
69 } else {
70 size.try_into().map_err(|_| {
71 new_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT, format!("Invalid size: {}", size))
72 })
73 }
74}
75
Victor Hsieh60acfd32021-02-23 13:08:13 -080076/// Configuration of a file descriptor to be served/exposed/shared.
77enum FdConfig {
78 /// A read-only file to serve by this server. The file is supposed to be verifiable with the
79 /// associated fs-verity metadata.
80 Readonly {
81 /// The file to read from. fs-verity metadata can be retrieved from this file's FD.
82 file: File,
Victor Hsieh42cc7762021-01-25 16:44:19 -080083
Victor Hsieh60acfd32021-02-23 13:08:13 -080084 /// Alternative Merkle tree stored in another file.
85 alt_merkle_tree: Option<File>,
Victor Hsieh42cc7762021-01-25 16:44:19 -080086
Victor Hsieh60acfd32021-02-23 13:08:13 -080087 /// Alternative signature stored in another file.
88 alt_signature: Option<File>,
89 },
90
91 /// A readable/writable file to serve by this server. This backing file should just be a
92 /// regular file and does not have any specific property.
93 ReadWrite(File),
Victor Hsieh42cc7762021-01-25 16:44:19 -080094}
95
96struct FdService {
Victor Hsieh60acfd32021-02-23 13:08:13 -080097 /// A pool of opened files, may be readonly or read-writable.
98 fd_pool: BTreeMap<i32, FdConfig>,
Victor Hsieh42cc7762021-01-25 16:44:19 -080099}
100
101impl FdService {
Victor Hsieh60acfd32021-02-23 13:08:13 -0800102 pub fn new_binder(fd_pool: BTreeMap<i32, FdConfig>) -> Strong<dyn IVirtFdService> {
Victor Hsieh42cc7762021-01-25 16:44:19 -0800103 let result = BnVirtFdService::new_binder(FdService { fd_pool });
104 result.as_binder().set_requesting_sid(false);
105 result
106 }
107
Victor Hsieh60acfd32021-02-23 13:08:13 -0800108 fn get_file_config(&self, id: i32) -> BinderResult<&FdConfig> {
Victor Hsieh42cc7762021-01-25 16:44:19 -0800109 self.fd_pool.get(&id).ok_or_else(|| Status::from(ERROR_UNKNOWN_FD))
110 }
Victor Hsieh42cc7762021-01-25 16:44:19 -0800111}
112
113impl Interface for FdService {}
114
115impl IVirtFdService for FdService {
116 fn readFile(&self, id: i32, offset: i64, size: i32) -> BinderResult<Vec<u8>> {
117 let size: usize = validate_and_cast_size(size)?;
118 let offset: u64 = validate_and_cast_offset(offset)?;
119
Victor Hsieh60acfd32021-02-23 13:08:13 -0800120 match self.get_file_config(id)? {
121 FdConfig::Readonly { file, .. } | FdConfig::ReadWrite(file) => {
122 read_into_buf(&file, size, offset).map_err(|e| {
123 error!("readFile: read error: {}", e);
124 Status::from(ERROR_IO)
125 })
126 }
127 }
Victor Hsieh42cc7762021-01-25 16:44:19 -0800128 }
129
130 fn readFsverityMerkleTree(&self, id: i32, offset: i64, size: i32) -> BinderResult<Vec<u8>> {
131 let size: usize = validate_and_cast_size(size)?;
132 let offset: u64 = validate_and_cast_offset(offset)?;
133
Victor Hsieh60acfd32021-02-23 13:08:13 -0800134 match &self.get_file_config(id)? {
Victor Hsieh4dc85c92021-03-15 11:01:23 -0700135 FdConfig::Readonly { file, alt_merkle_tree, .. } => {
136 if let Some(tree_file) = &alt_merkle_tree {
137 read_into_buf(&tree_file, size, offset).map_err(|e| {
Victor Hsieh60acfd32021-02-23 13:08:13 -0800138 error!("readFsverityMerkleTree: read error: {}", e);
139 Status::from(ERROR_IO)
140 })
141 } else {
Victor Hsieh4dc85c92021-03-15 11:01:23 -0700142 let mut buf = vec![0; size];
143 let s = fsverity::read_merkle_tree(file.as_raw_fd(), offset, &mut buf)
144 .map_err(|e| {
145 error!("readFsverityMerkleTree: failed to retrieve merkle tree: {}", e);
146 Status::from(e.raw_os_error().unwrap_or(ERROR_IO))
147 })?;
148 debug_assert!(s <= buf.len(), "Shouldn't return more bytes than asked");
149 buf.truncate(s);
150 Ok(buf)
Victor Hsieh60acfd32021-02-23 13:08:13 -0800151 }
152 }
153 FdConfig::ReadWrite(_file) => {
154 // For a writable file, Merkle tree is not expected to be served since Auth FS
155 // doesn't trust it anyway. Auth FS may keep the Merkle tree privately for its own
156 // use.
157 Err(new_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION, "Unsupported"))
158 }
Victor Hsieh42cc7762021-01-25 16:44:19 -0800159 }
160 }
161
162 fn readFsveritySignature(&self, id: i32) -> BinderResult<Vec<u8>> {
Victor Hsieh60acfd32021-02-23 13:08:13 -0800163 match &self.get_file_config(id)? {
Victor Hsieh4dc85c92021-03-15 11:01:23 -0700164 FdConfig::Readonly { file, alt_signature, .. } => {
165 if let Some(sig_file) = &alt_signature {
Victor Hsieh60acfd32021-02-23 13:08:13 -0800166 // Supposedly big enough buffer size to store signature.
167 let size = MAX_REQUESTING_DATA as usize;
Victor Hsieh4dc85c92021-03-15 11:01:23 -0700168 let offset = 0;
169 read_into_buf(&sig_file, size, offset).map_err(|e| {
Victor Hsieh60acfd32021-02-23 13:08:13 -0800170 error!("readFsveritySignature: read error: {}", e);
171 Status::from(ERROR_IO)
172 })
173 } else {
Victor Hsieh4dc85c92021-03-15 11:01:23 -0700174 let mut buf = vec![0; MAX_REQUESTING_DATA as usize];
175 let s = fsverity::read_signature(file.as_raw_fd(), &mut buf).map_err(|e| {
176 error!("readFsverityMerkleTree: failed to retrieve merkle tree: {}", e);
177 Status::from(e.raw_os_error().unwrap_or(ERROR_IO))
178 })?;
179 debug_assert!(s <= buf.len(), "Shouldn't return more bytes than asked");
180 buf.truncate(s);
181 Ok(buf)
Victor Hsieh60acfd32021-02-23 13:08:13 -0800182 }
183 }
184 FdConfig::ReadWrite(_file) => {
185 // There is no signature for a writable file.
186 Err(new_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION, "Unsupported"))
187 }
188 }
189 }
190
191 fn writeFile(&self, id: i32, buf: &[u8], offset: i64) -> BinderResult<i32> {
192 match &self.get_file_config(id)? {
193 FdConfig::Readonly { .. } => Err(StatusCode::INVALID_OPERATION.into()),
194 FdConfig::ReadWrite(file) => {
195 let offset: u64 = offset.try_into().map_err(|_| {
196 new_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT, "Invalid offset")
197 })?;
198 // Check buffer size just to make `as i32` safe below.
199 if buf.len() > i32::MAX as usize {
200 return Err(new_binder_exception(
201 ExceptionCode::ILLEGAL_ARGUMENT,
202 "Buffer size is too big",
203 ));
204 }
205 Ok(file.write_at(buf, offset).map_err(|e| {
206 error!("writeFile: write error: {}", e);
207 Status::from(ERROR_IO)
208 })? as i32)
209 }
Victor Hsieh42cc7762021-01-25 16:44:19 -0800210 }
211 }
Victor Hsieh9d0ab622021-04-26 17:07:02 -0700212
213 fn resize(&self, id: i32, size: i64) -> BinderResult<()> {
214 match &self.get_file_config(id)? {
215 FdConfig::Readonly { .. } => Err(StatusCode::INVALID_OPERATION.into()),
216 FdConfig::ReadWrite(file) => {
217 if size < 0 {
218 return Err(new_binder_exception(
219 ExceptionCode::ILLEGAL_ARGUMENT,
220 "Invalid size to resize to",
221 ));
222 }
223 file.set_len(size as u64).map_err(|e| {
224 error!("resize: set_len error: {}", e);
225 Status::from(ERROR_IO)
226 })
227 }
228 }
229 }
Victor Hsieh42cc7762021-01-25 16:44:19 -0800230}
231
232fn read_into_buf(file: &File, max_size: usize, offset: u64) -> io::Result<Vec<u8>> {
233 let remaining = file.metadata()?.len().saturating_sub(offset);
234 let buf_size = min(remaining, max_size as u64) as usize;
235 let mut buf = vec![0; buf_size];
236 file.read_exact_at(&mut buf, offset)?;
237 Ok(buf)
238}
239
240fn is_fd_valid(fd: i32) -> bool {
241 // SAFETY: a query-only syscall
242 let retval = unsafe { libc::fcntl(fd, libc::F_GETFD) };
243 retval >= 0
244}
245
246fn fd_to_file(fd: i32) -> Result<File> {
247 if !is_fd_valid(fd) {
248 bail!("Bad FD: {}", fd);
249 }
250 // SAFETY: The caller is supposed to provide valid FDs to this process.
251 Ok(unsafe { File::from_raw_fd(fd) })
252}
253
Victor Hsieh60acfd32021-02-23 13:08:13 -0800254fn parse_arg_ro_fds(arg: &str) -> Result<(i32, FdConfig)> {
Victor Hsieh42cc7762021-01-25 16:44:19 -0800255 let result: Result<Vec<i32>, _> = arg.split(':').map(|x| x.parse::<i32>()).collect();
256 let fds = result?;
257 if fds.len() > 3 {
258 bail!("Too many options: {}", arg);
259 }
Victor Hsieh42cc7762021-01-25 16:44:19 -0800260 Ok((
261 fds[0],
Victor Hsieh60acfd32021-02-23 13:08:13 -0800262 FdConfig::Readonly {
Victor Hsieh42cc7762021-01-25 16:44:19 -0800263 file: fd_to_file(fds[0])?,
Victor Hsieh60acfd32021-02-23 13:08:13 -0800264 // Alternative Merkle tree, if provided
265 alt_merkle_tree: fds.get(1).map(|fd| fd_to_file(*fd)).transpose()?,
266 // Alternative signature, if provided
267 alt_signature: fds.get(2).map(|fd| fd_to_file(*fd)).transpose()?,
Victor Hsieh42cc7762021-01-25 16:44:19 -0800268 },
269 ))
270}
271
Victor Hsieh60acfd32021-02-23 13:08:13 -0800272fn parse_arg_rw_fds(arg: &str) -> Result<(i32, FdConfig)> {
273 let fd = arg.parse::<i32>()?;
274 let file = fd_to_file(fd)?;
275 if file.metadata()?.len() > 0 {
276 bail!("File is expected to be empty");
277 }
278 Ok((fd, FdConfig::ReadWrite(file)))
279}
280
281fn parse_args() -> Result<BTreeMap<i32, FdConfig>> {
Victor Hsieh42cc7762021-01-25 16:44:19 -0800282 #[rustfmt::skip]
283 let matches = clap::App::new("fd_server")
284 .arg(clap::Arg::with_name("ro-fds")
285 .long("ro-fds")
Victor Hsieh60acfd32021-02-23 13:08:13 -0800286 .multiple(true)
287 .number_of_values(1))
288 .arg(clap::Arg::with_name("rw-fds")
289 .long("rw-fds")
Victor Hsieh42cc7762021-01-25 16:44:19 -0800290 .multiple(true)
291 .number_of_values(1))
292 .get_matches();
293
294 let mut fd_pool = BTreeMap::new();
295 if let Some(args) = matches.values_of("ro-fds") {
296 for arg in args {
297 let (fd, config) = parse_arg_ro_fds(arg)?;
298 fd_pool.insert(fd, config);
299 }
300 }
Victor Hsieh60acfd32021-02-23 13:08:13 -0800301 if let Some(args) = matches.values_of("rw-fds") {
302 for arg in args {
303 let (fd, config) = parse_arg_rw_fds(arg)?;
304 fd_pool.insert(fd, config);
305 }
306 }
Victor Hsieh42cc7762021-01-25 16:44:19 -0800307 Ok(fd_pool)
308}
309
310fn main() -> Result<()> {
Victor Hsieh60acfd32021-02-23 13:08:13 -0800311 android_logger::init_once(
312 android_logger::Config::default().with_tag("fd_server").with_min_level(log::Level::Debug),
313 );
314
Victor Hsieh42cc7762021-01-25 16:44:19 -0800315 let fd_pool = parse_args()?;
316
317 ProcessState::start_thread_pool();
318
319 add_service(SERVICE_NAME, FdService::new_binder(fd_pool).as_binder())
320 .with_context(|| format!("Failed to register service {}", SERVICE_NAME))?;
321 debug!("fd_server is running.");
322
323 ProcessState::join_thread_pool();
324 bail!("Unexpected exit after join_thread_pool")
325}