• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 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 mod aidl;
26 
27 use anyhow::{bail, Result};
28 use clap::Parser;
29 use log::debug;
30 use nix::sys::stat::{umask, Mode};
31 use rpcbinder::RpcServer;
32 use std::collections::BTreeMap;
33 use std::fs::File;
34 use std::os::unix::io::{FromRawFd, OwnedFd};
35 
36 use aidl::{FdConfig, FdService};
37 use authfs_fsverity_metadata::parse_fsverity_metadata;
38 
39 // TODO(b/259920193): support dynamic port for multiple fd_server instances
40 const RPC_SERVICE_PORT: u32 = 3264;
41 
is_fd_valid(fd: i32) -> bool42 fn is_fd_valid(fd: i32) -> bool {
43     // SAFETY: a query-only syscall
44     let retval = unsafe { libc::fcntl(fd, libc::F_GETFD) };
45     retval >= 0
46 }
47 
fd_to_owned<T: FromRawFd>(fd: i32) -> Result<T>48 fn fd_to_owned<T: FromRawFd>(fd: i32) -> Result<T> {
49     if !is_fd_valid(fd) {
50         bail!("Bad FD: {}", fd);
51     }
52     // SAFETY: The caller is supposed to provide valid FDs to this process.
53     Ok(unsafe { T::from_raw_fd(fd) })
54 }
55 
parse_arg_ro_fds(arg: &str) -> Result<(i32, FdConfig)>56 fn parse_arg_ro_fds(arg: &str) -> Result<(i32, FdConfig)> {
57     let result: Result<Vec<i32>, _> = arg.split(':').map(|x| x.parse::<i32>()).collect();
58     let fds = result?;
59     if fds.len() > 2 {
60         bail!("Too many options: {}", arg);
61     }
62     Ok((
63         fds[0],
64         FdConfig::Readonly {
65             file: fd_to_owned(fds[0])?,
66             // Alternative metadata source, if provided
67             alt_metadata: fds
68                 .get(1)
69                 .map(|fd| fd_to_owned(*fd))
70                 .transpose()?
71                 .and_then(|f| parse_fsverity_metadata(f).ok()),
72         },
73     ))
74 }
75 
76 #[derive(Parser)]
77 struct Args {
78     /// Read-only FD of file, with optional FD of corresponding .fsv_meta, joined with a ':'.
79     /// Example: "1:2", "3".
80     #[clap(long)]
81     ro_fds: Vec<String>,
82 
83     /// Read-writable FD of file
84     #[clap(long)]
85     rw_fds: Vec<i32>,
86 
87     /// Read-only FD of directory
88     #[clap(long)]
89     ro_dirs: Vec<i32>,
90 
91     /// Read-writable FD of directory
92     #[clap(long)]
93     rw_dirs: Vec<i32>,
94 
95     /// A pipe FD for signaling the other end once ready
96     #[clap(long)]
97     ready_fd: Option<i32>,
98 }
99 
100 /// Convert argument strings and integers to a form that is easier to use and handles ownership.
convert_args(args: Args) -> Result<(BTreeMap<i32, FdConfig>, Option<OwnedFd>)>101 fn convert_args(args: Args) -> Result<(BTreeMap<i32, FdConfig>, Option<OwnedFd>)> {
102     let mut fd_pool = BTreeMap::new();
103     for arg in args.ro_fds {
104         let (fd, config) = parse_arg_ro_fds(&arg)?;
105         fd_pool.insert(fd, config);
106     }
107     for fd in args.rw_fds {
108         let file = fd_to_owned::<File>(fd)?;
109         if file.metadata()?.len() > 0 {
110             bail!("File is expected to be empty");
111         }
112         fd_pool.insert(fd, FdConfig::ReadWrite(file));
113     }
114     for fd in args.ro_dirs {
115         fd_pool.insert(fd, FdConfig::InputDir(fd_to_owned(fd)?));
116     }
117     for fd in args.rw_dirs {
118         fd_pool.insert(fd, FdConfig::OutputDir(fd_to_owned(fd)?));
119     }
120     let ready_fd = args.ready_fd.map(fd_to_owned).transpose()?;
121     Ok((fd_pool, ready_fd))
122 }
123 
main() -> Result<()>124 fn main() -> Result<()> {
125     android_logger::init_once(
126         android_logger::Config::default()
127             .with_tag("fd_server")
128             .with_max_level(log::LevelFilter::Debug),
129     );
130 
131     let args = Args::parse();
132     let (fd_pool, mut ready_fd) = convert_args(args)?;
133 
134     // Allow open/create/mkdir from authfs to create with expecting mode. It's possible to still
135     // use a custom mask on creation, then report the actual file mode back to authfs. But there
136     // is no demand now.
137     let old_umask = umask(Mode::empty());
138     debug!("Setting umask to 0 (old: {:03o})", old_umask.bits());
139 
140     debug!("fd_server is starting as a rpc service.");
141     let service = FdService::new_binder(fd_pool).as_binder();
142     // TODO(b/259920193): Only accept connections from the intended guest VM.
143     let server = RpcServer::new_vsock(service, libc::VMADDR_CID_ANY, RPC_SERVICE_PORT)?;
144     debug!("fd_server is ready");
145 
146     // Close the ready-fd if we were given one to signal our readiness.
147     drop(ready_fd.take());
148 
149     server.join();
150     Ok(())
151 }
152 
153 #[cfg(test)]
154 mod tests {
155     use super::*;
156     use clap::CommandFactory;
157 
158     #[test]
verify_args()159     fn verify_args() {
160         // Check that the command parsing has been configured in a valid way.
161         Args::command().debug_assert();
162     }
163 }
164