1#![no_std]
2
3extern crate alloc;
4
5embedded_i18n::i18n!("locales");
6
7#[cfg(feature = "building")]
8mod building;
9mod error;
10mod format;
11#[cfg(all(
12 feature = "native-linked",
13 any(
14 all(
15 any(target_arch = "x86_64", target_arch = "aarch64"),
16 target_os = "linux"
17 ),
18 all(
19 any(
20 target_arch = "x86_64",
21 target_arch = "aarch64",
22 target_arch = "arm",
23 target_arch = "riscv32",
24 target_arch = "xtensa"
25 ),
26 target_os = "none"
27 )
28 )
29))]
30mod linked;
31#[cfg(all(
32 feature = "native-dev",
33 any(
34 all(
35 any(target_arch = "x86_64", target_arch = "aarch64"),
36 target_os = "linux"
37 ),
38 all(
39 any(
40 target_arch = "x86_64",
41 target_arch = "aarch64",
42 target_arch = "arm",
43 target_arch = "riscv32",
44 target_arch = "xtensa"
45 ),
46 target_os = "none"
47 )
48 )
49))]
50mod native;
51#[cfg(all(
52 any(feature = "native-dev", feature = "native-linked"),
53 any(
54 all(
55 any(target_arch = "x86_64", target_arch = "aarch64"),
56 target_os = "linux"
57 ),
58 all(
59 any(
60 target_arch = "x86_64",
61 target_arch = "aarch64",
62 target_arch = "arm",
63 target_arch = "riscv32",
64 target_arch = "xtensa"
65 ),
66 target_os = "none"
67 )
68 )
69))]
70mod process_host;
71mod standard;
72mod traits;
73
74#[cfg(feature = "building")]
75pub use building::*;
76pub use error::*;
77pub use file_system as exported_file_system;
78pub use format::*;
79#[cfg(all(
80 feature = "native-linked",
81 any(
82 all(
83 any(target_arch = "x86_64", target_arch = "aarch64"),
84 target_os = "linux"
85 ),
86 all(
87 any(
88 target_arch = "x86_64",
89 target_arch = "aarch64",
90 target_arch = "arm",
91 target_arch = "riscv32",
92 target_arch = "xtensa"
93 ),
94 target_os = "none"
95 )
96 )
97))]
98pub use linked::*;
99#[cfg(all(
100 feature = "native-dev",
101 any(
102 all(
103 any(target_arch = "x86_64", target_arch = "aarch64"),
104 target_os = "linux"
105 ),
106 all(
107 any(
108 target_arch = "x86_64",
109 target_arch = "aarch64",
110 target_arch = "arm",
111 target_arch = "riscv32",
112 target_arch = "xtensa"
113 ),
114 target_os = "none"
115 )
116 )
117))]
118pub use native::NativeFormat;
119
120#[cfg(feature = "native-dev")]
121pub use native_loader;
122#[cfg(all(
123 any(feature = "native-dev", feature = "native-linked"),
124 any(
125 all(
126 any(target_arch = "x86_64", target_arch = "aarch64"),
127 target_os = "linux"
128 ),
129 all(
130 any(
131 target_arch = "x86_64",
132 target_arch = "aarch64",
133 target_arch = "arm",
134 target_arch = "riscv32",
135 target_arch = "xtensa"
136 ),
137 target_os = "none"
138 )
139 )
140))]
141pub use stackful;
142pub use standard::*;
143pub use task as exported_task;
144pub use traits::*;
145pub use virtual_file_system as exported_virtual_file_system;
146
147use alloc::{string::String, vec::Vec};
148use file_system::{AccessFlags, Kind, Path, Permission, Position, Statistics};
149use task::{JoinHandle, SpawnerIdentifier, TaskIdentifier};
150use users::UserIdentifier;
151use virtual_file_system::File;
152
153pub async fn is_execute_allowed(
157 users_manager: &users::Manager,
158 statistics: &Statistics,
159 user: UserIdentifier,
160) -> bool {
161 if statistics
162 .permissions
163 .get_others()
164 .contains(Permission::Execute)
165 {
166 return true;
167 }
168
169 let is_user_allowed = user == UserIdentifier::ROOT || user == statistics.user;
170 if is_user_allowed
171 && statistics
172 .permissions
173 .get_user()
174 .contains(Permission::Execute)
175 {
176 return true;
177 }
178
179 let is_in_group =
180 users_manager.is_in_group(user, statistics.group).await || user == UserIdentifier::ROOT;
181 is_in_group
182 && statistics
183 .permissions
184 .get_group()
185 .contains(Permission::Execute)
186}
187
188fn get_overridden_user(
189 statistics: &Statistics,
190 current_user: UserIdentifier,
191) -> Result<Option<UserIdentifier>> {
192 if !statistics
193 .permissions
194 .get_special()
195 .get_set_user_identifier()
196 {
197 return Ok(None);
198 }
199
200 let new_user = statistics.user;
201
202 if current_user != users::UserIdentifier::ROOT || new_user != current_user {
203 return Err(Error::PermissionDenied);
204 }
205
206 Ok(Some(new_user))
207}
208
209pub async fn execute(
210 context: &'static ExecutableContext,
211 path: impl AsRef<Path>,
212 inputs: Vec<String>,
213 standard: Standard<'static>,
214 spawner: Option<SpawnerIdentifier>,
215) -> Result<JoinHandle<isize>> {
216 execute_with(context, path, inputs, standard, spawner, Launch::default()).await
217}
218
219pub async fn execute_with(
223 context: &'static ExecutableContext,
224 path: impl AsRef<Path>,
225 inputs: Vec<String>,
226 standard: Standard<'static>,
227 spawner: Option<SpawnerIdentifier>,
228 launch: Launch,
229) -> Result<JoinHandle<isize>> {
230 let (handle, _) =
231 execute_inner(context, path.as_ref(), inputs, standard, spawner, launch).await?;
232 Ok(handle)
233}
234
235async fn execute_inner(
237 context: &'static ExecutableContext,
238 path: &Path,
239 inputs: Vec<String>,
240 standard: Standard<'static>,
241 spawner: Option<SpawnerIdentifier>,
242 launch: Launch,
243) -> Result<(JoinHandle<isize>, TaskIdentifier)> {
244 if !lifecycle::SYSTEM.is_running() {
247 return Err(virtual_file_system::IoErrorKind::ResourceBusy.into());
248 }
249 let task_instance = &context.task_manager;
250
251 let task = task_instance.try_get_current_task_identifier().await?;
252
253 let virtual_file_system = &context.virtual_file_system;
254
255 let statistics = virtual_file_system.get_statistics(&path).await?;
257
258 let identity = launch.identity;
261 let user = match identity {
262 Some(identity) => identity.user,
263 None => task_instance.get_user(task).await?,
264 };
265
266 if !is_execute_allowed(context.users_manager, &statistics, user).await {
268 return Err(Error::PermissionDenied);
269 }
270
271 let mut file = File::open(virtual_file_system, task, path, AccessFlags::Read.into()).await?;
272
273 let file_name = path
274 .get_file_name()
275 .ok_or(virtual_file_system::IoErrorKind::InvalidPath)?;
276
277 if statistics.kind == Kind::File {
278 let mut magic = [0; 4];
279 let mut read = 0;
280 while read < magic.len() {
281 let count = file.read(&mut magic[read..]).await?;
282 if count == 0 {
283 break;
284 }
285 read += count;
286 }
287 if read != 0 {
288 file.set_position(&Position::Start(0)).await?;
289 }
290 if read == magic.len()
291 && let Some(handler) = find_format(
292 context.formats,
293 magic,
294 statistics
295 .permissions
296 .get_special()
297 .get_set_user_identifier(),
298 )?
299 {
300 if identity.is_some() {
303 return Err(Error::PermissionDenied);
304 }
305 let mut standard = standard;
306 standard.context = context;
307 return handler
308 .launch(FormatRequest {
309 file,
310 file_size: statistics.size,
311 name: String::from(file_name),
312 parent: task,
313 spawner,
314 standard,
315 arguments: inputs,
316 launch,
317 })
318 .await;
319 }
320 }
321
322 let new_user = get_overridden_user(&statistics, user)?;
323
324 let main_function_abi = file.control(GET_MAIN_FUNCTION, &()).await?;
325 let main_function = unsafe { main_function_abi.into_main_function() };
327
328 let main = main_function.ok_or(Error::FailedToGetMainFunction)?;
329
330 let spawned = task_instance
331 .spawn(task, file_name, spawner, async move |task| {
332 if let Some(identity) = identity
338 && context
339 .task_manager
340 .grant_identity(task, identity.user, identity.group)
341 .await
342 .is_err()
343 {
344 return -1;
345 }
346 if let Some(new_user) = new_user {
347 context.task_manager.set_user(task, new_user).await.unwrap();
348 }
349 if let Some(environment) = launch.environment {
350 let _ = context
352 .task_manager
353 .replace_environment_variables(task, environment)
354 .await;
355 }
356
357 match main(context, standard, inputs).await {
358 Ok(_) => 0_isize,
359 Err(error) => -(error.get() as isize),
360 }
361 })
362 .await?;
363
364 Ok(spawned)
365}
366
367#[cfg(test)]
368mod tests {
369 extern crate std;
370
371 use file_system::{Permissions, Time};
372
373 use task::test;
374 use users::GroupIdentifier;
375
376 use super::*;
377
378 fn get_statistics_with_permissions(permissions: Permissions) -> Statistics {
379 Statistics::new(
380 0,
381 1,
382 0,
383 Time::new(0),
384 Time::new(0),
385 Time::new(0),
386 Time::new(0),
387 file_system::Kind::File,
388 permissions,
389 UserIdentifier::ROOT,
390 GroupIdentifier::ROOT,
391 )
392 }
393
394 #[test]
395 async fn test_is_execute_allowed() {
396 let users_manager = users::Manager::new();
397
398 let statistics = get_statistics_with_permissions(Permissions::ALL_FULL);
399 assert!(is_execute_allowed(&users_manager, &statistics, UserIdentifier::ROOT).await);
400
401 let statistics = get_statistics_with_permissions(Permissions::EXECUTABLE);
402 assert!(is_execute_allowed(&users_manager, &statistics, UserIdentifier::ROOT).await);
403
404 let statistics = get_statistics_with_permissions(Permissions::from_octal(0o007).unwrap());
405 assert!(is_execute_allowed(&users_manager, &statistics, UserIdentifier::ROOT).await);
406
407 let statistics = get_statistics_with_permissions(Permissions::from_octal(0o070).unwrap());
408 assert!(is_execute_allowed(&users_manager, &statistics, UserIdentifier::ROOT).await);
409
410 let statistics = get_statistics_with_permissions(Permissions::from_octal(0o100).unwrap());
411 assert!(is_execute_allowed(&users_manager, &statistics, UserIdentifier::ROOT).await);
412
413 let statistics = get_statistics_with_permissions(Permissions::USER_READ_WRITE);
414 assert!(!is_execute_allowed(&users_manager, &statistics, UserIdentifier::ROOT).await);
415
416 let statistics = get_statistics_with_permissions(Permissions::NONE);
417 assert!(!is_execute_allowed(&users_manager, &statistics, UserIdentifier::ROOT).await);
418
419 let statistics = get_statistics_with_permissions(Permissions::ALL_READ_WRITE);
420 assert!(!is_execute_allowed(&users_manager, &statistics, UserIdentifier::ROOT).await);
421 }
422}
423
424#[cfg(test)]
425mod format_tests {
426 use super::*;
427
428 struct Handler;
429 impl FormatHandler for Handler {
430 fn launch(&self, _: FormatRequest) -> FormatLaunch<'_> {
431 unreachable!()
432 }
433 }
434
435 static FORMATS: [ExecutableFormat; 2] = [
436 ExecutableFormat::new(*b"\0asm", &Handler),
437 ExecutableFormat::new(*b"\x7fELF", &Handler),
438 ];
439
440 #[test]
441 fn detects_registered_formats_and_applies_native_policy() {
442 assert!(find_format(&FORMATS, *b"\0asm", false).unwrap().is_some());
443 assert!(find_format(&FORMATS, *b"data", false).unwrap().is_none());
444 assert!(matches!(
445 find_format(&FORMATS, *b"\x7fELF", true),
446 Err(Error::PermissionDenied)
447 ));
448 assert!(matches!(
449 find_format(&[], *b"\x7fELF", false),
450 Err(Error::PermissionDenied)
451 ));
452 let native = find_format(&FORMATS, *b"\x7fELF", false);
453 if cfg!(feature = "native-dev") {
454 assert!(native.unwrap().is_some());
455 } else {
456 assert!(matches!(native, Err(Error::PermissionDenied)));
457 }
458 }
459}