workpen 0.7.6

Workpen dest-deny and a per-child process jail (Landlock, Seatbelt, Windows).
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
//! Unique helper PE plus AppContainer plus package-scoped WFP.
//!
//! Not a dest-parent-copy. Userspace WFP has no process-id condition, so
//! a path-wide `cmd.exe` filter is out of scope. The helper is a unique
//! PE; the AppContainer SID is unique per spawn; descendants inherit the
//! package. WFP BLOCKs that package SID (and the helper APP_ID) only
//! when the token can add filters. `ERROR_ACCESS_DENIED` (win32 5) is
//! skipped: package WFP needs an elevated token. AppContainer with no
//! network capabilities still applies.

use std::ffi::OsStr;
use std::fs;
use std::mem;
use std::path::{Path, PathBuf};
use std::ptr;
use std::time::{SystemTime, UNIX_EPOCH};

use super::super::wfp_skip_access_denied;
use super::{Bool, Dword, Handle, KernelError, last_error, wide_os, wide_path, win32_error};

const HELPER_PE: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/workpen-net-helper.exe"));

const RPC_C_AUTHN_WINNT: u32 = 10;
const FWPM_SESSION_FLAG_DYNAMIC: u32 = 0x0000_0001;
const FWP_UINT8: u32 = 1;
const FWP_BYTE_BLOB_TYPE: u32 = 12;
const FWP_SID: u32 = 13;
const FWP_MATCH_EQUAL: u32 = 0;
const FWP_ACTION_FLAG_TERMINATING: u32 = 0x0000_1000;
const FWP_ACTION_BLOCK: u32 = 0x0000_0001 | FWP_ACTION_FLAG_TERMINATING;

#[repr(C)]
#[derive(Clone, Copy)]
struct Guid {
    data1: u32,
    data2: u16,
    data3: u16,
    data4: [u8; 8],
}

const fn guid(data1: u32, data2: u16, data3: u16, data4: [u8; 8]) -> Guid {
    Guid {
        data1,
        data2,
        data3,
        data4,
    }
}

const FWPM_LAYER_ALE_AUTH_CONNECT_V4: Guid = guid(
    0xc38d57d1,
    0x05a7,
    0x4c33,
    [0x90, 0x4f, 0x7f, 0xbc, 0xee, 0xe6, 0x0e, 0x82],
);
const FWPM_LAYER_ALE_AUTH_CONNECT_V6: Guid = guid(
    0x4a72393b,
    0x319f,
    0x44bc,
    [0x84, 0xc3, 0xba, 0x54, 0xdc, 0xb3, 0xb6, 0xb4],
);
const FWPM_CONDITION_ALE_APP_ID: Guid = guid(
    0xd78e1e87,
    0x8644,
    0x4ea5,
    [0x94, 0x37, 0xd8, 0x09, 0xec, 0xef, 0xc9, 0x71],
);
const FWPM_CONDITION_ALE_PACKAGE_ID: Guid = guid(
    0x71bc78fa,
    0xf17c,
    0x4997,
    [0xa6, 0x02, 0x6a, 0xbb, 0x26, 0x1f, 0x35, 0x1c],
);

#[repr(C)]
struct SecurityCapabilities {
    app_container_sid: Handle,
    capabilities: *mut SidAndAttributes,
    capability_count: Dword,
    reserved: Dword,
}

#[repr(C)]
struct SidAndAttributes {
    sid: Handle,
    attributes: Dword,
}

#[repr(C)]
struct FwpmDisplayData0 {
    name: *mut u16,
    description: *mut u16,
}

#[repr(C)]
struct FwpmSession0 {
    session_key: Guid,
    display_data: FwpmDisplayData0,
    flags: u32,
    txn_wait_timeout_in_msec: u32,
    process_id: Dword,
    sid: Handle,
    username: *mut u16,
    kernel_mode: Bool,
}

#[repr(C)]
struct FwpByteBlob {
    size: u32,
    data: *mut u8,
}

#[repr(C)]
struct FwpValue0 {
    data_type: u32,
    value: usize,
}

#[repr(C)]
struct FwpmAction0 {
    action_type: u32,
    filter_type: Guid,
}

#[repr(C)]
struct FwpmFilterCondition0 {
    field_key: Guid,
    match_type: u32,
    condition_value: FwpValue0,
}

#[repr(C)]
struct FwpmFilter0 {
    filter_key: Guid,
    display_data: FwpmDisplayData0,
    flags: u32,
    provider_key: *mut Guid,
    provider_data: FwpByteBlob,
    layer_key: Guid,
    sub_layer_key: Guid,
    weight: FwpValue0,
    num_filter_conditions: u32,
    filter_condition: *mut FwpmFilterCondition0,
    action: FwpmAction0,
    raw_context: u64,
    reserved: *mut Guid,
    filter_id: u64,
    effective_weight: FwpValue0,
}

type CreateAppContainerTokenFn =
    unsafe extern "system" fn(Handle, *const SecurityCapabilities, *mut Handle) -> Bool;

#[link(name = "userenv")]
unsafe extern "system" {
    fn CreateAppContainerProfile(
        psz_app_container_name: *const u16,
        psz_display_name: *const u16,
        psz_description: *const u16,
        p_capabilities: *const SidAndAttributes,
        dw_capability_count: Dword,
        pp_sid_app_container_sid: *mut Handle,
    ) -> i32;
    fn DeriveAppContainerSidFromAppContainerName(
        psz_app_container_name: *const u16,
        ppsid_app_container_sid: *mut Handle,
    ) -> i32;
    fn DeleteAppContainerProfile(psz_app_container_name: *const u16) -> i32;
}

#[link(name = "fwpuclnt")]
unsafe extern "system" {
    fn FwpmEngineOpen0(
        server_name: *const u16,
        authn_service: u32,
        auth_identity: *mut core::ffi::c_void,
        session: *const FwpmSession0,
        engine_handle: *mut Handle,
    ) -> u32;
    fn FwpmEngineClose0(engine_handle: Handle) -> u32;
    fn FwpmFilterAdd0(
        engine_handle: Handle,
        filter: *const FwpmFilter0,
        sd: *mut core::ffi::c_void,
        id: *mut u64,
    ) -> u32;
    fn FwpmGetAppIdFromFileName0(file_name: *const u16, app_id: *mut *mut FwpByteBlob) -> u32;
    fn FwpmFreeMemory0(p: *mut *mut core::ffi::c_void);
}

pub(super) struct AppContainerProfile {
    name: Vec<u16>,
    sid: Handle,
}

impl AppContainerProfile {
    pub(super) fn create() -> Result<Self, KernelError> {
        let suffix = unique_suffix();
        let raw = format!("wpnh.{suffix}");
        let name = wide_os(OsStr::new(&raw));
        let display = wide_os(OsStr::new(&raw));
        let desc = wide_os(OsStr::new("workpen"));
        let mut sid = ptr::null_mut();
        // SAFETY: name/display/desc are NUL-terminated; no capabilities.
        let hr = unsafe {
            CreateAppContainerProfile(
                name.as_ptr(),
                display.as_ptr(),
                desc.as_ptr(),
                ptr::null(),
                0,
                &mut sid,
            )
        };
        if hr != 0 || sid.is_null() {
            sid = ptr::null_mut();
            // SAFETY: leftover profile from a crashed spawn; name is NUL-terminated.
            let derived =
                unsafe { DeriveAppContainerSidFromAppContainerName(name.as_ptr(), &mut sid) };
            if derived != 0 || sid.is_null() {
                return Err(hresult_error("CreateAppContainerProfile", hr));
            }
        }
        Ok(Self { name, sid })
    }

    pub(super) fn sid(&self) -> Handle {
        self.sid
    }
}

impl Drop for AppContainerProfile {
    fn drop(&mut self) {
        if !self.sid.is_null() {
            // SAFETY: sid came from CreateAppContainerProfile or Derive.
            unsafe {
                super::free_sid(self.sid);
            }
            self.sid = ptr::null_mut();
        }
        if !self.name.is_empty() {
            // SAFETY: name is the profile we created or reused.
            unsafe {
                DeleteAppContainerProfile(self.name.as_ptr());
            }
        }
    }
}

pub(super) struct HelperFile {
    path: PathBuf,
}

impl HelperFile {
    pub(super) fn install(dir: &Path) -> Result<Self, KernelError> {
        let path = dir.join(format!(".wpnh-{}.exe", unique_suffix()));
        fs::write(&path, HELPER_PE)
            .map_err(|e| KernelError::Apply(format!("write net helper {}: {e}", path.display())))?;
        Ok(Self { path })
    }

    pub(super) fn path(&self) -> &Path {
        &self.path
    }
}

impl Drop for HelperFile {
    fn drop(&mut self) {
        let _ = fs::remove_file(&self.path);
    }
}

pub(super) struct WfpSession {
    engine: Handle,
}

impl WfpSession {
    /// Open a dynamic WFP session and add package plus helper APP_ID blocks.
    ///
    /// Returns `Ok(None)` when engine open or filter add is
    /// `ERROR_ACCESS_DENIED` (needs admin). Other WFP errors stay
    /// [`KernelError::Apply`].
    pub(super) fn apply(package_sid: Handle, helper: &Path) -> Result<Option<Self>, KernelError> {
        let mut name = wide_os(OsStr::new("workpen-net"));
        let mut session: FwpmSession0 = unsafe { mem::zeroed() };
        session.flags = FWPM_SESSION_FLAG_DYNAMIC;
        session.display_data.name = name.as_mut_ptr();
        let mut engine = ptr::null_mut();
        // SAFETY: local engine; session lives for the call.
        let err = unsafe {
            FwpmEngineOpen0(
                ptr::null(),
                RPC_C_AUTHN_WINNT,
                ptr::null_mut(),
                &session,
                &mut engine,
            )
        };
        if err != 0 || engine.is_null() {
            if wfp_skip_access_denied(err) {
                return Ok(None);
            }
            return Err(win32_error("FwpmEngineOpen0", err));
        }
        let wfp = Self { engine };
        match add_sid_blocks(engine, package_sid, &mut name) {
            Ok(()) => {}
            Err(WfpAddError::AccessDenied) => return Ok(None),
            Err(WfpAddError::Other(err)) => return Err(err),
        }
        match add_app_id_blocks(engine, helper, &mut name) {
            Ok(()) => {}
            Err(WfpAddError::AccessDenied) => return Ok(None),
            Err(WfpAddError::Other(err)) => return Err(err),
        }
        Ok(Some(wfp))
    }
}

impl Drop for WfpSession {
    fn drop(&mut self) {
        if !self.engine.is_null() {
            // SAFETY: engine from FwpmEngineOpen0; dynamic filters die with it.
            unsafe {
                FwpmEngineClose0(self.engine);
            }
            self.engine = ptr::null_mut();
        }
    }
}

pub(super) fn create_appcontainer_token(
    base: Handle,
    package_sid: Handle,
) -> Result<Handle, KernelError> {
    let create = load_create_appcontainer_token()?;
    let caps = SecurityCapabilities {
        app_container_sid: package_sid,
        capabilities: ptr::null_mut(),
        capability_count: 0,
        reserved: 0,
    };
    let mut out = ptr::null_mut();
    // SAFETY: base is a primary token we own; caps.sid lives for the call.
    let ok = unsafe { create(base, &caps, &mut out) };
    if ok == 0 || out.is_null() {
        return Err(last_error("CreateAppContainerToken"));
    }
    Ok(out)
}

fn load_create_appcontainer_token() -> Result<CreateAppContainerTokenFn, KernelError> {
    let module = wide_os(OsStr::new("kernelbase.dll"));
    // SAFETY: module is NUL-terminated.
    let handle = unsafe { super::GetModuleHandleW(module.as_ptr()) };
    if handle.is_null() {
        return Err(last_error("GetModuleHandleW kernelbase.dll"));
    }
    // SAFETY: handle is kernelbase; name is a static C string.
    let proc = unsafe { super::GetProcAddress(handle, c"CreateAppContainerToken".as_ptr().cast()) };
    if proc.is_null() {
        return Err(KernelError::Apply(
            "CreateAppContainerToken is not available".into(),
        ));
    }
    // SAFETY: documented kernelbase export; system calling convention.
    Ok(unsafe { mem::transmute::<_, CreateAppContainerTokenFn>(proc) })
}

enum WfpAddError {
    AccessDenied,
    Other(KernelError),
}

fn wfp_add_status(op: &str, err: u32) -> Result<(), WfpAddError> {
    if err == 0 {
        return Ok(());
    }
    if wfp_skip_access_denied(err) {
        return Err(WfpAddError::AccessDenied);
    }
    Err(WfpAddError::Other(win32_error(op, err)))
}

fn add_sid_blocks(
    engine: Handle,
    package_sid: Handle,
    name: &mut [u16],
) -> Result<(), WfpAddError> {
    for layer in [
        FWPM_LAYER_ALE_AUTH_CONNECT_V4,
        FWPM_LAYER_ALE_AUTH_CONNECT_V6,
    ] {
        let mut cond: FwpmFilterCondition0 = unsafe { mem::zeroed() };
        cond.field_key = FWPM_CONDITION_ALE_PACKAGE_ID;
        cond.match_type = FWP_MATCH_EQUAL;
        cond.condition_value.data_type = FWP_SID;
        cond.condition_value.value = package_sid as usize;
        add_block_filter(engine, layer, &mut cond, name)?;
    }
    Ok(())
}

fn add_app_id_blocks(engine: Handle, helper: &Path, name: &mut [u16]) -> Result<(), WfpAddError> {
    let wide = wide_path(helper);
    let mut blob: *mut FwpByteBlob = ptr::null_mut();
    // SAFETY: wide is a NUL-terminated existing helper path.
    let err = unsafe { FwpmGetAppIdFromFileName0(wide.as_ptr(), &mut blob) };
    if err != 0 || blob.is_null() {
        if wfp_skip_access_denied(err) {
            return Err(WfpAddError::AccessDenied);
        }
        if err == 0 {
            return Err(WfpAddError::Other(KernelError::Apply(
                "FwpmGetAppIdFromFileName0 returned a null blob".into(),
            )));
        }
        return Err(WfpAddError::Other(win32_error(
            "FwpmGetAppIdFromFileName0",
            err,
        )));
    }
    let result = (|| {
        for layer in [
            FWPM_LAYER_ALE_AUTH_CONNECT_V4,
            FWPM_LAYER_ALE_AUTH_CONNECT_V6,
        ] {
            let mut cond: FwpmFilterCondition0 = unsafe { mem::zeroed() };
            cond.field_key = FWPM_CONDITION_ALE_APP_ID;
            cond.match_type = FWP_MATCH_EQUAL;
            cond.condition_value.data_type = FWP_BYTE_BLOB_TYPE;
            cond.condition_value.value = blob as usize;
            add_block_filter(engine, layer, &mut cond, name)?;
        }
        Ok(())
    })();
    // SAFETY: blob came from FwpmGetAppIdFromFileName0.
    unsafe {
        let mut p = blob.cast::<core::ffi::c_void>();
        FwpmFreeMemory0(&mut p);
    }
    result
}

fn add_block_filter(
    engine: Handle,
    layer: Guid,
    cond: &mut FwpmFilterCondition0,
    name: &mut [u16],
) -> Result<(), WfpAddError> {
    let mut filter: FwpmFilter0 = unsafe { mem::zeroed() };
    filter.display_data.name = name.as_mut_ptr();
    filter.layer_key = layer;
    filter.num_filter_conditions = 1;
    filter.filter_condition = cond;
    filter.action.action_type = FWP_ACTION_BLOCK;
    filter.weight.data_type = FWP_UINT8;
    filter.weight.value = 15;
    let mut id = 0u64;
    // SAFETY: engine is open; filter/cond live for the call.
    let err = unsafe { FwpmFilterAdd0(engine, &filter, ptr::null_mut(), &mut id) };
    wfp_add_status("FwpmFilterAdd0", err)
}

fn unique_suffix() -> String {
    let nanos = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_nanos())
        .unwrap_or(0);
    format!("{}.{}", std::process::id(), nanos)
}

fn hresult_error(op: &str, hr: i32) -> KernelError {
    KernelError::Apply(format!("{op} failed (hr {hr:#x})"))
}