cloudfox-coreshift-core 2.17.0

Low-level Linux and Android systems primitives for CoreShift (CloudFox)
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
525
526
527
528
529
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/

//! `fork`/`execve` backend.
//!
//! Owns the child setup protocol (`ChildSetupOp`, the error pipe handshake),
//! fd-policy handling in the child, and the `fork` launch path used when
//! [`SpawnBackend::Fork`](crate::spawn::SpawnBackend::Fork) is selected.

use std::ffi::CString;
use std::os::unix::io::RawFd;

use crate::CoreError;
use crate::error::syscall_ret;
use crate::signal::SignalRuntime;
use libc::{c_char, pid_t};

use super::exec::ExecArgv;
use super::{
    Pipes, Process, SpawnDrain, SpawnFdPolicy, SpawnOptions, environ, errno, make_cloexec_pipe,
};

#[repr(u8)]
#[derive(Clone, Copy)]
enum ChildSetupOp {
    DupStdin = 1,
    DupStdout = 2,
    DupStderr = 3,
    Setsid = 4,
    Chdir = 5,
    Setpgid = 6,
    SignalMask = 7,
    Execve = 8,
    CloseFds = 9,
}

impl ChildSetupOp {
    fn as_str(self) -> &'static str {
        match self {
            Self::DupStdin => "spawn child dup2 stdin",
            Self::DupStdout => "spawn child dup2 stdout",
            Self::DupStderr => "spawn child dup2 stderr",
            Self::Setsid => "spawn child setsid",
            Self::Chdir => "spawn child chdir",
            Self::Setpgid => "spawn child setpgid",
            Self::SignalMask => "spawn child signal setup",
            Self::Execve => "spawn child execve",
            Self::CloseFds => "spawn child fd policy scan",
        }
    }

    fn from_u8(value: u8) -> Self {
        match value {
            1 => Self::DupStdin,
            2 => Self::DupStdout,
            3 => Self::DupStderr,
            4 => Self::Setsid,
            5 => Self::Chdir,
            6 => Self::Setpgid,
            7 => Self::SignalMask,
            8 => Self::Execve,
            9 => Self::CloseFds,
            _ => Self::Execve,
        }
    }
}

unsafe fn report_child_setup_error(fd: RawFd, op: ChildSetupOp, code: i32) -> ! {
    let mut msg = [0u8; 5];
    msg[..4].copy_from_slice(&code.to_ne_bytes());
    msg[4] = op as u8;
    let mut written = 0;
    while written < msg.len() {
        let n = unsafe {
            libc::write(
                fd,
                msg[written..].as_ptr().cast::<libc::c_void>(),
                msg.len() - written,
            )
        };
        if n < 0 {
            let e = errno();
            // A signal can interrupt the write; retry rather than exiting
            // with a partial message, which the parent would misread as EOF
            // (i.e. a successful spawn) after the child exits.
            if e == libc::EINTR {
                continue;
            }
            break;
        }
        if n == 0 {
            break;
        }
        written += n as usize;
    }
    unsafe {
        libc::_exit(127);
    }
}

fn read_child_setup_error(fd: RawFd) -> Result<Option<CoreError>, CoreError> {
    let mut msg = [0u8; 5];
    let mut read_len = 0;
    loop {
        let n = unsafe {
            libc::read(
                fd,
                msg[read_len..].as_mut_ptr().cast::<libc::c_void>(),
                msg.len() - read_len,
            )
        };
        if n == 0 {
            return Ok(None);
        }
        if n < 0 {
            let code = errno();
            if code == libc::EINTR {
                continue;
            }
            return Err(CoreError::sys(code, "read fork child setup error"));
        }
        read_len += n as usize;
        if read_len == msg.len() {
            let code = i32::from_ne_bytes([msg[0], msg[1], msg[2], msg[3]]);
            return Ok(Some(CoreError::sys(
                code,
                ChildSetupOp::from_u8(msg[4]).as_str(),
            )));
        }
    }
}

pub(super) fn collect_required_pipe_fds(pipes: &Pipes) -> Vec<RawFd> {
    let mut fds = Vec::new();
    if let Some(fd) = &pipes.stdin_r {
        fds.push(fd.raw());
    }
    if let Some(fd) = &pipes.stdin_w {
        fds.push(fd.raw());
    }
    if let Some(fd) = &pipes.stdout_r {
        fds.push(fd.raw());
    }
    if let Some(fd) = &pipes.stdout_w {
        fds.push(fd.raw());
    }
    if let Some(fd) = &pipes.stderr_r {
        fds.push(fd.raw());
    }
    if let Some(fd) = &pipes.stderr_w {
        fds.push(fd.raw());
    }
    fds
}

/// Close inherited descriptors in the child according to the fd policy.
///
/// The scan runs in the child *after* `fork()`, so it reflects the child's own
/// descriptor table and cannot be raced by other threads in the parent — a
/// parent-side snapshot would leak any fd opened between the snapshot and
/// `fork()`. `getdents64` into a fixed stack buffer keeps this
/// async-signal-safe (no allocation, no libc directory cursors). A scan
/// failure aborts the spawn through the setup-error pipe rather than silently
/// leaving every inherited fd open (a fail-open that would defeat the policy).
fn close_child_fds_for_policy(
    policy: &SpawnFdPolicy,
    required_fds: &[RawFd],
    child_error_w: RawFd,
) {
    match policy {
        SpawnFdPolicy::CloexecOnly => {}
        SpawnFdPolicy::CloseFrom3 | SpawnFdPolicy::Allowlist(_) => {
            let dir_fd = unsafe {
                libc::open(
                    c"/proc/self/fd".as_ptr(),
                    libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC,
                )
            };
            if dir_fd < 0 {
                unsafe {
                    report_child_setup_error(child_error_w, ChildSetupOp::CloseFds, errno());
                }
            }

            let mut buf = [0u8; 4096];
            loop {
                let n = unsafe {
                    libc::syscall(
                        libc::SYS_getdents64,
                        dir_fd,
                        buf.as_mut_ptr().cast::<libc::c_void>(),
                        buf.len(),
                    )
                };
                if n < 0 {
                    let e = errno();
                    // A signal can interrupt the scan; retry rather than
                    // aborting it, which would silently fail the policy open.
                    if e == libc::EINTR {
                        continue;
                    }
                    unsafe {
                        report_child_setup_error(child_error_w, ChildSetupOp::CloseFds, e);
                    }
                }
                if n == 0 {
                    break;
                }
                let mut off = 0usize;
                while off + 19 <= n as usize {
                    // linux_dirent64 layout: d_ino(8) d_off(8) d_reclen(2)
                    // d_type(1) d_name[].
                    let reclen = u16::from_ne_bytes([buf[off + 16], buf[off + 17]]) as usize;
                    if reclen < 19 || off + reclen > n as usize {
                        break;
                    }
                    let name = &buf[off + 19..off + reclen];
                    let name_end = name.iter().position(|&b| b == 0).unwrap_or(name.len());
                    if let Some(fd) = std::str::from_utf8(&name[..name_end])
                        .ok()
                        .and_then(|s| s.parse::<RawFd>().ok())
                    {
                        if fd > 2
                            && fd != dir_fd
                            && !required_fds.contains(&fd)
                            && !matches!(
                                policy,
                                SpawnFdPolicy::Allowlist(allowlist) if allowlist.contains(&fd)
                            )
                        {
                            unsafe {
                                libc::close(fd);
                            }
                        }
                    }
                    off += reclen;
                }
            }
            unsafe {
                libc::close(dir_fd);
            }
        }
    }
}

/// Parent-side state captured before the spawn syscall and handed read-only to
/// the child. The pointer vectors must be built in the parent: under `vfork`
/// the child shares the parent's heap, so any allocation there would corrupt
/// the parent's allocator state.
pub(super) struct ChildContext<'a> {
    pub exe_ptr: *const c_char,
    pub argv: Vec<*mut c_char>,
    pub envp: Option<Vec<*mut c_char>>,
    pub cwd: Option<&'a CString>,
}

pub(super) fn prepare_child_context(opts: &SpawnOptions) -> ChildContext<'_> {
    let exe_ptr = match &opts.ctx.argv {
        ExecArgv::Dynamic(v) => v[0].as_ptr(),
    };
    ChildContext {
        exe_ptr,
        argv: opts.ctx.get_argv_ptrs(),
        envp: opts.ctx.get_envp_ptrs(),
        cwd: opts.ctx.cwd.as_ref(),
    }
}

/// Child-side setup shared by every exec-style backend (`fork`, `vfork`,
/// `clone3`).
///
/// The child runs only async-signal-safe operations — raw syscalls into a
/// stack-local buffer, no allocation, no locks — and either `execve`s or
/// reports the failure on `child_error_w` and `_exit`s. It never returns.
///
/// # Safety
/// This must be called only in the child after `fork`/`vfork`/`clone3`.
/// Under `vfork` the address space is shared with the suspended parent, so the
/// caller must not mutate any parent-owned state (the pipe descriptors are
/// left open — they are `O_CLOEXEC` and closed by `execve`).
pub(super) unsafe fn child_entry(
    pipes: &Pipes,
    opts: &SpawnOptions,
    ctx: &ChildContext<'_>,
    required_fds: &[RawFd],
    child_error_r: RawFd,
    child_error_w: RawFd,
) -> ! {
    unsafe {
        libc::close(child_error_r);

        // dup stdin
        if let (Some(r), Some(_)) = (&pipes.stdin_r, &pipes.stdin_w) {
            if libc::dup2(r.raw(), 0) < 0 {
                report_child_setup_error(child_error_w, ChildSetupOp::DupStdin, errno());
            }
        }

        // dup stdout
        if let (Some(_), Some(w)) = (&pipes.stdout_r, &pipes.stdout_w) {
            if libc::dup2(w.raw(), 1) < 0 {
                report_child_setup_error(child_error_w, ChildSetupOp::DupStdout, errno());
            }
        }

        // dup stderr
        if let (Some(_), Some(w)) = (&pipes.stderr_r, &pipes.stderr_w) {
            if libc::dup2(w.raw(), 2) < 0 {
                report_child_setup_error(child_error_w, ChildSetupOp::DupStderr, errno());
            }
        }

        close_child_fds_for_policy(&opts.fd_policy, required_fds, child_error_w);

        // setsid
        if opts.pgroup.isolated && libc::setsid() < 0 {
            report_child_setup_error(child_error_w, ChildSetupOp::Setsid, errno());
        }

        // chdir
        if let Some(cwd) = ctx.cwd {
            if libc::chdir(cwd.as_ptr()) != 0 {
                report_child_setup_error(child_error_w, ChildSetupOp::Chdir, errno());
            }
        }

        // setpgid
        if let Some(pg) = opts.pgroup.leader {
            if libc::setpgid(0, pg) < 0 {
                report_child_setup_error(child_error_w, ChildSetupOp::Setpgid, errno());
            }
        }

        let envp_ptr = ctx.envp.as_ref().map_or_else(
            || environ as *const *mut c_char,
            |e: &Vec<*mut c_char>| e.as_ptr(),
        );

        // unblock signals and reset SIGPIPE
        if let Err(err) = SignalRuntime::unblock_all() {
            report_child_setup_error(
                child_error_w,
                ChildSetupOp::SignalMask,
                err.raw_os_error().unwrap_or(libc::EIO),
            );
        }
        if let Err(err) = SignalRuntime::reset_default(libc::SIGPIPE) {
            report_child_setup_error(
                child_error_w,
                ChildSetupOp::SignalMask,
                err.raw_os_error().unwrap_or(libc::EIO),
            );
        }

        // exec
        libc::execve(
            ctx.exe_ptr,
            ctx.argv.as_ptr() as *const *const _,
            envp_ptr as *const *const _,
        );
        report_child_setup_error(child_error_w, ChildSetupOp::Execve, errno());
    }
}

/// Parent-side post-spawn handshake shared by every exec-style backend: close
/// the write end, read the child setup error (empty ⇒ success), reap a failed
/// child, then build the stdio drain from the surviving pipe ends.
pub(super) fn reap_and_drain(
    pid: pid_t,
    mut pipes: Pipes,
    child_error_r: RawFd,
    child_error_w: RawFd,
    stdin: Option<Box<[u8]>>,
    max_output: usize,
    early_exit: Option<fn(&[u8]) -> bool>,
) -> Result<SpawnDrain, CoreError> {
    unsafe {
        libc::close(child_error_w);
    }
    match read_child_setup_error(child_error_r) {
        Ok(Some(err)) => {
            unsafe {
                libc::close(child_error_r);
                let mut status = 0;
                let _ = libc::waitpid(pid, &mut status, 0);
            }
            pipes.close_all();
            return Err(err);
        }
        Ok(None) => {}
        Err(err) => {
            unsafe {
                libc::close(child_error_r);
            }
            pipes.close_all();
            return Err(err);
        }
    }
    unsafe {
        libc::close(child_error_r);
    }
    drop(pipes.stdin_r.take());
    drop(pipes.stdout_w.take());
    drop(pipes.stderr_w.take());

    let drain = crate::io::DrainState::new(
        pipes.stdin_w.take().filter(|_| stdin.is_some()),
        stdin,
        pipes.stdout_r.take(),
        pipes.stderr_r.take(),
        max_output,
        early_exit,
    )?;

    Ok(drain)
}

pub(super) fn spawn_fork_internal(opts: SpawnOptions) -> Result<(Process, SpawnDrain), CoreError> {
    let ctx = prepare_child_context(&opts);
    let mut pipes = Pipes::new(
        opts.stdin.as_deref(),
        opts.capture_stdout,
        opts.capture_stderr,
    )?;

    let (child_error_r, child_error_w) = make_cloexec_pipe()?;
    let mut required_fds = collect_required_pipe_fds(&pipes);
    required_fds.push(child_error_w);

    let pid = unsafe { libc::fork() };

    if pid < 0 {
        unsafe {
            libc::close(child_error_r);
            libc::close(child_error_w);
        }
        pipes.close_all();
        syscall_ret(-1, "fork")?;
    }

    if pid == 0 {
        // Child
        // SAFETY: child-only setup; never returns.
        unsafe {
            child_entry(
                &pipes,
                &opts,
                &ctx,
                &required_fds,
                child_error_r,
                child_error_w,
            );
        }
    }

    let drain = reap_and_drain(
        pid,
        pipes,
        child_error_r,
        child_error_w,
        opts.stdin,
        opts.max_output,
        opts.early_exit,
    )?;

    Ok((Process::new(pid), drain))
}

pub(super) fn spawn_vfork_internal(opts: SpawnOptions) -> Result<(Process, SpawnDrain), CoreError> {
    let ctx = prepare_child_context(&opts);
    let mut pipes = Pipes::new(
        opts.stdin.as_deref(),
        opts.capture_stdout,
        opts.capture_stderr,
    )?;

    let (child_error_r, child_error_w) = make_cloexec_pipe()?;
    let mut required_fds = collect_required_pipe_fds(&pipes);
    required_fds.push(child_error_w);

    // `vfork(2)`: the child shares the parent's address space and the parent is
    // suspended until the child execs or `_exit`s. The `libc` wrapper is marked
    // deprecated because vfork is dangerous — not because it is broken — and we
    // rely on it exactly for the dangerous part it gets right: glibc/bionic
    // implement the arch-specific `clone(CLONE_VM|CLONE_VFORK|SIGCHLD)`
    // invocation (aarch64 has no `vfork` syscall and requires a valid stack).
    // Our child runs only async-signal-safe setup and never returns.
    #[allow(deprecated)]
    let pid = unsafe { libc::vfork() };

    if pid < 0 {
        unsafe {
            libc::close(child_error_r);
            libc::close(child_error_w);
        }
        pipes.close_all();
        syscall_ret(-1, "vfork")?;
    }

    if pid == 0 {
        // SAFETY: the vfork child shares the parent's address space, but
        // `child_entry` runs only async-signal-safe operations and never
        // returns, and the parent thread is suspended by the kernel until the
        // child execs or `_exit`s.
        unsafe {
            child_entry(
                &pipes,
                &opts,
                &ctx,
                &required_fds,
                child_error_r,
                child_error_w,
            );
        }
    }

    let drain = reap_and_drain(
        pid,
        pipes,
        child_error_r,
        child_error_w,
        opts.stdin,
        opts.max_output,
        opts.early_exit,
    )?;

    Ok((Process::new(pid), drain))
}