tapid-runner 0.0.6

Policy-aware package execution foundations for Tapid
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
#![cfg(windows)]

use crate::config::ExecutionLimits;
use crate::execution::{
    ExecutionError, ExecutionErrorCategory, FilesystemAccess, FilesystemGrantKind,
    ResolvedFilesystemGrant,
};
use std::ffi::c_void;
use std::mem::{size_of, zeroed};
use std::ptr::{null, null_mut};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::thread::JoinHandle;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use windows_sys::Win32::Foundation::{
    CloseHandle, GetLastError, HANDLE, HANDLE_FLAG_INHERIT, INVALID_HANDLE_VALUE,
    SetHandleInformation, WAIT_OBJECT_0, WAIT_TIMEOUT,
};
use windows_sys::Win32::Security::Isolation::{
    CreateAppContainerProfile, DeleteAppContainerProfile,
};
use windows_sys::Win32::Security::SECURITY_ATTRIBUTES;
use windows_sys::Win32::Security::{
    EqualSid, FreeSid, GetTokenInformation, IsValidSid, SECURITY_CAPABILITIES,
    TOKEN_APPCONTAINER_INFORMATION, TOKEN_QUERY, TokenAppContainerSid, TokenIsAppContainer,
};
use windows_sys::Win32::System::IO::{CreateIoCompletionPort, GetQueuedCompletionStatus};
use windows_sys::Win32::System::JobObjects::{
    AssignProcessToJobObject, CreateJobObjectW, IsProcessInJob, JOB_OBJECT_LIMIT_ACTIVE_PROCESS,
    JOB_OBJECT_LIMIT_JOB_MEMORY, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
    JOBOBJECT_ASSOCIATE_COMPLETION_PORT, JOBOBJECT_BASIC_ACCOUNTING_INFORMATION,
    JOBOBJECT_EXTENDED_LIMIT_INFORMATION, JobObjectAssociateCompletionPortInformation,
    JobObjectBasicAccountingInformation, JobObjectExtendedLimitInformation,
    QueryInformationJobObject, SetInformationJobObject, TerminateJobObject,
};
use windows_sys::Win32::System::Pipes::CreatePipe;
use windows_sys::Win32::System::SystemServices::JOB_OBJECT_MSG_ACTIVE_PROCESS_ZERO;
use windows_sys::Win32::System::Threading::{
    CREATE_SUSPENDED, CREATE_UNICODE_ENVIRONMENT, CreateProcessW, DeleteProcThreadAttributeList,
    EXTENDED_STARTUPINFO_PRESENT, GetExitCodeProcess, InitializeProcThreadAttributeList,
    OpenProcessToken, PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
    PROC_THREAD_ATTRIBUTE_SECURITY_CAPABILITIES, PROCESS_INFORMATION, ResumeThread,
    STARTF_USESTDHANDLES, STARTUPINFOEXW, TerminateProcess, UpdateProcThreadAttribute,
    WaitForSingleObject,
};

/// Owns a kernel Job Object configured before any child is assigned to it.
#[allow(dead_code)] // The Windows launch lifecycle will own this after suspended creation lands.
pub(super) struct WindowsJob {
    handle: HANDLE,
    completion_port: HANDLE,
    process_was_assigned: AtomicBool,
}

#[allow(dead_code)] // Used by the Windows launch lifecycle and the native configuration test.
impl WindowsJob {
    pub(super) fn new(
        limits: &ExecutionLimits,
        restrict_subprocesses: bool,
    ) -> Result<Self, ExecutionError> {
        // SAFETY: null attributes request a private unnamed object with default security.
        let handle = unsafe { CreateJobObjectW(null(), null()) };
        if handle == 0 {
            return Err(unsupported_job("create Job Object"));
        }
        let mut job = Self {
            handle,
            completion_port: 0,
            process_was_assigned: AtomicBool::new(false),
        };

        // SAFETY: INVALID_HANDLE_VALUE requests a new, private I/O completion port.
        job.completion_port = unsafe { CreateIoCompletionPort(INVALID_HANDLE_VALUE, 0, 0, 1) };
        if job.completion_port == 0 {
            return Err(unsupported_job("create Job Object completion port"));
        }

        // SAFETY: the structure is a plain Win32 POD output/input structure; zero is the documented
        // baseline for every limit field that is not explicitly enabled below.
        let mut information: JOBOBJECT_EXTENDED_LIMIT_INFORMATION = unsafe { zeroed() };
        let mut flags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
        let process_limit = match (limits.max_processes(), restrict_subprocesses) {
            (Some(limit), true) => Some(limit.min(1)),
            (Some(limit), false) => Some(limit),
            (None, true) => Some(1),
            (None, false) => None,
        };
        if let Some(limit) = process_limit {
            flags |= JOB_OBJECT_LIMIT_ACTIVE_PROCESS;
            information.BasicLimitInformation.ActiveProcessLimit = limit;
        }
        if let Some(limit) = limits.max_memory_bytes() {
            information.JobMemoryLimit = usize::try_from(limit).map_err(|_| {
                ExecutionError::new(
                    ExecutionErrorCategory::UnsupportedContainment,
                    "Windows Job Object cannot represent the requested job-wide memory limit",
                )
            })?;
            flags |= JOB_OBJECT_LIMIT_JOB_MEMORY;
        }
        information.BasicLimitInformation.LimitFlags = flags;
        let size = u32::try_from(size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>())
            .expect("Win32 Job Object information structure size fits u32");
        // SAFETY: `information` points to a fully initialized structure of the size supplied.
        let configured = unsafe {
            SetInformationJobObject(
                job.handle,
                JobObjectExtendedLimitInformation,
                (&information as *const JOBOBJECT_EXTENDED_LIMIT_INFORMATION).cast::<c_void>(),
                size,
            )
        };
        if configured == 0 {
            return Err(unsupported_job("configure Job Object limits"));
        }
        let association = JOBOBJECT_ASSOCIATE_COMPLETION_PORT {
            CompletionKey: job.handle as usize as *mut c_void,
            CompletionPort: job.completion_port,
        };
        let association_size = u32::try_from(size_of::<JOBOBJECT_ASSOCIATE_COMPLETION_PORT>())
            .expect("Job Object completion-port association size fits u32");
        // SAFETY: association contains a live completion-port handle and a stable per-job key.
        let associated = unsafe {
            SetInformationJobObject(
                job.handle,
                JobObjectAssociateCompletionPortInformation,
                (&association as *const JOBOBJECT_ASSOCIATE_COMPLETION_PORT).cast::<c_void>(),
                association_size,
            )
        };
        if associated == 0 {
            return Err(unsupported_job("associate Job Object completion port"));
        }
        Ok(job)
    }

    /// Assigns a child that the caller created suspended, then verifies membership before it may run.
    #[allow(dead_code)]
    pub(super) fn assign_suspended_process(&self, process: HANDLE) -> Result<(), ExecutionError> {
        if process == 0 {
            return Err(ExecutionError::new(
                ExecutionErrorCategory::UnsupportedContainment,
                "cannot assign an invalid process handle to the Windows Job Object",
            ));
        }
        // SAFETY: the caller must retain a valid process handle and keep the child suspended until
        // this call and the membership check complete.
        let assigned = unsafe { AssignProcessToJobObject(self.handle, process) };
        if assigned == 0 {
            return Err(unsupported_job("assign suspended child to Job Object"));
        }
        self.process_was_assigned.store(true, Ordering::Release);

        let mut in_job = 0;
        // SAFETY: both handles are valid for this call; `in_job` is a writable BOOL destination.
        let verified = unsafe { IsProcessInJob(process, self.handle, &mut in_job) };
        if verified == 0 {
            return Err(unsupported_job(
                "verify suspended child Job Object membership",
            ));
        }
        if in_job == 0 {
            return Err(ExecutionError::new(
                ExecutionErrorCategory::UnsupportedContainment,
                "Windows reported successful Job Object assignment but membership verification failed",
            ));
        }
        Ok(())
    }

    pub(super) fn terminate_all(&self) -> Result<(), ExecutionError> {
        // SAFETY: the owned Job Object handle remains valid for the duration of the call.
        if unsafe { TerminateJobObject(self.handle, 1) } == 0 {
            return Err(unsupported_job("terminate Windows Job Object members"));
        }
        Ok(())
    }

    pub(super) fn active_process_count(&self) -> Result<u32, ExecutionError> {
        // SAFETY: zeroed is a valid writable destination; the declared output length matches.
        let mut information: JOBOBJECT_BASIC_ACCOUNTING_INFORMATION = unsafe { zeroed() };
        let size = u32::try_from(size_of::<JOBOBJECT_BASIC_ACCOUNTING_INFORMATION>())
            .expect("Job Object accounting information size fits u32");
        // SAFETY: the Job Object handle and output buffer remain valid for the call.
        let queried = unsafe {
            QueryInformationJobObject(
                self.handle,
                JobObjectBasicAccountingInformation,
                (&mut information as *mut JOBOBJECT_BASIC_ACCOUNTING_INFORMATION).cast::<c_void>(),
                size,
                null_mut(),
            )
        };
        if queried == 0 {
            return Err(unsupported_job("query active Job Object process count"));
        }
        Ok(information.ActiveProcesses)
    }

    pub(super) fn wait_until_empty(&self, timeout_ms: u32) -> Result<(), ExecutionError> {
        if !self.process_was_assigned.load(Ordering::Acquire) {
            return Ok(());
        }
        if matches!(self.active_process_count(), Ok(0)) {
            return Ok(());
        }
        self.wait_for_active_process_zero_notification(timeout_ms)
    }

    fn wait_for_active_process_zero_notification(
        &self,
        timeout_ms: u32,
    ) -> Result<(), ExecutionError> {
        let started = Instant::now();
        loop {
            let remaining_ms = if timeout_ms == u32::MAX {
                u32::MAX
            } else {
                let elapsed_ms = u32::try_from(started.elapsed().as_millis()).unwrap_or(u32::MAX);
                if elapsed_ms >= timeout_ms {
                    return Err(ExecutionError::new(
                        ExecutionErrorCategory::Timeout,
                        "timed out waiting for Windows Job Object active-process-zero notification",
                    ));
                }
                timeout_ms - elapsed_ms
            };
            let mut bytes_transferred = 0u32;
            let mut completion_key = 0usize;
            let mut overlapped = null_mut();
            // SAFETY: the completion port is owned by self and each output is writable.
            let received = unsafe {
                GetQueuedCompletionStatus(
                    self.completion_port,
                    &mut bytes_transferred,
                    &mut completion_key,
                    &mut overlapped,
                    remaining_ms,
                )
            };
            if received == 0 {
                let error = unsafe { GetLastError() };
                if error == WAIT_TIMEOUT {
                    return Err(ExecutionError::new(
                        ExecutionErrorCategory::Timeout,
                        "timed out waiting for Windows Job Object active-process-zero notification",
                    ));
                }
                return Err(unsupported_job(
                    "receive Job Object completion notification",
                ));
            }
            if completion_key == self.handle as usize
                && bytes_transferred == JOB_OBJECT_MSG_ACTIVE_PROCESS_ZERO
                && overlapped.is_null()
            {
                return Ok(());
            }
        }
    }

    #[cfg(test)]
    fn query_extended_limits(
        &self,
    ) -> Result<JOBOBJECT_EXTENDED_LIMIT_INFORMATION, ExecutionError> {
        // SAFETY: zeroed is a valid writable destination and the API fills the declared structure.
        let mut information: JOBOBJECT_EXTENDED_LIMIT_INFORMATION = unsafe { zeroed() };
        let size = u32::try_from(size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>())
            .expect("Win32 Job Object information structure size fits u32");
        // SAFETY: the handle is owned by self and the output pointer/length match the structure.
        let queried = unsafe {
            QueryInformationJobObject(
                self.handle,
                JobObjectExtendedLimitInformation,
                (&mut information as *mut JOBOBJECT_EXTENDED_LIMIT_INFORMATION).cast::<c_void>(),
                size,
                null_mut(),
            )
        };
        if queried == 0 {
            return Err(unsupported_job("query configured Job Object limits"));
        }
        Ok(information)
    }
}

impl Drop for WindowsJob {
    fn drop(&mut self) {
        if self.handle != 0 {
            // SAFETY: this wrapper uniquely owns the Job Object handle.
            unsafe { CloseHandle(self.handle) };
        }
        if self.completion_port != 0 {
            // SAFETY: this wrapper uniquely owns the completion-port handle.
            unsafe { CloseHandle(self.completion_port) };
        }
    }
}

static NEXT_APPCONTAINER_ID: AtomicU64 = AtomicU64::new(1);

/// Owns a per-execution AppContainer profile and its allocated SID.
#[allow(dead_code)]
pub(super) struct WindowsAppContainer {
    name: Vec<u16>,
    sid: windows_sys::Win32::Foundation::PSID,
    deleted: bool,
}

#[allow(dead_code)]
impl WindowsAppContainer {
    pub(super) fn create() -> Result<Self, ExecutionError> {
        let nonce = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map_err(|_| {
                ExecutionError::new(
                    ExecutionErrorCategory::UnsupportedContainment,
                    "Windows AppContainer profile name could not be generated",
                )
            })?
            .as_nanos();
        let sequence = NEXT_APPCONTAINER_ID.fetch_add(1, Ordering::Relaxed);
        let profile = format!("td-{:x}-{nonce:x}-{sequence:x}", std::process::id());
        if profile.encode_utf16().count() > 64 {
            return Err(ExecutionError::new(
                ExecutionErrorCategory::UnsupportedContainment,
                "Windows AppContainer profile name exceeds the platform limit",
            ));
        }
        let name = profile
            .encode_utf16()
            .chain(std::iter::once(0))
            .collect::<Vec<_>>();
        let display = format!("Tapid {profile}")
            .encode_utf16()
            .chain(std::iter::once(0))
            .collect::<Vec<_>>();
        let description = "Ephemeral Tapid root-script execution"
            .encode_utf16()
            .chain(std::iter::once(0))
            .collect::<Vec<_>>();
        let mut sid = null_mut();
        // SAFETY: all strings are NUL-terminated; no capability SIDs are requested, so null/zero
        // are the documented capability list inputs. The returned SID is released with FreeSid.
        let result = unsafe {
            CreateAppContainerProfile(
                name.as_ptr(),
                display.as_ptr(),
                description.as_ptr(),
                null(),
                0,
                &mut sid,
            )
        };
        if result < 0 {
            if !sid.is_null() {
                // SAFETY: the API returned this allocation despite reporting failure.
                unsafe { FreeSid(sid) };
            }
            return Err(unsupported_hresult("create AppContainer profile", result));
        }
        if sid.is_null() || unsafe { IsValidSid(sid) } == 0 {
            if !sid.is_null() {
                // SAFETY: the profile API returned this allocation.
                unsafe { FreeSid(sid) };
            }
            // SAFETY: the name is valid and profile creation succeeded.
            unsafe { DeleteAppContainerProfile(name.as_ptr()) };
            return Err(ExecutionError::new(
                ExecutionErrorCategory::UnsupportedContainment,
                "Windows created an AppContainer profile without a valid SID",
            ));
        }
        Ok(Self {
            name,
            sid,
            deleted: false,
        })
    }

    pub(super) fn sid(&self) -> windows_sys::Win32::Foundation::PSID {
        self.sid
    }

    pub(super) fn profile_name(&self) -> &[u16] {
        &self.name
    }

    pub(super) fn cleanup(&mut self) -> Result<(), ExecutionError> {
        if !self.deleted {
            // SAFETY: profile name is the exact NUL-terminated name created by this value.
            let result = unsafe { DeleteAppContainerProfile(self.name.as_ptr()) };
            if result < 0 {
                return Err(unsupported_hresult("delete AppContainer profile", result));
            }
            self.deleted = true;
        }
        if !self.sid.is_null() {
            // SAFETY: CreateAppContainerProfile allocated this SID for this wrapper.
            unsafe { FreeSid(self.sid) };
            self.sid = null_mut();
        }
        Ok(())
    }
}

impl Drop for WindowsAppContainer {
    fn drop(&mut self) {
        if !self.deleted {
            // SAFETY: best-effort profile cleanup; explicit lifecycle cleanup reports errors.
            if unsafe { DeleteAppContainerProfile(self.name.as_ptr()) } >= 0 {
                self.deleted = true;
            }
        }
        if !self.sid.is_null() {
            // SAFETY: CreateAppContainerProfile allocated this SID for this wrapper.
            unsafe { FreeSid(self.sid) };
            self.sid = null_mut();
        }
    }
}

#[path = "windows_filesystem.rs"]
mod filesystem;
pub(super) use filesystem::WindowsFilesystemGrants;
#[cfg(test)]
pub(super) use filesystem::WindowsPathAcl;

#[path = "windows_process.rs"]
mod process;
pub(super) use process::{
    WindowsChildTermination, WindowsOutputCapture, WindowsStdioPipes, WindowsSuspendedChild,
};

fn unsupported_hresult(operation: &str, hresult: i32) -> ExecutionError {
    ExecutionError::new(
        ExecutionErrorCategory::UnsupportedContainment,
        format!(
            "Windows {operation} failed with HRESULT 0x{:08X}",
            hresult as u32
        ),
    )
}

fn unsupported_job(operation: &str) -> ExecutionError {
    ExecutionError::new(
        ExecutionErrorCategory::UnsupportedContainment,
        format!(
            "Windows {operation} failed: {}",
            std::io::Error::last_os_error()
        ),
    )
}

#[cfg(test)]
#[path = "windows_job_tests.rs"]
mod tests;