Debian Codegraph @

debian/rust-vendor/procfs/src/sys/fs/binfmt_misc.rs

raw
1 use bitflags::bitflags;
2 use std::path::Path;
3
4 use crate::{build_internal_error, from_str, read_value, ProcResult};
5
6 /// Returns true if the miscellaneous Binary Formats system is enabled.
7 pub fn enabled() -> ProcResult<bool> {
8 let val: String = read_value("/proc/sys/fs/binfmt_misc/status")?;
9 Ok(val == "enabled")
10 }
11
12 fn hex_to_vec(hex: &str) -> ProcResult<Vec<u8>> {
13 if hex.len() % 2 != 0 {
14 return Err(build_internal_error!(format!(
15 "Hex string {:?} has non-even length",
16 hex
17 )));
18 }
19 let mut idx = 0;
20 let mut data = Vec::new();
21 while idx < hex.len() {
22 let byte = from_str!(u8, &hex[idx..idx + 2], 16);
23 data.push(byte);
24 idx += 2;
25 }
26
27 Ok(data)
28 }
29
30 #[derive(Debug, Clone)]
31 pub enum BinFmtData {
32 /// A BinFmt entry based on a file extension (does not include the period)
33 Extension(String),
34 /// A BinFmt entry based on magic string matching
35 Magic { offset: u8, magic: Vec<u8>, mask: Vec<u8> },
36 }
37
38 /// A registered binary format entry
39 ///
40 /// For more info, see the kernel doc Documentation/admin-guide/binfmt-misc.rst
41 #[derive(Debug, Clone)]
42 pub struct BinFmtEntry {
43 /// The name of the entry
44 ///
45 /// Corresponds to a file in /proc/sys/fs/binfmt_misc/
46 pub name: String,
47 /// Is the entry enabled or not
48 pub enabled: bool,
49 /// Full path to the interpreter to run this entry
50 pub interpreter: String,
51 ///
52 pub flags: BinFmtFlags,
53 pub data: BinFmtData,
54 }
55
56 impl BinFmtEntry {
57 pub(crate) fn from_string(name: String, data: &str) -> ProcResult<Self> {
58 let mut enabled = false;
59 let mut interpreter = String::new();
60
61 let mut ext = None;
62
63 let mut offset = 0;
64 let mut magic = Vec::new();
65 let mut mask = Vec::new();
66 let mut flags = BinFmtFlags::empty();
67
68 for line in data.lines() {
69 if line == "enabled" {
70 enabled = true;
71 } else if let Some(stripped) = line.strip_prefix("interpreter ") {
72 interpreter = stripped.to_string();
73 } else if let Some(stripped) = line.strip_prefix("flags:") {
74 flags = BinFmtFlags::from_str(stripped);
75 } else if let Some(stripped) = line.strip_prefix("extension .") {
76 ext = Some(stripped.to_string());
77 } else if let Some(stripped) = line.strip_prefix("offset ") {
78 offset = from_str!(u8, stripped);
79 } else if let Some(stripped) = line.strip_prefix("magic ") {
80 let hex = stripped;
81 magic = hex_to_vec(dbg!(hex))?;
82 } else if let Some(stripped) = line.strip_prefix("mask ") {
83 let hex = stripped;
84 mask = hex_to_vec(hex)?;
85 }
86 }
87
88 if !magic.is_empty() && mask.is_empty() {
89 mask.resize(magic.len(), 0xff);
90 }
91
92 Ok(BinFmtEntry {
93 name,
94 enabled,
95 interpreter,
96 flags,
97 data: if let Some(ext) = ext {
98 BinFmtData::Extension(ext)
99 } else {
100 BinFmtData::Magic { magic, mask, offset }
101 },
102 })
103 }
104 }
105
106 bitflags! {
107 /// Various key flags
108 #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)]
109 pub struct BinFmtFlags: u8 {
110 /// Preserve Argv[0]
111 ///
112 /// Legacy behavior of binfmt_misc is to overwrite the original argv[0] with the full path to the binary. When
113 /// this flag is included, binfmt_misc will add an argument to the argument vector for this purpose, thus
114 /// preserving the original `argv[0]`.
115 ///
116 /// For example, If your interp is set to `/bin/foo` and you run `blah` (which is in `/usr/local/bin`),
117 /// then the kernel will execute `/bin/foo` with `argv[]` set to `["/bin/foo", "/usr/local/bin/blah", "blah"]`.
118 ///
119 /// The interp has to be aware of this so it can execute `/usr/local/bin/blah` with `argv[]` set to `["blah"]`.
120 const P = 0x01;
121
122 /// Open Binary
123 ///
124 /// Legacy behavior of binfmt_misc is to pass the full path
125 /// of the binary to the interpreter as an argument. When this flag is
126 /// included, binfmt_misc will open the file for reading and pass its
127 /// descriptor as an argument, instead of the full path, thus allowing
128 /// the interpreter to execute non-readable binaries. This feature
129 /// should be used with care - the interpreter has to be trusted not to
130 //// emit the contents of the non-readable binary.
131 const O = 0x02;
132
133 /// Credentials
134 ///
135 /// Currently, the behavior of binfmt_misc is to calculate
136 /// the credentials and security token of the new process according to
137 /// the interpreter. When this flag is included, these attributes are
138 /// calculated according to the binary. It also implies the `O` flag.
139 /// This feature should be used with care as the interpreter
140 /// will run with root permissions when a setuid binary owned by root
141 /// is run with binfmt_misc.
142 const C = 0x04;
143
144 /// Fix binary
145 ///
146 /// The usual behaviour of binfmt_misc is to spawn the
147 /// binary lazily when the misc format file is invoked. However,
148 /// this doesn't work very well in the face of mount namespaces and
149 /// changeroots, so the `F` mode opens the binary as soon as the
150 /// emulation is installed and uses the opened image to spawn the
151 /// emulator, meaning it is always available once installed,
152 /// regardless of how the environment changes.
153 const F = 0x08;
154 }
155 }
156
157 impl BinFmtFlags {
158 pub(crate) fn from_str(s: &str) -> Self {
159 s.chars()
160 .filter_map(|c| match c {
161 'P' => Some(BinFmtFlags::P),
162 'O' => Some(BinFmtFlags::O),
163 'C' => Some(BinFmtFlags::C),
164 'F' => Some(BinFmtFlags::F),
165 _ => None,
166 })
167 .fold(BinFmtFlags::empty(), |a, b| a | b)
168 }
169 }
170
171 pub fn list() -> ProcResult<Vec<BinFmtEntry>> {
172 let path = Path::new("/proc/sys/fs/binfmt_misc/");
173
174 let mut v = Vec::new();
175
176 for entry in wrap_io_error!(path, path.read_dir())? {
177 let entry = entry?;
178 if entry.file_name() == "status" || entry.file_name() == "register" {
179 // these entries do not represent real entries
180 continue;
181 }
182
183 let name = entry.file_name().to_string_lossy().to_string();
184
185 let data = std::fs::read_to_string(entry.path())?;
186
187 v.push(BinFmtEntry::from_string(name, &data)?);
188 }
189
190 Ok(v)
191 }
192
193 #[cfg(test)]
194 mod tests {
195 use super::*;
196
197 #[test]
198 fn test_enabled() {
199 match enabled() {
200 Ok(_) => {}
201 Err(crate::ProcError::NotFound(_)) => {}
202 Err(e) => panic!("{}", e),
203 }
204 }
205
206 #[test]
207 fn parse_magic() {
208 let mask = "7f454c460201010000000000000000000200f300";
209
210 let data = hex_to_vec(mask).unwrap();
211 println!("{:?}", data);
212 assert_eq!(data.len(), 20);
213 assert_eq!(data[0], 0x7f);
214 assert_eq!(data[1], 0x45);
215
216 assert!(hex_to_vec("a").is_err());
217 assert!(hex_to_vec("zz").is_err());
218 }
219
220 #[test]
221 fn flags_parsing() {
222 assert!(BinFmtFlags::from_str("").is_empty());
223
224 let flags = BinFmtFlags::from_str("F");
225 assert_eq!(flags, BinFmtFlags::F);
226
227 let flags = BinFmtFlags::from_str("OCF");
228 assert_eq!(flags, BinFmtFlags::F | BinFmtFlags::C | BinFmtFlags::O);
229 }
230
231 #[test]
232 fn binfmt() {
233 let data = r#"enabled
234 interpreter /usr/bin/qemu-riscv64-static
235 flags: OCF
236 offset 12
237 magic 7f454c460201010000000000000000000200f300
238 mask ffffffffffffff00fffffffffffffffffeffffff"#;
239
240 let entry = BinFmtEntry::from_string("test".to_owned(), data).unwrap();
241 println!("{:#?}", entry);
242 assert_eq!(entry.flags, BinFmtFlags::F | BinFmtFlags::C | BinFmtFlags::O);
243 assert!(entry.enabled);
244 assert_eq!(entry.interpreter, "/usr/bin/qemu-riscv64-static");
245 if let BinFmtData::Magic { offset, magic, mask } = entry.data {
246 assert_eq!(offset, 12);
247 assert_eq!(magic.len(), mask.len());
248 assert_eq!(
249 magic,
250 vec![
251 0x7f, 0x45, 0x4c, 0x46, 0x02, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
252 0x02, 0x00, 0xf3, 0x00
253 ]
254 );
255 } else {
256 panic!("Unexpected data");
257 }
258
259 let data = r#"enabled
260 interpreter /bin/hello
261 flags:
262 extension .hello"#;
263 let entry = BinFmtEntry::from_string("test".to_owned(), data).unwrap();
264 println!("{:#?}", entry);
265 assert_eq!(entry.flags, BinFmtFlags::empty());
266 assert!(entry.enabled);
267 assert_eq!(entry.interpreter, "/bin/hello");
268 if let BinFmtData::Extension(ext) = entry.data {
269 assert_eq!(ext, "hello");
270 } else {
271 panic!("Unexpected data");
272 }
273 }
274
275 #[test]
276 fn live() {
277 for entry in super::list().unwrap() {
278 println!("{:?}", entry);
279 }
280 }
281 }