Skip to main content

executable/
format.rs

1use alloc::{boxed::Box, string::String, vec::Vec};
2use core::pin::Pin;
3use file_system::PathOwned;
4use task::{EnvironmentVariable, JoinHandle, SpawnerIdentifier, TaskIdentifier};
5use users::{GroupIdentifier, UserIdentifier};
6use virtual_file_system::File;
7
8use crate::{Error, Result, Standard};
9
10pub(crate) const ELF: [u8; 4] = *b"\x7fELF";
11
12/// Platform registration for a four-byte file magic. The context searches
13/// registrations in order. Mounted executables continue to use their control command.
14pub struct ExecutableFormat {
15    magic: [u8; 4],
16    handler: &'static dyn FormatHandler,
17}
18
19impl ExecutableFormat {
20    pub const fn new(magic: [u8; 4], handler: &'static dyn FormatHandler) -> Self {
21        Self { magic, handler }
22    }
23}
24
25/// A directory capability a launched program gets as its home, bound to its own task.
26pub struct Home {
27    pub path: PathOwned,
28    pub rights: u8,
29}
30
31/// The user and group a launched program runs as, instead of its parent's.
32#[derive(Clone, Copy, Debug, PartialEq, Eq)]
33pub struct Identity {
34    pub user: UserIdentifier,
35    pub group: GroupIdentifier,
36}
37
38/// The network rights a launch grants a native process: connecting (and sending
39/// datagrams), listening (and binding) and resolving names. A launch grants none by
40/// default.
41#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
42pub struct NetworkRights(u8);
43
44impl NetworkRights {
45    /// No network: the default.
46    pub const NONE: Self = Self(0);
47    /// Open TCP connections and send UDP datagrams.
48    pub const CONNECT: Self = Self(1);
49    /// Listen for TCP connections and bind UDP sockets.
50    pub const LISTEN: Self = Self(2);
51    /// Resolve host names.
52    pub const RESOLVE: Self = Self(4);
53    /// Every right.
54    pub const ALL: Self = Self(7);
55
56    /// The rights in either set.
57    pub const fn union(self, other: Self) -> Self {
58        Self(self.0 | other.0)
59    }
60
61    /// Whether every right of `other` is in this set.
62    pub const fn contains(self, other: Self) -> bool {
63        self.0 & other.0 == other.0
64    }
65
66    pub const fn is_empty(self) -> bool {
67        self.0 == 0
68    }
69
70    /// The rights as the native ABI's `XILA_NETWORK_*` bits.
71    pub const fn bits(self) -> u8 {
72        self.0
73    }
74
75    /// The set from `XILA_NETWORK_*` bits, or `None` if an unknown bit is set.
76    pub const fn from_bits(bits: u8) -> Option<Self> {
77        if bits & !Self::ALL.0 == 0 {
78            Some(Self(bits))
79        } else {
80            None
81        }
82    }
83}
84
85impl core::ops::BitOr for NetworkRights {
86    type Output = Self;
87
88    fn bitor(self, other: Self) -> Self {
89        self.union(other)
90    }
91}
92
93/// Optional parameters of a launch beyond the program's arguments and streams.
94///
95/// A handler applies the home capability only if its format supports one. It must
96/// apply `environment` in every case and fail the launch if it cannot: an explicit
97/// environment is a confinement request, so ignoring it would hand the program the
98/// caller's whole environment (fail closed).
99///
100/// An `identity` is applied to mounted native executables only: the launch of any
101/// registered file format (WebAssembly, native images) with an identity is refused,
102/// so a format handler never has to apply one (fail closed).
103///
104/// `network` is denied by default: a program gets network authority only from an
105/// explicit [`Launch::with_network`], and only formats with a socket interface apply
106/// it (native executables, through `XilaStartup.network`). WebAssembly applications
107/// get no sockets, so a grant has no effect on them.
108#[derive(Default)]
109#[non_exhaustive]
110pub struct Launch {
111    /// The program's whole environment, replacing the copy its task makes of the
112    /// parent's. A later variable overrides an earlier one of the same name.
113    pub environment: Option<Vec<EnvironmentVariable>>,
114    /// Home directory capability for programs that take one (native executables).
115    pub home: Option<Home>,
116    /// The user and group of the new task, replacing the ones it inherits from its
117    /// parent. Deciding who may run a program as another user is the caller's job
118    /// (see [`Launch::with_identity`]).
119    pub identity: Option<Identity>,
120    /// The network rights of the program. None by default (see [`Launch::with_network`]).
121    pub network: NetworkRights,
122}
123
124impl Launch {
125    /// Give the program this whole environment instead of a copy of its parent's.
126    pub fn with_environment(mut self, environment: Vec<EnvironmentVariable>) -> Self {
127        self.environment = Some(environment);
128        self
129    }
130
131    /// Give the program this home directory capability.
132    pub fn with_home(mut self, home: Home) -> Self {
133        self.home = Some(home);
134        self
135    }
136
137    /// Run the program as `user` and `group` instead of the caller's identity.
138    ///
139    /// The identity is set on the new task before the program starts, and only on
140    /// that task (and the tasks it starts): the caller's own identity never changes.
141    /// The new task and all its descendants are marked as running with a granted
142    /// identity, which they cannot clear (`task::Manager::is_identity_granted`), so
143    /// runtimes for untrusted code can refuse to run under it.
144    /// The execute permission is checked for `user`. The caller must have
145    /// authorized the change itself, for example by authenticating an
146    /// administrator, because this function grants it unconditionally.
147    pub fn with_identity(mut self, user: UserIdentifier, group: GroupIdentifier) -> Self {
148        self.identity = Some(Identity { user, group });
149        self
150    }
151
152    /// Grant the program these network rights. Without this call it has no network.
153    ///
154    /// A native process that spawns a child can pass it a subset of these rights and
155    /// never more. Deciding which programs may use the network is the caller's job:
156    /// this function grants the rights unconditionally.
157    pub fn with_network(mut self, rights: NetworkRights) -> Self {
158        self.network = rights;
159        self
160    }
161}
162
163#[non_exhaustive]
164pub struct FormatRequest {
165    /// The already-opened executable file, positioned at the beginning.
166    pub file: File<'static>,
167    pub file_size: file_system::Size,
168    pub name: String,
169    pub parent: TaskIdentifier,
170    pub spawner: Option<SpawnerIdentifier>,
171    pub standard: Standard<'static>,
172    pub arguments: Vec<String>,
173    pub launch: Launch,
174}
175
176/// Start a registered file format and return the child's exit-status handle and task.
177pub trait FormatHandler: Sync {
178    fn launch(&self, request: FormatRequest) -> FormatLaunch<'_>;
179}
180
181pub type FormatLaunch<'a> =
182    Pin<Box<dyn Future<Output = Result<(JoinHandle<isize>, TaskIdentifier)>> + 'a>>;
183
184pub(crate) fn find_format(
185    formats: &[ExecutableFormat],
186    magic: [u8; 4],
187    setuid: bool,
188) -> Result<Option<&'static dyn FormatHandler>> {
189    let handler = formats
190        .iter()
191        .find(|format| format.magic == magic)
192        .map(|format| format.handler);
193    if (magic == ELF && (!cfg!(feature = "native-dev") || handler.is_none()))
194        || (handler.is_some() && setuid)
195    {
196        return Err(Error::PermissionDenied);
197    }
198    Ok(handler)
199}