oscall 0.1.0

Low-level cross-platform interface to operating system services: files, memory mapping, networking and more, with no libc on Linux
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
//! What `process::linux` is made of: namespaces, identifier maps, pidfds,
//! `prctl`, and the `clone3` that `spawn` needs for a cgroup or a time
//! namespace.
//!
//! The constants are those of `include/uapi/linux/sched.h` and
//! `include/uapi/linux/prctl.h`, which every architecture shares.

use crate::process::linux::{IdMap, Namespaces};
use crate::sys::{errno, syscall};
use crate::{Error, ErrorKind, OwnedHandle, Result};

const CLONE_NEWTIME: usize = 0x80;
const CLONE_NEWNS: usize = 0x0002_0000;
const CLONE_NEWCGROUP: usize = 0x0200_0000;
const CLONE_NEWUTS: usize = 0x0400_0000;
const CLONE_NEWIPC: usize = 0x0800_0000;
const CLONE_NEWUSER: usize = 0x1000_0000;
const CLONE_NEWPID: usize = 0x2000_0000;
const CLONE_NEWNET: usize = 0x4000_0000;

const O_WRONLY: usize = 1;
/// The same on every architecture.
const O_CLOEXEC: usize = 0o2000000;
const AT_FDCWD: i32 = -100;

const PR_GET_DUMPABLE: usize = 3;
const PR_SET_DUMPABLE: usize = 4;
const PR_SET_CHILD_SUBREAPER: usize = 36;
const PR_GET_CHILD_SUBREAPER: usize = 37;
pub(crate) const PR_SET_NO_NEW_PRIVS: usize = 38;
const PR_GET_NO_NEW_PRIVS: usize = 39;

/// The `CLONE_NEW*` flags of `namespaces`.
pub(crate) fn clone_flags(namespaces: Namespaces) -> usize {
    let table = [
        (Namespaces::MOUNT, CLONE_NEWNS),
        (Namespaces::UTS, CLONE_NEWUTS),
        (Namespaces::IPC, CLONE_NEWIPC),
        (Namespaces::USER, CLONE_NEWUSER),
        (Namespaces::PID, CLONE_NEWPID),
        (Namespaces::NETWORK, CLONE_NEWNET),
        (Namespaces::CGROUP, CLONE_NEWCGROUP),
        (Namespaces::TIME, CLONE_NEWTIME),
    ];
    let mut flags = 0;
    for (namespace, flag) in table {
        if namespaces.contains(namespace) {
            flags |= flag;
        }
    }
    flags
}

pub(crate) fn unshare(namespaces: Namespaces) -> Result<()> {
    // SAFETY: no memory is involved.
    unsafe { syscall!(UNSHARE, clone_flags(namespaces)) }.map(drop)
}

pub(crate) fn setns(fd: i32, namespaces: Namespaces) -> Result<()> {
    // SAFETY: no memory is involved.
    unsafe { syscall!(SETNS, fd, clone_flags(namespaces)) }.map(drop)
}

pub(crate) fn set_host_name(name: &[u8]) -> Result<()> {
    // SAFETY: the kernel reads `name.len()` bytes at `name`.
    unsafe { syscall!(SETHOSTNAME, name.as_ptr(), name.len()) }.map(drop)
}

pub(crate) fn pidfd_open(pid: u32) -> Result<OwnedHandle> {
    // SAFETY: no memory is involved.
    let fd = unsafe { syscall!(PIDFD_OPEN, pid, 0) }?;
    // SAFETY: the descriptor was just created (close-on-exec, as pidfds
    // always are).
    Ok(unsafe { OwnedHandle::from_raw(fd as i32) })
}

pub(crate) fn pidfd_send_signal(pidfd: i32, signal: i32) -> Result<()> {
    // SAFETY: no memory is involved (no `siginfo` is given).
    unsafe { syscall!(PIDFD_SEND_SIGNAL, pidfd, signal, 0, 0) }.map(drop)
}

/// `prctl` with one integer argument; the three others must be zero for
/// the options used here.
fn prctl(option: usize, value: usize) -> Result<usize> {
    // SAFETY: none of the options used with this passes memory.
    unsafe { syscall!(PRCTL, option, value, 0, 0, 0) }
}

pub(crate) fn set_no_new_privileges() -> Result<()> {
    prctl(PR_SET_NO_NEW_PRIVS, 1).map(drop)
}

pub(crate) fn no_new_privileges() -> Result<bool> {
    prctl(PR_GET_NO_NEW_PRIVS, 0).map(|value| value != 0)
}

pub(crate) fn set_child_subreaper(on: bool) -> Result<()> {
    prctl(PR_SET_CHILD_SUBREAPER, usize::from(on)).map(drop)
}

pub(crate) fn is_child_subreaper() -> Result<bool> {
    let mut value: i32 = 0;
    // SAFETY: the kernel writes one `int`.
    unsafe { syscall!(PRCTL, PR_GET_CHILD_SUBREAPER, &raw mut value, 0, 0, 0) }?;
    Ok(value != 0)
}

pub(crate) fn set_dumpable(on: bool) -> Result<()> {
    prctl(PR_SET_DUMPABLE, usize::from(on)).map(drop)
}

pub(crate) fn is_dumpable() -> Result<bool> {
    // 2 is "by root only" (`fs.suid_dumpable`): not dumpable, to anyone
    // this process could be hiding from.
    prctl(PR_GET_DUMPABLE, 0).map(|value| value == 1)
}

/// The text of a `uid_map` or `gid_map` file. The kernel wants it whole in
/// one `write` shorter than a page.
pub(crate) struct MapText {
    buf: [u8; 4096],
    len: usize,
}

impl MapText {
    /// A line per range: `inside outside count`.
    pub(crate) fn new(map: &[IdMap]) -> Result<Self> {
        let mut text = Self {
            buf: [0; 4096],
            len: 0,
        };
        // The kernel refuses an empty map with the same error.
        if map.is_empty() {
            return Err(ErrorKind::InvalidInput.into());
        }
        for range in map {
            text.number(range.inside, b' ')?;
            text.number(range.outside, b' ')?;
            text.number(range.count, b'\n')?;
        }
        Ok(text)
    }

    fn number(&mut self, value: u32, end: u8) -> Result<()> {
        let mut digits = [0u8; 10];
        let digits = decimal(value, &mut digits);
        let buf = self
            .buf
            .get_mut(self.len..self.len + digits.len() + 1)
            .ok_or(ErrorKind::InvalidInput)?;
        buf[..digits.len()].copy_from_slice(digits);
        buf[digits.len()] = end;
        self.len += digits.len() + 1;
        Ok(())
    }

    pub(crate) fn as_bytes(&self) -> &[u8] {
        &self.buf[..self.len]
    }
}

/// `value` in decimal, at the end of `buf`.
fn decimal(mut value: u32, buf: &mut [u8; 10]) -> &[u8] {
    let mut start = buf.len();
    loop {
        start -= 1;
        buf[start] = b'0' + (value % 10) as u8;
        value /= 10;
        if value == 0 {
            break;
        }
    }
    &buf[start..]
}

/// Writes `data`, in one `write`, to the file `name` of `/proc/<pid>`.
/// Only system calls: `spawn` calls this with a child that waits.
pub(crate) fn write_proc(pid: u32, name: &[u8], data: &[u8]) -> Result<()> {
    // "/proc/", ten digits, "/", the name, a NUL.
    let mut path = [0u8; 40];
    let mut digits = [0u8; 10];
    let digits = decimal(pid, &mut digits);
    let mut len = 0;
    for part in [b"/proc/".as_slice(), digits, b"/", name] {
        path.get_mut(len..len + part.len())
            .ok_or(ErrorKind::InvalidInput)?
            .copy_from_slice(part);
        len += part.len();
    }
    if len >= path.len() {
        return Err(ErrorKind::InvalidInput.into());
    }
    // SAFETY: `path` ends with a NUL: it is longer than what was written.
    let fd = unsafe {
        syscall!(
            OPENAT,
            AT_FDCWD,
            path.as_ptr(),
            O_WRONLY | O_CLOEXEC,
            0usize
        )
    }?;
    // SAFETY: the descriptor was just opened.
    let file = unsafe { OwnedHandle::from_raw(fd as i32) };
    // SAFETY: the kernel reads `data.len()` bytes at `data`.
    let written = unsafe { syscall!(WRITE, file.as_raw(), data.as_ptr(), data.len()) }?;
    if written != data.len() {
        return Err(Error::from_raw_os_error(errno::EIO));
    }
    Ok(())
}

pub(crate) fn write_id_map(pid: u32, name: &[u8], map: &[IdMap]) -> Result<()> {
    write_proc(pid, name, MapText::new(map)?.as_bytes())
}

pub(crate) fn allow_setgroups(pid: u32, allow: bool) -> Result<()> {
    let text: &[u8] = if allow { b"allow" } else { b"deny" };
    write_proc(pid, b"setgroups", text)
}

#[cfg(test)]
mod tests {
    use super::{IdMap, MapText};

    #[test]
    fn map_text() {
        let range = |inside, outside, count| IdMap {
            inside,
            outside,
            count,
        };
        let text = |map: &[IdMap]| MapText::new(map).map(|text| text.as_bytes().len());
        let map = [range(0, 1000, 1), range(1, 100_000, 65_535)];
        let written = MapText::new(&map).unwrap();
        assert_eq!(written.as_bytes(), b"0 1000 1\n1 100000 65535\n");
        let widest = MapText::new(&[range(u32::MAX, u32::MAX, u32::MAX)]).unwrap();
        assert_eq!(
            widest.as_bytes(),
            b"4294967295 4294967295 4294967295\n".as_slice()
        );
        assert!(text(&[]).is_err());
        // 33 bytes a line: 124 lines fit in 4096 bytes, 125 do not.
        assert_eq!(text(&[range(u32::MAX, u32::MAX, u32::MAX); 124]), Ok(4092));
        assert!(text(&[range(u32::MAX, u32::MAX, u32::MAX); 125]).is_err());
    }
}

#[cfg(feature = "alloc")]
pub(crate) use spawn::{CLONE_INTO_CGROUP, CloneArgs, Maps, clone3_vfork, join_cgroup};

#[cfg(feature = "alloc")]
mod spawn {
    use core::ffi::c_void;

    use super::{MapText, O_CLOEXEC, O_WRONLY, allow_setgroups, write_proc};
    use crate::process::linux::{Namespaces, Options};
    use crate::sys::{nr, syscall};
    use crate::{ErrorKind, Result};

    pub(crate) const CLONE_INTO_CGROUP: u64 = 0x2_0000_0000;

    /// `struct clone_args`, as of Linux 5.7 (`CLONE_ARGS_SIZE_VER2`): every
    /// field is an `__aligned_u64`, pointers included.
    #[repr(C, align(8))]
    #[derive(Default)]
    pub(crate) struct CloneArgs {
        pub(crate) flags: u64,
        /// Where the pidfd is written (`CLONE_PIDFD`): a pointer to an
        /// `int`.
        pub(crate) pidfd: u64,
        pub(crate) child_tid: u64,
        pub(crate) parent_tid: u64,
        pub(crate) exit_signal: u64,
        /// The lowest address of the child's stack, and its size: the
        /// child starts at the other end.
        pub(crate) stack: u64,
        pub(crate) stack_size: u64,
        pub(crate) tls: u64,
        pub(crate) set_tid: u64,
        pub(crate) set_tid_size: u64,
        /// The descriptor of a cgroup directory (`CLONE_INTO_CGROUP`).
        pub(crate) cgroup: u64,
    }

    const _: () = assert!(size_of::<CloneArgs>() == 88 && align_of::<CloneArgs>() == 8);

    /// What the parent writes to `/proc/<pid>` for a child created in a new
    /// user namespace, while the child waits. Prepared before the child
    /// exists.
    pub(crate) struct Maps {
        deny_setgroups: bool,
        uid: Option<MapText>,
        gid: Option<MapText>,
    }

    impl Maps {
        /// `None` when the command asks for nothing of the kind, and the
        /// child need not wait.
        pub(crate) fn new(options: &Options<'_>) -> Result<Option<Self>> {
            if options.uid_map.is_none() && options.gid_map.is_none() && !options.deny_setgroups {
                return Ok(None);
            }
            // They are the files of a user namespace the child owns.
            if !options.namespaces.contains(Namespaces::USER) {
                return Err(ErrorKind::InvalidInput.into());
            }
            Ok(Some(Self {
                deny_setgroups: options.deny_setgroups,
                uid: options.uid_map.map(MapText::new).transpose()?,
                gid: options.gid_map.map(MapText::new).transpose()?,
            }))
        }

        /// Writes the files of the child `pid`. Only system calls.
        pub(crate) fn write(&self, pid: u32) -> Result<()> {
            // In this order: without privilege, the group map is only
            // accepted once `setgroups` is denied.
            if self.deny_setgroups {
                allow_setgroups(pid, false)?;
            }
            if let Some(gid) = &self.gid {
                write_proc(pid, b"gid_map", gid.as_bytes())?;
            }
            if let Some(uid) = &self.uid {
                write_proc(pid, b"uid_map", uid.as_bytes())?;
            }
            Ok(())
        }
    }

    /// Moves the calling process into the cgroup whose directory is
    /// `cgroup`: writes `0` to its `cgroup.procs`. For the child of
    /// `spawn`, where `clone3` could not put it there.
    ///
    /// # Safety
    ///
    /// Makes system calls only, and is meant for a process that may do
    /// nothing else.
    pub(crate) unsafe fn join_cgroup(cgroup: i32) -> Result<()> {
        let name = c"cgroup.procs";
        // SAFETY: the name is a C string, the byte written is readable.
        unsafe {
            let fd = syscall!(OPENAT, cgroup, name.as_ptr(), O_WRONLY | O_CLOEXEC, 0usize)?;
            let written = syscall!(WRITE, fd, b"0".as_ptr(), 1usize);
            let _ = syscall!(CLOSE, fd);
            written.map(drop)
        }
    }

    /// `clone3(args, size)`, for a child that shares the memory of the
    /// caller and runs `f(arg)` on the stack `args` gives it. Returns the
    /// child's process identifier, or a negative error number.
    ///
    /// The child starts with the registers of the caller and its stack
    /// pointer at the end of the stack (`stack + stack_size`, which must be
    /// aligned to 16 bytes): `f` and `arg` travel in registers the system
    /// call preserves.
    ///
    /// # Safety
    ///
    /// `args` must point to `size` bytes of a valid `struct clone_args`
    /// whose flags have `CLONE_VM`, and whose stack is a writable region
    /// large enough for `f`. `f` runs in a copy of the calling thread that
    /// shares its memory and its thread-local storage: it must only make
    /// system calls, and must not allocate, panic, take locks nor touch
    /// thread-local state.
    #[cfg(target_arch = "x86_64")]
    #[unsafe(naked)]
    pub(crate) unsafe extern "C" fn clone3_vfork(
        args: *const CloneArgs,
        size: usize,
        f: unsafe extern "C" fn(*mut c_void) -> !,
        arg: *mut c_void,
    ) -> isize {
        // rdi = args, rsi = size, rdx = f, rcx = arg. The system call
        // clobbers rcx and r11.
        core::arch::naked_asm!(
            "mov r8, rcx",
            "mov eax, {clone3}",
            "syscall",
            "test rax, rax",
            "jz 2f",
            "ret",
            // The child: rsp is the end of the new stack, 16-byte aligned
            // as the ABI wants before a call.
            "2:",
            "xor ebp, ebp",
            "mov rdi, r8",
            "call rdx",
            "ud2",
            clone3 = const nr::CLONE3,
        )
    }

    /// See the x86_64 version.
    #[cfg(target_arch = "x86")]
    #[unsafe(naked)]
    pub(crate) unsafe extern "C" fn clone3_vfork(
        args: *const CloneArgs,
        size: usize,
        f: unsafe extern "C" fn(*mut c_void) -> !,
        arg: *mut c_void,
    ) -> isize {
        // After the pushes: [esp + 16] = args, + 20 = size, + 24 = f,
        // + 28 = arg. `int 0x80` preserves every register but eax.
        core::arch::naked_asm!(
            "push ebx",
            "push esi",
            "push edi",
            "mov ebx, [esp + 16]",
            "mov ecx, [esp + 20]",
            "mov esi, [esp + 24]",
            "mov edi, [esp + 28]",
            "mov eax, {clone3}",
            "int 0x80",
            "test eax, eax",
            "jz 2f",
            "pop edi",
            "pop esi",
            "pop ebx",
            "ret",
            // The child: esp is the end of the new stack. The argument
            // goes on it, and esp is 16-byte aligned at the call.
            "2:",
            "xor ebp, ebp",
            "sub esp, 16",
            "mov [esp], edi",
            "call esi",
            "ud2",
            clone3 = const nr::CLONE3,
        )
    }

    /// See the x86_64 version.
    #[cfg(target_arch = "aarch64")]
    #[unsafe(naked)]
    pub(crate) unsafe extern "C" fn clone3_vfork(
        args: *const CloneArgs,
        size: usize,
        f: unsafe extern "C" fn(*mut c_void) -> !,
        arg: *mut c_void,
    ) -> isize {
        // x0 = args, x1 = size, x2 = f, x3 = arg. `svc` preserves every
        // register but x0.
        core::arch::naked_asm!(
            // `bti c`, a no-op where branch target identification is off.
            "hint #34",
            "mov x8, {clone3}",
            "svc #0",
            "cbz x0, 2f",
            "ret",
            // The child: sp is the end of the new stack, 16-byte aligned.
            "2:",
            "mov x29, #0",
            "mov x30, #0",
            "mov x0, x3",
            "blr x2",
            "brk #1",
            clone3 = const nr::CLONE3,
        )
    }

    /// See the x86_64 version.
    #[cfg(target_arch = "arm")]
    #[unsafe(naked)]
    pub(crate) unsafe extern "C" fn clone3_vfork(
        args: *const CloneArgs,
        size: usize,
        f: unsafe extern "C" fn(*mut c_void) -> !,
        arg: *mut c_void,
    ) -> isize {
        // r0 = args, r1 = size, r2 = f, r3 = arg, the number in r7. `svc`
        // preserves every register but r0. The number does not fit one
        // immediate operand of the ARM instruction set: it is put together
        // from two, which exist in Thumb-2 as well.
        core::arch::naked_asm!(
            "push {{r4, r7}}",
            "mov r7, #{high}",
            "orr r7, r7, #{low}",
            "svc 0",
            "cmp r0, #0",
            "beq 2f",
            "pop {{r4, r7}}",
            "bx lr",
            // The child: sp is the end of the new stack, 8-byte aligned.
            "2:",
            "mov r11, #0",
            "mov lr, #0",
            "mov r0, r3",
            "blx r2",
            "udf #0",
            high = const nr::CLONE3 & !0xf,
            low = const nr::CLONE3 & 0xf,
        )
    }

    /// See the x86_64 version.
    #[cfg(any(target_arch = "riscv32", target_arch = "riscv64"))]
    #[unsafe(naked)]
    pub(crate) unsafe extern "C" fn clone3_vfork(
        args: *const CloneArgs,
        size: usize,
        f: unsafe extern "C" fn(*mut c_void) -> !,
        arg: *mut c_void,
    ) -> isize {
        // a0 = args, a1 = size, a2 = f, a3 = arg, the number in a7.
        // `ecall` preserves every register but a0.
        core::arch::naked_asm!(
            "li a7, {clone3}",
            "ecall",
            "beqz a0, 2f",
            "ret",
            // The child: sp is the end of the new stack, 16-byte aligned.
            "2:",
            "mv s0, zero",
            "mv ra, zero",
            "mv a0, a3",
            "jalr a2",
            "unimp",
            clone3 = const nr::CLONE3,
        )
    }
}