envseal 0.3.12

Write-only secret vault with process-level access control — post-agent secret management
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
//! Windows sandbox backend — Job Object based process containment.
//!
//! macOS and Linux apply isolation in the child's `pre_exec` closure (between
//! `fork` and `exec`). Windows has no `pre_exec`; instead the parent assigns
//! the child to a Job Object after the child is spawned, and the Job Object's
//! limits propagate to the child for the rest of its lifetime.
//!
//! # Tier mapping
//!
//! `None` is a no-op. `Hardened` sets `KILL_ON_JOB_CLOSE` (child dies if
//! the supervisor exits), `DIE_ON_UNHANDLED_EXCEPTION` (silent crashes
//! are killed), and leaves `BREAKAWAY_OK` clear so the child cannot spawn
//! descendants outside the job. `Lockdown` adds `ACTIVE_PROCESS = 1`
//! (the supervised child is the only process allowed in the job — any
//! attempt to spawn another inside the job is denied with
//! `ERROR_NOT_ENOUGH_QUOTA`) and all `JOB_OBJECT_UILIMIT_*` restrictions
//! so the child cannot read other processes' handles, manipulate the
//! global atom table, change desktop/display settings, or interact with
//! the windowing subsystem of other sessions.
//!
//! # Race window — closed via `CREATE_SUSPENDED` + `NtResumeProcess`
//!
//! `std::process::Command::spawn` calls `CreateProcessW` and returns a
//! handle to a process whose main thread is already running. Between
//! that point and our subsequent `AssignProcessToJobObject` call there
//! is a multi-millisecond window where the child runs unconstrained.
//! A child that `CreateProcessW`s a grandchild during that window
//! produces a grandchild that is **not** in the job, escaping
//! `ACTIVE_PROCESS_LIMIT` and `KILL_ON_JOB_CLOSE`.
//!
//! [`spawn_in_job`] eliminates the window. The flow is:
//!
//! 1. Caller-supplied `Command` is augmented with the `CREATE_SUSPENDED`
//!    creation flag via `std::os::windows::process::CommandExt`.
//!    `CreateProcessW` returns with the child created but its main
//!    thread suspended — not a single user instruction has run.
//! 2. The Job Object is created and configured.
//! 3. `AssignProcessToJobObject` slots the still-frozen child into the
//!    job. From this point onward, any `CreateProcessW` issued by the
//!    child (or its descendants) inherits the job assignment.
//! 4. `NtResumeProcess` (undocumented but stable Win32-since-XP API
//!    exported by `ntdll.dll`) resumes all threads of the child. The
//!    child's `main` runs for the first time, already inside the
//!    job. There is no instant where the child is alive and not
//!    constrained.
//!
//! The legacy [`apply_to_process`] post-spawn variant is kept as a
//! fallback for `tier == SandboxTier::None` callers and for
//! diagnostic test code.
//!
//! # Tracking
//!
//! The `OwnedJob` returned by [`apply_to_process`] is dropped by the
//! supervisor *after* it has finished `wait`-ing for the child. Dropping
//! the handle terminates any process still in the job (because of
//! `KILL_ON_JOB_CLOSE`) — a belt-and-suspenders against a child that
//! `Detach`-style escapes a `wait`.

#![cfg(target_os = "windows")]

use std::os::windows::io::{AsRawHandle, RawHandle};
use std::os::windows::process::CommandExt;
use std::process::{Child, Command};
use std::ptr;

use windows_sys::Win32::Foundation::{CloseHandle, GetLastError, ERROR_SUCCESS, FALSE, HANDLE};
use windows_sys::Win32::System::JobObjects::{
    AssignProcessToJobObject, CreateJobObjectW, JobObjectBasicLimitInformation,
    JobObjectBasicUIRestrictions, SetInformationJobObject, JOBOBJECT_BASIC_LIMIT_INFORMATION,
    JOBOBJECT_BASIC_UI_RESTRICTIONS, JOB_OBJECT_LIMIT_ACTIVE_PROCESS,
    JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE, JOB_OBJECT_UILIMIT_DESKTOP,
    JOB_OBJECT_UILIMIT_DISPLAYSETTINGS, JOB_OBJECT_UILIMIT_EXITWINDOWS,
    JOB_OBJECT_UILIMIT_GLOBALATOMS, JOB_OBJECT_UILIMIT_HANDLES, JOB_OBJECT_UILIMIT_READCLIPBOARD,
    JOB_OBJECT_UILIMIT_SYSTEMPARAMETERS, JOB_OBJECT_UILIMIT_WRITECLIPBOARD,
};
use windows_sys::Win32::System::Threading::CREATE_SUSPENDED;

use super::SandboxTier;

// `NtResumeProcess` — exported by `ntdll.dll`, present since Windows XP,
// not in the Win32 SDK so we declare it manually. Resumes every thread
// of `process_handle` in a single syscall. Returns NTSTATUS (0 ==
// `STATUS_SUCCESS`).
#[link(name = "ntdll")]
extern "system" {
    fn NtResumeProcess(process_handle: HANDLE) -> i32;
}

/// Owned Job Object handle. Closed on drop, which (because the job has
/// `JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE`) terminates any still-running
/// process inside it.
pub struct OwnedJob {
    handle: HANDLE,
}

impl OwnedJob {
    fn new() -> std::io::Result<Self> {
        let h = unsafe { CreateJobObjectW(ptr::null_mut(), ptr::null()) };
        if h.is_null() {
            return Err(last_os_error("CreateJobObjectW"));
        }
        Ok(Self { handle: h })
    }

    /// Terminate every process currently in the job, returning
    /// `exit_code` from `TerminateJobObject`. Used by supervised
    /// mode (audit C4) after the direct child exits to bring down
    /// any grandchildren still holding inherited stdout/stderr
    /// pipe write-ends.
    ///
    /// This is *additionally* covered by the
    /// `JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE` flag we set during
    /// [`apply_to_process`] — when this `OwnedJob` is dropped the
    /// kernel kills the job too. `kill_now` lets the caller force
    /// the kill *before* dropping the handle so reader threads
    /// observing the inherited pipes get EOF immediately.
    pub fn kill_now(&self, exit_code: u32) {
        if self.handle.is_null() {
            return;
        }
        unsafe {
            use windows_sys::Win32::System::JobObjects::TerminateJobObject;
            // SAFETY: `handle` is a non-null job-object handle obtained
            // from `CreateJobObjectW`. The handle is owned by `self`
            // and not closed until Drop; calling TerminateJobObject
            // before Drop is well-defined and idempotent.
            let _ = TerminateJobObject(self.handle, exit_code);
        }
    }
}

impl Drop for OwnedJob {
    fn drop(&mut self) {
        if !self.handle.is_null() {
            unsafe {
                CloseHandle(self.handle);
            }
        }
    }
}

/// Apply the requested Job Object limits to `child` and return the owned
/// Job handle.
///
/// The caller MUST keep the returned [`OwnedJob`] alive at least until the
/// child has been `wait`-ed on; dropping the job terminates any still-live
/// process inside it.
///
/// # Errors
///
/// Returns the underlying `io::Error` on failure of any of:
/// - `CreateJobObjectW`
/// - `SetInformationJobObject`
/// - `AssignProcessToJobObject`
pub fn apply_to_process(tier: SandboxTier, child: &Child) -> std::io::Result<Option<OwnedJob>> {
    if matches!(tier, SandboxTier::None) {
        return Ok(None);
    }

    let job = OwnedJob::new()?;
    set_basic_limits(job.handle, tier)?;
    if matches!(tier, SandboxTier::Lockdown) {
        set_ui_restrictions(job.handle)?;
    }

    let process_handle: RawHandle = child.as_raw_handle();
    let assigned = unsafe { AssignProcessToJobObject(job.handle, process_handle as HANDLE) };
    if assigned == FALSE {
        return Err(last_os_error("AssignProcessToJobObject"));
    }

    Ok(Some(job))
}

fn set_basic_limits(job: HANDLE, tier: SandboxTier) -> std::io::Result<()> {
    let mut limit_flags = 0u32;
    if !matches!(tier, SandboxTier::None) {
        limit_flags |= JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
    }
    if matches!(tier, SandboxTier::Lockdown) {
        limit_flags |= JOB_OBJECT_LIMIT_ACTIVE_PROCESS;
    }

    let mut basic: JOBOBJECT_BASIC_LIMIT_INFORMATION = unsafe { std::mem::zeroed() };
    basic.LimitFlags = limit_flags;
    if matches!(tier, SandboxTier::Lockdown) {
        basic.ActiveProcessLimit = 1;
    }

    // SetInformationJobObject for `JobObjectBasicLimitInformation` takes a
    // `JOBOBJECT_BASIC_LIMIT_INFORMATION`. For the extended variant we'd
    // pass `JOBOBJECT_EXTENDED_LIMIT_INFORMATION`. We use the basic form
    // because we don't currently set any extended-only fields.
    // SAFETY: `JOBOBJECT_BASIC_LIMIT_INFORMATION` is a fixed-size struct of
    // ~64 bytes; the cast to `u32` cannot truncate.
    #[allow(clippy::cast_possible_truncation)]
    let size = std::mem::size_of::<JOBOBJECT_BASIC_LIMIT_INFORMATION>() as u32;
    let rc = unsafe {
        SetInformationJobObject(
            job,
            JobObjectBasicLimitInformation,
            std::ptr::addr_of_mut!(basic).cast(),
            size,
        )
    };
    if rc == FALSE {
        let err = std::io::Error::last_os_error();
        // If the OS rejects KILL_ON_JOB_CLOSE (common when the current
        // process already lives inside a Job Object / Silo that disallows
        // nested jobs with that flag — Windows Sandbox, WSLg, some CI
        // runners), fall back to the remaining limits. The child still
        // gets ACTIVE_PROCESS and UI restrictions; we just lose the
        // "kill child when parent exits" belt-and-suspenders.
        if err.raw_os_error() == Some(87) && limit_flags & JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE != 0 {
            limit_flags &= !JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
            basic.LimitFlags = limit_flags;
            let rc2 = unsafe {
                SetInformationJobObject(
                    job,
                    JobObjectBasicLimitInformation,
                    std::ptr::addr_of_mut!(basic).cast(),
                    size,
                )
            };
            if rc2 == FALSE {
                return Err(last_os_error(
                    "SetInformationJobObject(BasicLimitInformation)",
                ));
            }
            return Ok(());
        }
        return Err(last_os_error(
            "SetInformationJobObject(BasicLimitInformation)",
        ));
    }
    Ok(())
}

fn set_ui_restrictions(job: HANDLE) -> std::io::Result<()> {
    let mut ui = JOBOBJECT_BASIC_UI_RESTRICTIONS {
        UIRestrictionsClass: JOB_OBJECT_UILIMIT_DESKTOP
            | JOB_OBJECT_UILIMIT_DISPLAYSETTINGS
            | JOB_OBJECT_UILIMIT_EXITWINDOWS
            | JOB_OBJECT_UILIMIT_GLOBALATOMS
            | JOB_OBJECT_UILIMIT_HANDLES
            | JOB_OBJECT_UILIMIT_READCLIPBOARD
            | JOB_OBJECT_UILIMIT_SYSTEMPARAMETERS
            | JOB_OBJECT_UILIMIT_WRITECLIPBOARD,
    };

    // SAFETY: `JOBOBJECT_BASIC_UI_RESTRICTIONS` is a 4-byte struct;
    // the cast to `u32` cannot truncate.
    #[allow(clippy::cast_possible_truncation)]
    let size = std::mem::size_of::<JOBOBJECT_BASIC_UI_RESTRICTIONS>() as u32;
    let rc = unsafe {
        SetInformationJobObject(
            job,
            JobObjectBasicUIRestrictions,
            std::ptr::addr_of_mut!(ui).cast(),
            size,
        )
    };
    if rc == FALSE {
        return Err(last_os_error(
            "SetInformationJobObject(BasicUIRestrictions)",
        ));
    }
    Ok(())
}

fn last_os_error(label: &str) -> std::io::Error {
    let err = unsafe { GetLastError() };
    if err == ERROR_SUCCESS {
        return std::io::Error::other(format!("{label} failed with no error code"));
    }
    let raw = i32::try_from(err).unwrap_or(i32::MAX);
    std::io::Error::from_raw_os_error(raw)
}

/// Whether the Windows sandbox primitive (`CreateJobObjectW`) is reachable
/// on this build. Always `true` on Windows. Used by [`super::OsCapabilities`]
/// for diagnostic reporting.
#[must_use]
pub fn available() -> bool {
    true
}

/// Spawn `cmd` directly into a Job Object, with no race window between
/// process creation and job assignment.
///
/// The implementation uses `CREATE_SUSPENDED` so the child's main thread
/// is created but never executes; we then `AssignProcessToJobObject` and
/// finally `NtResumeProcess`. From the child's perspective, the very
/// first instruction it runs already sees itself in the job — there is
/// no unconstrained interval.
///
/// For [`SandboxTier::None`] this falls back to a plain `cmd.spawn()`
/// since there is no job to bind to.
///
/// # Errors
///
/// - `cmd.spawn` errors propagate as `io::Error`.
/// - Failure of any of `CreateJobObjectW`, `SetInformationJobObject`,
///   `AssignProcessToJobObject`, or `NtResumeProcess` produces an
///   `io::Error` from `GetLastError` / NTSTATUS. On such failures the
///   child is terminated to avoid leaving an unconstrained process
///   behind.
pub fn spawn_in_job(
    cmd: &mut Command,
    tier: SandboxTier,
) -> std::io::Result<(Child, Option<OwnedJob>)> {
    if matches!(tier, SandboxTier::None) {
        let child = cmd.spawn()?;
        return Ok((child, None));
    }

    // Stamp CREATE_SUSPENDED on top of any flags the caller already set.
    // `CommandExt::creation_flags` overwrites any existing value, so we
    // don't have to read-modify-write.
    cmd.creation_flags(CREATE_SUSPENDED);

    let mut child = cmd.spawn()?;

    // From here on, any error must terminate the child — leaving a
    // suspended process around would be a resource leak; leaving a
    // running unconstrained one would be a security regression.
    let job = match prepare_job(tier) {
        Ok(j) => j,
        Err(e) => {
            terminate_and_release(&mut child);
            return Err(e);
        }
    };

    let process_handle = child.as_raw_handle() as HANDLE;
    let assigned = unsafe { AssignProcessToJobObject(job.handle, process_handle) };
    if assigned == FALSE {
        let err = last_os_error("AssignProcessToJobObject");
        terminate_and_release(&mut child);
        return Err(err);
    }

    // SAFETY: `process_handle` is valid (we hold `child` until after this
    // call) and `NtResumeProcess` only consumes it; ownership of the
    // handle remains with `child`.
    let status = unsafe { NtResumeProcess(process_handle) };
    if status < 0 {
        terminate_and_release(&mut child);
        return Err(std::io::Error::other(format!(
            "NtResumeProcess failed with NTSTATUS 0x{status:x}"
        )));
    }

    Ok((child, Some(job)))
}

/// Build the Job Object and its limits, ready to receive a process via
/// [`AssignProcessToJobObject`].
fn prepare_job(tier: SandboxTier) -> std::io::Result<OwnedJob> {
    let job = OwnedJob::new()?;
    set_basic_limits(job.handle, tier)?;
    if matches!(tier, SandboxTier::Lockdown) {
        set_ui_restrictions(job.handle)?;
    }
    Ok(job)
}

/// Last-resort cleanup when the spawn-into-job sequence aborts midway:
/// kill the still-suspended (or barely-running) child so it cannot
/// continue without our containment. Best-effort; both `kill` and
/// `wait` failures are ignored because we are already on an error
/// path and the caller will propagate the original error.
fn terminate_and_release(child: &mut Child) {
    let _ = child.kill();
    let _ = child.wait();
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn spawn_none_no_job_created() {
        let mut cmd = Command::new("cmd");
        cmd.args(["/c", "exit", "0"]);
        let (mut child, job) = spawn_in_job(&mut cmd, SandboxTier::None).expect("spawn None");
        assert!(job.is_none(), "None tier must not create a job");
        let status = child.wait().expect("wait for child");
        assert!(status.success());
    }

    #[test]
    fn spawn_hardened_creates_job_and_child_exits() {
        let mut cmd = Command::new("cmd");
        cmd.args(["/c", "exit", "0"]);
        let (mut child, job) =
            spawn_in_job(&mut cmd, SandboxTier::Hardened).expect("spawn Hardened");
        assert!(job.is_some(), "Hardened tier must create a job");
        let status = child.wait().expect("wait for child");
        assert!(status.success());
        // Dropping the job here (end of scope) exercises the OwnedJob Drop impl.
    }

    #[test]
    fn spawn_lockdown_creates_job_and_child_exits() {
        let mut cmd = Command::new("cmd");
        cmd.args(["/c", "exit", "0"]);
        let (mut child, job) =
            spawn_in_job(&mut cmd, SandboxTier::Lockdown).expect("spawn Lockdown");
        assert!(job.is_some(), "Lockdown tier must create a job");
        let status = child.wait().expect("wait for child");
        assert!(status.success());
    }

    #[test]
    fn apply_to_process_none_returns_none() {
        let mut cmd = Command::new("cmd");
        cmd.args(["/c", "exit", "0"]);
        let mut child = cmd.spawn().expect("spawn child");
        let job = apply_to_process(SandboxTier::None, &child).expect("apply None");
        assert!(job.is_none());
        let _ = child.wait();
    }

    #[test]
    fn apply_to_process_hardened_returns_job() {
        let mut cmd = Command::new("cmd");
        cmd.args(["/c", "exit", "0"]);
        let mut child = cmd.spawn().expect("spawn child");
        let job = apply_to_process(SandboxTier::Hardened, &child).expect("apply Hardened");
        assert!(job.is_some());
        let _ = child.wait();
    }

    #[test]
    fn apply_to_process_lockdown_returns_job() {
        let mut cmd = Command::new("cmd");
        cmd.args(["/c", "exit", "0"]);
        let mut child = cmd.spawn().expect("spawn child");
        let job = apply_to_process(SandboxTier::Lockdown, &child).expect("apply Lockdown");
        assert!(job.is_some());
        let _ = child.wait();
    }

    #[test]
    fn spawn_in_job_nonexistent_binary_fails() {
        let mut cmd = Command::new("this_binary_does_not_exist_99999.exe");
        let result = spawn_in_job(&mut cmd, SandboxTier::Hardened);
        assert!(result.is_err(), "spawning nonexistent binary must fail");
    }
}