blob: 44817d5b64973de97dfed5040ee4efa842cb1b30 [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
28use std::cmp::min;
29use std::collections::BTreeMap;
30use std::convert::TryInto;
31use std::ffi::CString;
32use std::fs::File;
33use std::io;
34use std::os::unix::fs::FileExt;
35use std::os::unix::io::FromRawFd;
36
37use anyhow::{bail, Context, Result};
Andrew Walbranbb49b442021-03-16 13:53:05 +000038use binder::IBinderInternal; // TODO(178852354): remove once set_requesting_sid is exposed in the API.
Victor Hsieh42cc7762021-01-25 16:44:19 -080039use log::{debug, error};
40
41use authfs_aidl_interface::aidl::com::android::virt::fs::IVirtFdService::{
42 BnVirtFdService, IVirtFdService, ERROR_IO, ERROR_UNKNOWN_FD, MAX_REQUESTING_DATA,
43};
44use authfs_aidl_interface::binder::{
Victor Hsieh60acfd32021-02-23 13:08:13 -080045 add_service, ExceptionCode, Interface, ProcessState, Result as BinderResult, Status,
46 StatusCode, Strong,
Victor Hsieh42cc7762021-01-25 16:44:19 -080047};
48
49const SERVICE_NAME: &str = "authfs_fd_server";
50
51fn new_binder_exception<T: AsRef<str>>(exception: ExceptionCode, message: T) -> Status {
52 Status::new_exception(exception, CString::new(message.as_ref()).as_deref().ok())
53}
54
55fn validate_and_cast_offset(offset: i64) -> Result<u64, Status> {
56 offset.try_into().map_err(|_| {
57 new_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT, format!("Invalid offset: {}", offset))
58 })
59}
60
61fn validate_and_cast_size(size: i32) -> Result<usize, Status> {
62 if size > MAX_REQUESTING_DATA {
63 Err(new_binder_exception(
64 ExceptionCode::ILLEGAL_ARGUMENT,
65 format!("Unexpectedly large size: {}", size),
66 ))
67 } else {
68 size.try_into().map_err(|_| {
69 new_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT, format!("Invalid size: {}", size))
70 })
71 }
72}
73
Victor Hsieh60acfd32021-02-23 13:08:13 -080074/// Configuration of a file descriptor to be served/exposed/shared.
75enum FdConfig {
76 /// A read-only file to serve by this server. The file is supposed to be verifiable with the
77 /// associated fs-verity metadata.
78 Readonly {
79 /// The file to read from. fs-verity metadata can be retrieved from this file's FD.
80 file: File,
Victor Hsieh42cc7762021-01-25 16:44:19 -080081
Victor Hsieh60acfd32021-02-23 13:08:13 -080082 /// Alternative Merkle tree stored in another file.
83 alt_merkle_tree: Option<File>,
Victor Hsieh42cc7762021-01-25 16:44:19 -080084
Victor Hsieh60acfd32021-02-23 13:08:13 -080085 /// Alternative signature stored in another file.
86 alt_signature: Option<File>,
87 },
88
89 /// A readable/writable file to serve by this server. This backing file should just be a
90 /// regular file and does not have any specific property.
91 ReadWrite(File),
Victor Hsieh42cc7762021-01-25 16:44:19 -080092}
93
94struct FdService {
Victor Hsieh60acfd32021-02-23 13:08:13 -080095 /// A pool of opened files, may be readonly or read-writable.
96 fd_pool: BTreeMap<i32, FdConfig>,
Victor Hsieh42cc7762021-01-25 16:44:19 -080097}
98
99impl FdService {
Victor Hsieh60acfd32021-02-23 13:08:13 -0800100 pub fn new_binder(fd_pool: BTreeMap<i32, FdConfig>) -> Strong<dyn IVirtFdService> {
Victor Hsieh42cc7762021-01-25 16:44:19 -0800101 let result = BnVirtFdService::new_binder(FdService { fd_pool });
102 result.as_binder().set_requesting_sid(false);
103 result
104 }
105
Victor Hsieh60acfd32021-02-23 13:08:13 -0800106 fn get_file_config(&self, id: i32) -> BinderResult<&FdConfig> {
Victor Hsieh42cc7762021-01-25 16:44:19 -0800107 self.fd_pool.get(&id).ok_or_else(|| Status::from(ERROR_UNKNOWN_FD))
108 }
Victor Hsieh42cc7762021-01-25 16:44:19 -0800109}
110
111impl Interface for FdService {}
112
113impl IVirtFdService for FdService {
114 fn readFile(&self, id: i32, offset: i64, size: i32) -> BinderResult<Vec<u8>> {
115 let size: usize = validate_and_cast_size(size)?;
116 let offset: u64 = validate_and_cast_offset(offset)?;
117
Victor Hsieh60acfd32021-02-23 13:08:13 -0800118 match self.get_file_config(id)? {
119 FdConfig::Readonly { file, .. } | FdConfig::ReadWrite(file) => {
120 read_into_buf(&file, size, offset).map_err(|e| {
121 error!("readFile: read error: {}", e);
122 Status::from(ERROR_IO)
123 })
124 }
125 }
Victor Hsieh42cc7762021-01-25 16:44:19 -0800126 }
127
128 fn readFsverityMerkleTree(&self, id: i32, offset: i64, size: i32) -> BinderResult<Vec<u8>> {
129 let size: usize = validate_and_cast_size(size)?;
130 let offset: u64 = validate_and_cast_offset(offset)?;
131
Victor Hsieh60acfd32021-02-23 13:08:13 -0800132 match &self.get_file_config(id)? {
133 FdConfig::Readonly { alt_merkle_tree, .. } => {
134 if let Some(file) = &alt_merkle_tree {
135 read_into_buf(&file, size, offset).map_err(|e| {
136 error!("readFsverityMerkleTree: read error: {}", e);
137 Status::from(ERROR_IO)
138 })
139 } else {
140 // TODO(victorhsieh) retrieve from the fd when the new ioctl is ready
141 Err(new_binder_exception(
142 ExceptionCode::UNSUPPORTED_OPERATION,
143 "Not implemented yet",
144 ))
145 }
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)? {
158 FdConfig::Readonly { alt_signature, .. } => {
159 if let Some(file) = &alt_signature {
160 // Supposedly big enough buffer size to store signature.
161 let size = MAX_REQUESTING_DATA as usize;
162 read_into_buf(&file, size, 0).map_err(|e| {
163 error!("readFsveritySignature: read error: {}", e);
164 Status::from(ERROR_IO)
165 })
166 } else {
167 // TODO(victorhsieh) retrieve from the fd when the new ioctl is ready
168 Err(new_binder_exception(
169 ExceptionCode::UNSUPPORTED_OPERATION,
170 "Not implemented yet",
171 ))
172 }
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 }
202}
203
204fn read_into_buf(file: &File, max_size: usize, offset: u64) -> io::Result<Vec<u8>> {
205 let remaining = file.metadata()?.len().saturating_sub(offset);
206 let buf_size = min(remaining, max_size as u64) as usize;
207 let mut buf = vec![0; buf_size];
208 file.read_exact_at(&mut buf, offset)?;
209 Ok(buf)
210}
211
212fn is_fd_valid(fd: i32) -> bool {
213 // SAFETY: a query-only syscall
214 let retval = unsafe { libc::fcntl(fd, libc::F_GETFD) };
215 retval >= 0
216}
217
218fn fd_to_file(fd: i32) -> Result<File> {
219 if !is_fd_valid(fd) {
220 bail!("Bad FD: {}", fd);
221 }
222 // SAFETY: The caller is supposed to provide valid FDs to this process.
223 Ok(unsafe { File::from_raw_fd(fd) })
224}
225
Victor Hsieh60acfd32021-02-23 13:08:13 -0800226fn parse_arg_ro_fds(arg: &str) -> Result<(i32, FdConfig)> {
Victor Hsieh42cc7762021-01-25 16:44:19 -0800227 let result: Result<Vec<i32>, _> = arg.split(':').map(|x| x.parse::<i32>()).collect();
228 let fds = result?;
229 if fds.len() > 3 {
230 bail!("Too many options: {}", arg);
231 }
Victor Hsieh42cc7762021-01-25 16:44:19 -0800232 Ok((
233 fds[0],
Victor Hsieh60acfd32021-02-23 13:08:13 -0800234 FdConfig::Readonly {
Victor Hsieh42cc7762021-01-25 16:44:19 -0800235 file: fd_to_file(fds[0])?,
Victor Hsieh60acfd32021-02-23 13:08:13 -0800236 // Alternative Merkle tree, if provided
237 alt_merkle_tree: fds.get(1).map(|fd| fd_to_file(*fd)).transpose()?,
238 // Alternative signature, if provided
239 alt_signature: fds.get(2).map(|fd| fd_to_file(*fd)).transpose()?,
Victor Hsieh42cc7762021-01-25 16:44:19 -0800240 },
241 ))
242}
243
Victor Hsieh60acfd32021-02-23 13:08:13 -0800244fn parse_arg_rw_fds(arg: &str) -> Result<(i32, FdConfig)> {
245 let fd = arg.parse::<i32>()?;
246 let file = fd_to_file(fd)?;
247 if file.metadata()?.len() > 0 {
248 bail!("File is expected to be empty");
249 }
250 Ok((fd, FdConfig::ReadWrite(file)))
251}
252
253fn parse_args() -> Result<BTreeMap<i32, FdConfig>> {
Victor Hsieh42cc7762021-01-25 16:44:19 -0800254 #[rustfmt::skip]
255 let matches = clap::App::new("fd_server")
256 .arg(clap::Arg::with_name("ro-fds")
257 .long("ro-fds")
Victor Hsieh60acfd32021-02-23 13:08:13 -0800258 .multiple(true)
259 .number_of_values(1))
260 .arg(clap::Arg::with_name("rw-fds")
261 .long("rw-fds")
Victor Hsieh42cc7762021-01-25 16:44:19 -0800262 .multiple(true)
263 .number_of_values(1))
264 .get_matches();
265
266 let mut fd_pool = BTreeMap::new();
267 if let Some(args) = matches.values_of("ro-fds") {
268 for arg in args {
269 let (fd, config) = parse_arg_ro_fds(arg)?;
270 fd_pool.insert(fd, config);
271 }
272 }
Victor Hsieh60acfd32021-02-23 13:08:13 -0800273 if let Some(args) = matches.values_of("rw-fds") {
274 for arg in args {
275 let (fd, config) = parse_arg_rw_fds(arg)?;
276 fd_pool.insert(fd, config);
277 }
278 }
Victor Hsieh42cc7762021-01-25 16:44:19 -0800279 Ok(fd_pool)
280}
281
282fn main() -> Result<()> {
Victor Hsieh60acfd32021-02-23 13:08:13 -0800283 android_logger::init_once(
284 android_logger::Config::default().with_tag("fd_server").with_min_level(log::Level::Debug),
285 );
286
Victor Hsieh42cc7762021-01-25 16:44:19 -0800287 let fd_pool = parse_args()?;
288
289 ProcessState::start_thread_pool();
290
291 add_service(SERVICE_NAME, FdService::new_binder(fd_pool).as_binder())
292 .with_context(|| format!("Failed to register service {}", SERVICE_NAME))?;
293 debug!("fd_server is running.");
294
295 ProcessState::join_thread_pool();
296 bail!("Unexpected exit after join_thread_pool")
297}