Victor Hsieh | 42cc776 | 2021-01-25 16:44:19 -0800 | [diff] [blame] | 1 | /* |
| 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 Hsieh | 4dc85c9 | 2021-03-15 11:01:23 -0700 | [diff] [blame] | 28 | mod fsverity; |
| 29 | |
Victor Hsieh | 42cc776 | 2021-01-25 16:44:19 -0800 | [diff] [blame] | 30 | use std::cmp::min; |
| 31 | use std::collections::BTreeMap; |
| 32 | use std::convert::TryInto; |
| 33 | use std::ffi::CString; |
| 34 | use std::fs::File; |
| 35 | use std::io; |
| 36 | use std::os::unix::fs::FileExt; |
Victor Hsieh | 4dc85c9 | 2021-03-15 11:01:23 -0700 | [diff] [blame] | 37 | use std::os::unix::io::{AsRawFd, FromRawFd}; |
Victor Hsieh | 42cc776 | 2021-01-25 16:44:19 -0800 | [diff] [blame] | 38 | |
| 39 | use anyhow::{bail, Context, Result}; |
Andrew Walbran | bb49b44 | 2021-03-16 13:53:05 +0000 | [diff] [blame] | 40 | use binder::IBinderInternal; // TODO(178852354): remove once set_requesting_sid is exposed in the API. |
Victor Hsieh | 42cc776 | 2021-01-25 16:44:19 -0800 | [diff] [blame] | 41 | use log::{debug, error}; |
| 42 | |
| 43 | use authfs_aidl_interface::aidl::com::android::virt::fs::IVirtFdService::{ |
| 44 | BnVirtFdService, IVirtFdService, ERROR_IO, ERROR_UNKNOWN_FD, MAX_REQUESTING_DATA, |
| 45 | }; |
| 46 | use authfs_aidl_interface::binder::{ |
Victor Hsieh | 60acfd3 | 2021-02-23 13:08:13 -0800 | [diff] [blame] | 47 | add_service, ExceptionCode, Interface, ProcessState, Result as BinderResult, Status, |
| 48 | StatusCode, Strong, |
Victor Hsieh | 42cc776 | 2021-01-25 16:44:19 -0800 | [diff] [blame] | 49 | }; |
| 50 | |
| 51 | const SERVICE_NAME: &str = "authfs_fd_server"; |
| 52 | |
| 53 | fn 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 | |
| 57 | fn 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 | |
| 63 | fn 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 Hsieh | 60acfd3 | 2021-02-23 13:08:13 -0800 | [diff] [blame] | 76 | /// Configuration of a file descriptor to be served/exposed/shared. |
| 77 | enum 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 Hsieh | 42cc776 | 2021-01-25 16:44:19 -0800 | [diff] [blame] | 83 | |
Victor Hsieh | 60acfd3 | 2021-02-23 13:08:13 -0800 | [diff] [blame] | 84 | /// Alternative Merkle tree stored in another file. |
| 85 | alt_merkle_tree: Option<File>, |
Victor Hsieh | 42cc776 | 2021-01-25 16:44:19 -0800 | [diff] [blame] | 86 | |
Victor Hsieh | 60acfd3 | 2021-02-23 13:08:13 -0800 | [diff] [blame] | 87 | /// 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 Hsieh | 42cc776 | 2021-01-25 16:44:19 -0800 | [diff] [blame] | 94 | } |
| 95 | |
| 96 | struct FdService { |
Victor Hsieh | 60acfd3 | 2021-02-23 13:08:13 -0800 | [diff] [blame] | 97 | /// A pool of opened files, may be readonly or read-writable. |
| 98 | fd_pool: BTreeMap<i32, FdConfig>, |
Victor Hsieh | 42cc776 | 2021-01-25 16:44:19 -0800 | [diff] [blame] | 99 | } |
| 100 | |
| 101 | impl FdService { |
Victor Hsieh | 60acfd3 | 2021-02-23 13:08:13 -0800 | [diff] [blame] | 102 | pub fn new_binder(fd_pool: BTreeMap<i32, FdConfig>) -> Strong<dyn IVirtFdService> { |
Victor Hsieh | 42cc776 | 2021-01-25 16:44:19 -0800 | [diff] [blame] | 103 | let result = BnVirtFdService::new_binder(FdService { fd_pool }); |
| 104 | result.as_binder().set_requesting_sid(false); |
| 105 | result |
| 106 | } |
| 107 | |
Victor Hsieh | 60acfd3 | 2021-02-23 13:08:13 -0800 | [diff] [blame] | 108 | fn get_file_config(&self, id: i32) -> BinderResult<&FdConfig> { |
Victor Hsieh | 42cc776 | 2021-01-25 16:44:19 -0800 | [diff] [blame] | 109 | self.fd_pool.get(&id).ok_or_else(|| Status::from(ERROR_UNKNOWN_FD)) |
| 110 | } |
Victor Hsieh | 42cc776 | 2021-01-25 16:44:19 -0800 | [diff] [blame] | 111 | } |
| 112 | |
| 113 | impl Interface for FdService {} |
| 114 | |
| 115 | impl 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 Hsieh | 60acfd3 | 2021-02-23 13:08:13 -0800 | [diff] [blame] | 120 | 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 Hsieh | 42cc776 | 2021-01-25 16:44:19 -0800 | [diff] [blame] | 128 | } |
| 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 Hsieh | 60acfd3 | 2021-02-23 13:08:13 -0800 | [diff] [blame] | 134 | match &self.get_file_config(id)? { |
Victor Hsieh | 4dc85c9 | 2021-03-15 11:01:23 -0700 | [diff] [blame] | 135 | 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 Hsieh | 60acfd3 | 2021-02-23 13:08:13 -0800 | [diff] [blame] | 138 | error!("readFsverityMerkleTree: read error: {}", e); |
| 139 | Status::from(ERROR_IO) |
| 140 | }) |
| 141 | } else { |
Victor Hsieh | 4dc85c9 | 2021-03-15 11:01:23 -0700 | [diff] [blame] | 142 | 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 Hsieh | 60acfd3 | 2021-02-23 13:08:13 -0800 | [diff] [blame] | 151 | } |
| 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 Hsieh | 42cc776 | 2021-01-25 16:44:19 -0800 | [diff] [blame] | 159 | } |
| 160 | } |
| 161 | |
| 162 | fn readFsveritySignature(&self, id: i32) -> BinderResult<Vec<u8>> { |
Victor Hsieh | 60acfd3 | 2021-02-23 13:08:13 -0800 | [diff] [blame] | 163 | match &self.get_file_config(id)? { |
Victor Hsieh | 4dc85c9 | 2021-03-15 11:01:23 -0700 | [diff] [blame] | 164 | FdConfig::Readonly { file, alt_signature, .. } => { |
| 165 | if let Some(sig_file) = &alt_signature { |
Victor Hsieh | 60acfd3 | 2021-02-23 13:08:13 -0800 | [diff] [blame] | 166 | // Supposedly big enough buffer size to store signature. |
| 167 | let size = MAX_REQUESTING_DATA as usize; |
Victor Hsieh | 4dc85c9 | 2021-03-15 11:01:23 -0700 | [diff] [blame] | 168 | let offset = 0; |
| 169 | read_into_buf(&sig_file, size, offset).map_err(|e| { |
Victor Hsieh | 60acfd3 | 2021-02-23 13:08:13 -0800 | [diff] [blame] | 170 | error!("readFsveritySignature: read error: {}", e); |
| 171 | Status::from(ERROR_IO) |
| 172 | }) |
| 173 | } else { |
Victor Hsieh | 4dc85c9 | 2021-03-15 11:01:23 -0700 | [diff] [blame] | 174 | 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 Hsieh | 60acfd3 | 2021-02-23 13:08:13 -0800 | [diff] [blame] | 182 | } |
| 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 Hsieh | 42cc776 | 2021-01-25 16:44:19 -0800 | [diff] [blame] | 210 | } |
| 211 | } |
Victor Hsieh | 9d0ab62 | 2021-04-26 17:07:02 -0700 | [diff] [blame^] | 212 | |
| 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 Hsieh | 42cc776 | 2021-01-25 16:44:19 -0800 | [diff] [blame] | 230 | } |
| 231 | |
| 232 | fn 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 | |
| 240 | fn 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 | |
| 246 | fn 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 Hsieh | 60acfd3 | 2021-02-23 13:08:13 -0800 | [diff] [blame] | 254 | fn parse_arg_ro_fds(arg: &str) -> Result<(i32, FdConfig)> { |
Victor Hsieh | 42cc776 | 2021-01-25 16:44:19 -0800 | [diff] [blame] | 255 | 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 Hsieh | 42cc776 | 2021-01-25 16:44:19 -0800 | [diff] [blame] | 260 | Ok(( |
| 261 | fds[0], |
Victor Hsieh | 60acfd3 | 2021-02-23 13:08:13 -0800 | [diff] [blame] | 262 | FdConfig::Readonly { |
Victor Hsieh | 42cc776 | 2021-01-25 16:44:19 -0800 | [diff] [blame] | 263 | file: fd_to_file(fds[0])?, |
Victor Hsieh | 60acfd3 | 2021-02-23 13:08:13 -0800 | [diff] [blame] | 264 | // 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 Hsieh | 42cc776 | 2021-01-25 16:44:19 -0800 | [diff] [blame] | 268 | }, |
| 269 | )) |
| 270 | } |
| 271 | |
Victor Hsieh | 60acfd3 | 2021-02-23 13:08:13 -0800 | [diff] [blame] | 272 | fn 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 | |
| 281 | fn parse_args() -> Result<BTreeMap<i32, FdConfig>> { |
Victor Hsieh | 42cc776 | 2021-01-25 16:44:19 -0800 | [diff] [blame] | 282 | #[rustfmt::skip] |
| 283 | let matches = clap::App::new("fd_server") |
| 284 | .arg(clap::Arg::with_name("ro-fds") |
| 285 | .long("ro-fds") |
Victor Hsieh | 60acfd3 | 2021-02-23 13:08:13 -0800 | [diff] [blame] | 286 | .multiple(true) |
| 287 | .number_of_values(1)) |
| 288 | .arg(clap::Arg::with_name("rw-fds") |
| 289 | .long("rw-fds") |
Victor Hsieh | 42cc776 | 2021-01-25 16:44:19 -0800 | [diff] [blame] | 290 | .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 Hsieh | 60acfd3 | 2021-02-23 13:08:13 -0800 | [diff] [blame] | 301 | 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 Hsieh | 42cc776 | 2021-01-25 16:44:19 -0800 | [diff] [blame] | 307 | Ok(fd_pool) |
| 308 | } |
| 309 | |
| 310 | fn main() -> Result<()> { |
Victor Hsieh | 60acfd3 | 2021-02-23 13:08:13 -0800 | [diff] [blame] | 311 | android_logger::init_once( |
| 312 | android_logger::Config::default().with_tag("fd_server").with_min_level(log::Level::Debug), |
| 313 | ); |
| 314 | |
Victor Hsieh | 42cc776 | 2021-01-25 16:44:19 -0800 | [diff] [blame] | 315 | 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 | } |