blob: 4e5c5d35910eee42b2f410bb54dd5514d4c14159 [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};
Victor Hsieh42cc7762021-01-25 16:44:19 -080040use log::{debug, error};
41
42use authfs_aidl_interface::aidl::com::android::virt::fs::IVirtFdService::{
43 BnVirtFdService, IVirtFdService, ERROR_IO, ERROR_UNKNOWN_FD, MAX_REQUESTING_DATA,
44};
45use authfs_aidl_interface::binder::{
Andrew Walbran4de28782021-04-13 14:51:43 +000046 add_service, BinderFeatures, ExceptionCode, Interface, ProcessState, Result as BinderResult,
47 Status, StatusCode, Strong,
Victor Hsieh42cc7762021-01-25 16:44:19 -080048};
49
50const SERVICE_NAME: &str = "authfs_fd_server";
51
52fn new_binder_exception<T: AsRef<str>>(exception: ExceptionCode, message: T) -> Status {
53 Status::new_exception(exception, CString::new(message.as_ref()).as_deref().ok())
54}
55
56fn validate_and_cast_offset(offset: i64) -> Result<u64, Status> {
57 offset.try_into().map_err(|_| {
58 new_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT, format!("Invalid offset: {}", offset))
59 })
60}
61
62fn validate_and_cast_size(size: i32) -> Result<usize, Status> {
63 if size > MAX_REQUESTING_DATA {
64 Err(new_binder_exception(
65 ExceptionCode::ILLEGAL_ARGUMENT,
66 format!("Unexpectedly large size: {}", size),
67 ))
68 } else {
69 size.try_into().map_err(|_| {
70 new_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT, format!("Invalid size: {}", size))
71 })
72 }
73}
74
Victor Hsieh60acfd32021-02-23 13:08:13 -080075/// Configuration of a file descriptor to be served/exposed/shared.
76enum FdConfig {
77 /// A read-only file to serve by this server. The file is supposed to be verifiable with the
78 /// associated fs-verity metadata.
79 Readonly {
80 /// The file to read from. fs-verity metadata can be retrieved from this file's FD.
81 file: File,
Victor Hsieh42cc7762021-01-25 16:44:19 -080082
Victor Hsieh60acfd32021-02-23 13:08:13 -080083 /// Alternative Merkle tree stored in another file.
84 alt_merkle_tree: Option<File>,
Victor Hsieh42cc7762021-01-25 16:44:19 -080085
Victor Hsieh60acfd32021-02-23 13:08:13 -080086 /// Alternative signature stored in another file.
87 alt_signature: Option<File>,
88 },
89
90 /// A readable/writable file to serve by this server. This backing file should just be a
91 /// regular file and does not have any specific property.
92 ReadWrite(File),
Victor Hsieh42cc7762021-01-25 16:44:19 -080093}
94
95struct FdService {
Victor Hsieh60acfd32021-02-23 13:08:13 -080096 /// A pool of opened files, may be readonly or read-writable.
97 fd_pool: BTreeMap<i32, FdConfig>,
Victor Hsieh42cc7762021-01-25 16:44:19 -080098}
99
100impl FdService {
Victor Hsieh60acfd32021-02-23 13:08:13 -0800101 pub fn new_binder(fd_pool: BTreeMap<i32, FdConfig>) -> Strong<dyn IVirtFdService> {
Andrew Walbran4de28782021-04-13 14:51:43 +0000102 BnVirtFdService::new_binder(FdService { fd_pool }, BinderFeatures::default())
Victor Hsieh42cc7762021-01-25 16:44:19 -0800103 }
104
Victor Hsieh60acfd32021-02-23 13:08:13 -0800105 fn get_file_config(&self, id: i32) -> BinderResult<&FdConfig> {
Victor Hsieh42cc7762021-01-25 16:44:19 -0800106 self.fd_pool.get(&id).ok_or_else(|| Status::from(ERROR_UNKNOWN_FD))
107 }
Victor Hsieh42cc7762021-01-25 16:44:19 -0800108}
109
110impl Interface for FdService {}
111
112impl IVirtFdService for FdService {
113 fn readFile(&self, id: i32, offset: i64, size: i32) -> BinderResult<Vec<u8>> {
114 let size: usize = validate_and_cast_size(size)?;
115 let offset: u64 = validate_and_cast_offset(offset)?;
116
Victor Hsieh60acfd32021-02-23 13:08:13 -0800117 match self.get_file_config(id)? {
118 FdConfig::Readonly { file, .. } | FdConfig::ReadWrite(file) => {
119 read_into_buf(&file, size, offset).map_err(|e| {
120 error!("readFile: read error: {}", e);
121 Status::from(ERROR_IO)
122 })
123 }
124 }
Victor Hsieh42cc7762021-01-25 16:44:19 -0800125 }
126
127 fn readFsverityMerkleTree(&self, id: i32, offset: i64, size: i32) -> BinderResult<Vec<u8>> {
128 let size: usize = validate_and_cast_size(size)?;
129 let offset: u64 = validate_and_cast_offset(offset)?;
130
Victor Hsieh60acfd32021-02-23 13:08:13 -0800131 match &self.get_file_config(id)? {
Victor Hsieh4dc85c92021-03-15 11:01:23 -0700132 FdConfig::Readonly { file, alt_merkle_tree, .. } => {
133 if let Some(tree_file) = &alt_merkle_tree {
134 read_into_buf(&tree_file, size, offset).map_err(|e| {
Victor Hsieh60acfd32021-02-23 13:08:13 -0800135 error!("readFsverityMerkleTree: read error: {}", e);
136 Status::from(ERROR_IO)
137 })
138 } else {
Victor Hsieh4dc85c92021-03-15 11:01:23 -0700139 let mut buf = vec![0; size];
140 let s = fsverity::read_merkle_tree(file.as_raw_fd(), offset, &mut buf)
141 .map_err(|e| {
142 error!("readFsverityMerkleTree: failed to retrieve merkle tree: {}", e);
143 Status::from(e.raw_os_error().unwrap_or(ERROR_IO))
144 })?;
145 debug_assert!(s <= buf.len(), "Shouldn't return more bytes than asked");
146 buf.truncate(s);
147 Ok(buf)
Victor Hsieh60acfd32021-02-23 13:08:13 -0800148 }
149 }
150 FdConfig::ReadWrite(_file) => {
151 // For a writable file, Merkle tree is not expected to be served since Auth FS
152 // doesn't trust it anyway. Auth FS may keep the Merkle tree privately for its own
153 // use.
154 Err(new_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION, "Unsupported"))
155 }
Victor Hsieh42cc7762021-01-25 16:44:19 -0800156 }
157 }
158
159 fn readFsveritySignature(&self, id: i32) -> BinderResult<Vec<u8>> {
Victor Hsieh60acfd32021-02-23 13:08:13 -0800160 match &self.get_file_config(id)? {
Victor Hsieh4dc85c92021-03-15 11:01:23 -0700161 FdConfig::Readonly { file, alt_signature, .. } => {
162 if let Some(sig_file) = &alt_signature {
Victor Hsieh60acfd32021-02-23 13:08:13 -0800163 // Supposedly big enough buffer size to store signature.
164 let size = MAX_REQUESTING_DATA as usize;
Victor Hsieh4dc85c92021-03-15 11:01:23 -0700165 let offset = 0;
166 read_into_buf(&sig_file, size, offset).map_err(|e| {
Victor Hsieh60acfd32021-02-23 13:08:13 -0800167 error!("readFsveritySignature: read error: {}", e);
168 Status::from(ERROR_IO)
169 })
170 } else {
Victor Hsieh4dc85c92021-03-15 11:01:23 -0700171 let mut buf = vec![0; MAX_REQUESTING_DATA as usize];
172 let s = fsverity::read_signature(file.as_raw_fd(), &mut buf).map_err(|e| {
173 error!("readFsverityMerkleTree: failed to retrieve merkle tree: {}", e);
174 Status::from(e.raw_os_error().unwrap_or(ERROR_IO))
175 })?;
176 debug_assert!(s <= buf.len(), "Shouldn't return more bytes than asked");
177 buf.truncate(s);
178 Ok(buf)
Victor Hsieh60acfd32021-02-23 13:08:13 -0800179 }
180 }
181 FdConfig::ReadWrite(_file) => {
182 // There is no signature for a writable file.
183 Err(new_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION, "Unsupported"))
184 }
185 }
186 }
187
188 fn writeFile(&self, id: i32, buf: &[u8], offset: i64) -> BinderResult<i32> {
189 match &self.get_file_config(id)? {
190 FdConfig::Readonly { .. } => Err(StatusCode::INVALID_OPERATION.into()),
191 FdConfig::ReadWrite(file) => {
192 let offset: u64 = offset.try_into().map_err(|_| {
193 new_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT, "Invalid offset")
194 })?;
195 // Check buffer size just to make `as i32` safe below.
196 if buf.len() > i32::MAX as usize {
197 return Err(new_binder_exception(
198 ExceptionCode::ILLEGAL_ARGUMENT,
199 "Buffer size is too big",
200 ));
201 }
202 Ok(file.write_at(buf, offset).map_err(|e| {
203 error!("writeFile: write error: {}", e);
204 Status::from(ERROR_IO)
205 })? as i32)
206 }
Victor Hsieh42cc7762021-01-25 16:44:19 -0800207 }
208 }
209}
210
211fn read_into_buf(file: &File, max_size: usize, offset: u64) -> io::Result<Vec<u8>> {
212 let remaining = file.metadata()?.len().saturating_sub(offset);
213 let buf_size = min(remaining, max_size as u64) as usize;
214 let mut buf = vec![0; buf_size];
215 file.read_exact_at(&mut buf, offset)?;
216 Ok(buf)
217}
218
219fn is_fd_valid(fd: i32) -> bool {
220 // SAFETY: a query-only syscall
221 let retval = unsafe { libc::fcntl(fd, libc::F_GETFD) };
222 retval >= 0
223}
224
225fn fd_to_file(fd: i32) -> Result<File> {
226 if !is_fd_valid(fd) {
227 bail!("Bad FD: {}", fd);
228 }
229 // SAFETY: The caller is supposed to provide valid FDs to this process.
230 Ok(unsafe { File::from_raw_fd(fd) })
231}
232
Victor Hsieh60acfd32021-02-23 13:08:13 -0800233fn parse_arg_ro_fds(arg: &str) -> Result<(i32, FdConfig)> {
Victor Hsieh42cc7762021-01-25 16:44:19 -0800234 let result: Result<Vec<i32>, _> = arg.split(':').map(|x| x.parse::<i32>()).collect();
235 let fds = result?;
236 if fds.len() > 3 {
237 bail!("Too many options: {}", arg);
238 }
Victor Hsieh42cc7762021-01-25 16:44:19 -0800239 Ok((
240 fds[0],
Victor Hsieh60acfd32021-02-23 13:08:13 -0800241 FdConfig::Readonly {
Victor Hsieh42cc7762021-01-25 16:44:19 -0800242 file: fd_to_file(fds[0])?,
Victor Hsieh60acfd32021-02-23 13:08:13 -0800243 // Alternative Merkle tree, if provided
244 alt_merkle_tree: fds.get(1).map(|fd| fd_to_file(*fd)).transpose()?,
245 // Alternative signature, if provided
246 alt_signature: fds.get(2).map(|fd| fd_to_file(*fd)).transpose()?,
Victor Hsieh42cc7762021-01-25 16:44:19 -0800247 },
248 ))
249}
250
Victor Hsieh60acfd32021-02-23 13:08:13 -0800251fn parse_arg_rw_fds(arg: &str) -> Result<(i32, FdConfig)> {
252 let fd = arg.parse::<i32>()?;
253 let file = fd_to_file(fd)?;
254 if file.metadata()?.len() > 0 {
255 bail!("File is expected to be empty");
256 }
257 Ok((fd, FdConfig::ReadWrite(file)))
258}
259
260fn parse_args() -> Result<BTreeMap<i32, FdConfig>> {
Victor Hsieh42cc7762021-01-25 16:44:19 -0800261 #[rustfmt::skip]
262 let matches = clap::App::new("fd_server")
263 .arg(clap::Arg::with_name("ro-fds")
264 .long("ro-fds")
Victor Hsieh60acfd32021-02-23 13:08:13 -0800265 .multiple(true)
266 .number_of_values(1))
267 .arg(clap::Arg::with_name("rw-fds")
268 .long("rw-fds")
Victor Hsieh42cc7762021-01-25 16:44:19 -0800269 .multiple(true)
270 .number_of_values(1))
271 .get_matches();
272
273 let mut fd_pool = BTreeMap::new();
274 if let Some(args) = matches.values_of("ro-fds") {
275 for arg in args {
276 let (fd, config) = parse_arg_ro_fds(arg)?;
277 fd_pool.insert(fd, config);
278 }
279 }
Victor Hsieh60acfd32021-02-23 13:08:13 -0800280 if let Some(args) = matches.values_of("rw-fds") {
281 for arg in args {
282 let (fd, config) = parse_arg_rw_fds(arg)?;
283 fd_pool.insert(fd, config);
284 }
285 }
Victor Hsieh42cc7762021-01-25 16:44:19 -0800286 Ok(fd_pool)
287}
288
289fn main() -> Result<()> {
Victor Hsieh60acfd32021-02-23 13:08:13 -0800290 android_logger::init_once(
291 android_logger::Config::default().with_tag("fd_server").with_min_level(log::Level::Debug),
292 );
293
Victor Hsieh42cc7762021-01-25 16:44:19 -0800294 let fd_pool = parse_args()?;
295
296 ProcessState::start_thread_pool();
297
298 add_service(SERVICE_NAME, FdService::new_binder(fd_pool).as_binder())
299 .with_context(|| format!("Failed to register service {}", SERVICE_NAME))?;
300 debug!("fd_server is running.");
301
302 ProcessState::join_thread_pool();
303 bail!("Unexpected exit after join_thread_pool")
304}