win-custody 0.1.6

Take custody of Windows child processes: exact handle inheritance, kill-on-close jobs, launches into another session's token, SDDL-secured pipes, and opt-in AppContainer confinement.
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
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
//! AppContainer profiles and the process-creation capability attribute.
#![allow(unsafe_code)]

use std::ffi::OsString;
use std::io;
use std::mem::{offset_of, size_of};
use std::os::windows::ffi::OsStringExt;
use std::path::Path;
use std::ptr;

use windows_sys::Win32::Foundation::{LocalFree, GENERIC_EXECUTE, GENERIC_READ, GENERIC_WRITE};
use windows_sys::Win32::Globalization::lstrlenW;
use windows_sys::Win32::Security::Authorization::{
    ConvertSidToStringSidW, GetNamedSecurityInfoW, SetEntriesInAclW, SetNamedSecurityInfoW,
    EXPLICIT_ACCESS_W, SET_ACCESS, SE_FILE_OBJECT, TRUSTEE_IS_GROUP, TRUSTEE_IS_SID, TRUSTEE_W,
};
use windows_sys::Win32::Security::Isolation::{
    CreateAppContainerProfile, DeleteAppContainerProfile, DeriveAppContainerSidFromAppContainerName,
};
use windows_sys::Win32::Security::{
    AclSizeInformation, CreateWellKnownSid, DeriveCapabilitySidsFromName, EqualSid, FreeSid,
    GetAce, GetAclInformation, GetLengthSid, IsValidSid, MapGenericMask, WinBuiltinAnyPackageSid,
    ACCESS_ALLOWED_ACE, ACL, ACL_SIZE_INFORMATION, CONTAINER_INHERIT_ACE,
    DACL_SECURITY_INFORMATION, GENERIC_MAPPING, INHERIT_ONLY_ACE, OBJECT_INHERIT_ACE, PSID,
    SECURITY_CAPABILITIES, SID_AND_ATTRIBUTES,
};
use windows_sys::Win32::Storage::FileSystem::{
    DELETE, FILE_ALL_ACCESS, FILE_GENERIC_EXECUTE, FILE_GENERIC_READ, FILE_GENERIC_WRITE,
};
use windows_sys::Win32::System::SystemServices::{
    ACCESS_ALLOWED_ACE_TYPE, ACCESS_DENIED_ACE_TYPE, SE_GROUP_ENABLED,
};

use crate::wide::wide_null;

const PROFILE_ALREADY_EXISTS: u32 = 0x8007_00b7;

/// A named AppContainer profile and the capabilities assigned to its child
/// processes. Profile data persists in Windows after this value is dropped.
///
/// A process launched in the profile still has everything Windows grants to
/// ALL APPLICATION PACKAGES (`S-1-15-2-1`): read and execute access to the
/// Windows and Program Files directories, and to every registry key that
/// grants that SID access. This is a plain AppContainer, not a Less
/// Privileged AppContainer (LPAC).
pub struct AppContainerProfile {
    sid: AppContainerSid,
    _capabilities: Vec<DerivedCapability>,
    capability_attributes: Vec<SID_AND_ATTRIBUTES>,
    name: Vec<u16>,
    created: bool,
}

// SAFETY: the profile owns every SID and SID pointer array reachable through
// its fields. They are written once during construction and only read after
// construction, with no interior mutability, and the Windows readers have no
// thread affinity, so ownership may move between threads.
unsafe impl Send for AppContainerProfile {}
// SAFETY: every owned SID and SID pointer array is immutable after
// construction, there is no interior mutability, and Windows only reads these
// allocations through APIs with no thread affinity, so shared access is safe.
unsafe impl Sync for AppContainerProfile {}

impl AppContainerProfile {
    /// Creates or opens a named AppContainer profile with no capabilities.
    ///
    /// With no capabilities, the profile receives no optional network or
    /// device access. The name must be unique to the application and at most
    /// 64 UTF-16 code units, as required by Windows. Use
    /// [`was_created`](Self::was_created) to distinguish a newly created
    /// profile from an existing one.
    pub fn create_or_open(name: &str, display_name: &str, description: &str) -> io::Result<Self> {
        Self::create_or_open_with_capabilities(name, display_name, description, &[])
    }

    /// Creates or opens a named AppContainer profile and grants the named
    /// Windows capabilities to processes launched in it.
    ///
    /// Windows does not validate capability names:
    /// `DeriveCapabilitySidsFromName` turns any non-empty string into a SID,
    /// so a misspelled name succeeds and the child runs without the
    /// capability that was meant. Use the names Microsoft documents, such as
    /// `internetClient`. An empty name is rejected.
    pub fn create_or_open_with_capabilities(
        name: &str,
        display_name: &str,
        description: &str,
        capabilities: &[&str],
    ) -> io::Result<Self> {
        let name_w = wide_null(name)?;
        if name_w.len() > 65 || name.is_empty() {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "AppContainer profile names must be 1 to 64 UTF-16 code units",
            ));
        }
        let display_w = wide_null(display_name)?;
        let description_w = wide_null(description)?;
        let mut derivations = Vec::with_capacity(capabilities.len());
        for capability in capabilities {
            derivations.push(DerivedCapability::from_name(capability)?);
        }
        let mut capability_attributes = Vec::new();
        for derivation in &derivations {
            capability_attributes.extend(derivation.capability_sids.iter().map(|sid| {
                SID_AND_ATTRIBUTES {
                    Sid: *sid,
                    Attributes: SE_GROUP_ENABLED as u32,
                }
            }));
        }

        let mut sid = ptr::null_mut();
        // SAFETY: all UTF-16 strings and capability attributes remain live
        // across the call; `sid` is a local out pointer. Windows returns the
        // profile SID allocation owned by `AppContainerSid`.
        let result = unsafe {
            CreateAppContainerProfile(
                name_w.as_ptr(),
                display_w.as_ptr(),
                description_w.as_ptr(),
                if capability_attributes.is_empty() {
                    ptr::null()
                } else {
                    capability_attributes.as_ptr()
                },
                capability_attributes.len() as u32,
                &mut sid,
            )
        };
        let created = if result as u32 == PROFILE_ALREADY_EXISTS {
            // SAFETY: the profile name is valid and NUL-terminated; `sid` is
            // a local out pointer whose allocation is freed with FreeSid.
            let derived =
                unsafe { DeriveAppContainerSidFromAppContainerName(name_w.as_ptr(), &mut sid) };
            if derived < 0 {
                return Err(hresult_error(derived));
            }
            false
        } else if result < 0 {
            return Err(hresult_error(result));
        } else {
            true
        };
        if sid.is_null() {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "Windows returned a null AppContainer SID",
            ));
        }
        Ok(Self {
            sid: AppContainerSid(sid),
            _capabilities: derivations,
            capability_attributes,
            name: name_w,
            created,
        })
    }

    /// Whether this call created the profile.
    ///
    /// `false` means a profile with this name already existed and was opened.
    /// An existing profile may belong to another program or to an earlier
    /// version of yours, and it keeps every access rule ever granted to its SID.
    pub fn was_created(&self) -> bool {
        self.created
    }

    /// Deletes the profile from Windows: its registry data and its folder
    /// under `%LOCALAPPDATA%\Packages`.
    ///
    /// Access granted with [`grant_path`](Self::grant_path) is not removed,
    /// because those rules live on the files themselves and name the
    /// profile's SID. A process already running in the container keeps
    /// running.
    pub fn delete(self) -> io::Result<()> {
        // SAFETY: `self.name` is the NUL-terminated profile name retained from
        // construction and remains live through the call.
        let result = unsafe { DeleteAppContainerProfile(self.name.as_ptr()) };
        if result < 0 {
            return Err(hresult_error(result));
        }
        Ok(())
    }

    /// The profile's SID in standard string form, for security descriptors on
    /// files, directories, and named pipes.
    ///
    /// A named-pipe descriptor must also allow the user and carry the low
    /// mandatory label `S:(ML;;NW;;;LW)`, because an AppContainer runs at low
    /// integrity.
    pub fn sid_string(&self) -> io::Result<String> {
        let mut string = ptr::null_mut();
        // SAFETY: `self.sid` is a live SID and `string` is a local out
        // pointer. The returned string allocation is freed below.
        if unsafe { ConvertSidToStringSidW(self.sid.0, &mut string) } == 0 || string.is_null() {
            return Err(io::Error::last_os_error());
        }
        // SAFETY: ConvertSidToStringSidW returns a readable NUL-terminated
        // string that remains live until the matching LocalFree below.
        let length = unsafe { lstrlenW(string) };
        if length < 0 {
            // SAFETY: the allocation came from ConvertSidToStringSidW.
            unsafe { LocalFree(string.cast()) };
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "Windows returned an invalid SID string",
            ));
        }
        // SAFETY: `length` was measured through the terminating NUL.
        let value =
            unsafe { OsString::from_wide(std::slice::from_raw_parts(string, length as usize)) };
        // SAFETY: the allocation came from ConvertSidToStringSidW.
        unsafe { LocalFree(string.cast()) };
        value
            .into_string()
            .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "SID string was not Unicode"))
    }

    /// Adds an inheritable access rule for this profile to an existing file or
    /// directory DACL without replacing its other access rules.
    ///
    /// Windows propagates inheritable rules to existing descendants when the
    /// DACL is set, so on a directory this rewrites the ACL of every file and
    /// folder under it, which can take a while on a large tree. Files created
    /// later inherit the rule too.
    ///
    /// The grant is persistent: it stays after this value is dropped, after
    /// the launched processes exit and after the profile is deleted, and this
    /// crate has no call to remove it. [`AppContainerAccess::ReadWrite`] and
    /// [`AppContainerAccess::ReadWriteExecute`] also grant delete access, so a
    /// child can replace files inside a writable directory.
    pub fn grant_path(&self, path: impl AsRef<Path>, access: AppContainerAccess) -> io::Result<()> {
        grant_sid_access(path.as_ref(), self.sid.0, access)
    }

    /// Gives processes in this profile `access` to `path` unless they already
    /// have it, and returns whether it wrote an access rule.
    ///
    /// Access already granted to this profile's SID or to ALL APPLICATION
    /// PACKAGES counts. When all requested rights are present, this does not
    /// write, so it works on directories the caller cannot change, such as
    /// Program Files, and does not rewrite a previously granted tree. A rule
    /// written here is the same persistent rule that [`grant_path`](Self::grant_path)
    /// writes.
    pub fn ensure_path_access(
        &self,
        path: impl AsRef<Path>,
        access: AppContainerAccess,
    ) -> io::Result<bool> {
        let path = path.as_ref();
        let dacl = path_dacl(path)?;
        let Some(dacl) = dacl.dacl else {
            return Ok(false);
        };
        let mut package_sid = [0_u32; 17];
        let mut package_sid_bytes = std::mem::size_of_val(&package_sid) as u32;
        // SAFETY: `package_sid` is an aligned, writable buffer large enough for
        // the maximum SID, and `package_sid_bytes` is a local in/out length.
        if unsafe {
            CreateWellKnownSid(
                WinBuiltinAnyPackageSid,
                ptr::null_mut(),
                package_sid.as_mut_ptr().cast(),
                &mut package_sid_bytes,
            )
        } == 0
        {
            return Err(io::Error::last_os_error());
        }
        let package_sid = package_sid.as_mut_ptr().cast();
        let granted = container_rights(dacl, &[self.sid.0, package_sid])?;
        let required = map_file_generic_mask(access_mask(access));
        if granted & required == required {
            return Ok(false);
        }
        grant_sid_access(path, self.sid.0, access)?;
        Ok(true)
    }

    #[cfg(test)]
    pub(crate) fn effective_path_rights(&self, path: &Path) -> io::Result<u32> {
        let dacl = path_dacl(path)?;
        match dacl.dacl {
            Some(dacl) => container_rights(dacl, &[self.sid.0]),
            None => Ok(FILE_ALL_ACCESS),
        }
    }

    pub(crate) fn security_capabilities(&self) -> SECURITY_CAPABILITIES {
        SECURITY_CAPABILITIES {
            AppContainerSid: self.sid.0,
            Capabilities: if self.capability_attributes.is_empty() {
                ptr::null_mut()
            } else {
                self.capability_attributes.as_ptr().cast_mut()
            },
            CapabilityCount: self.capability_attributes.len() as u32,
            Reserved: 0,
        }
    }
}

/// Filesystem rights granted by [`AppContainerProfile::grant_path`].
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum AppContainerAccess {
    /// Lists directories and reads files and attributes, without execute access.
    Read,
    /// Reads, writes, and deletes files, without execute access.
    ReadWrite,
    /// Lists directories, reads files and attributes, and executes files.
    /// Loading a DLL needs execute access, so grant this on a directory the
    /// child loads code from.
    ReadExecute,
    /// Reads, writes, deletes and executes files.
    ReadWriteExecute,
}

const fn access_mask(access: AppContainerAccess) -> u32 {
    match access {
        AppContainerAccess::Read => GENERIC_READ,
        AppContainerAccess::ReadWrite => GENERIC_READ | GENERIC_WRITE | DELETE,
        AppContainerAccess::ReadExecute => GENERIC_READ | GENERIC_EXECUTE,
        AppContainerAccess::ReadWriteExecute => {
            GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE | DELETE
        }
    }
}

struct PathDacl {
    dacl: Option<*mut ACL>,
    _descriptor: LocalBlock,
}

fn path_dacl(path: &Path) -> io::Result<PathDacl> {
    let path = wide_null(path.as_os_str())?;
    let mut dacl: *mut ACL = ptr::null_mut();
    let mut descriptor = ptr::null_mut();
    // SAFETY: `path` is NUL-terminated and both outputs are local pointers;
    // Windows returns a LocalAlloc descriptor owned by `PathDacl`.
    let status = unsafe {
        GetNamedSecurityInfoW(
            path.as_ptr(),
            SE_FILE_OBJECT,
            DACL_SECURITY_INFORMATION,
            ptr::null_mut(),
            ptr::null_mut(),
            &mut dacl,
            ptr::null_mut(),
            &mut descriptor,
        )
    };
    if status != 0 {
        return Err(io::Error::from_raw_os_error(status as i32));
    }
    Ok(PathDacl {
        dacl: if dacl.is_null() { None } else { Some(dacl) },
        _descriptor: LocalBlock(descriptor.cast()),
    })
}

/// The rights `dacl` gives a token whose AppContainer check sees exactly
/// `sids`, evaluated as Windows evaluates `MAXIMUM_ALLOWED`: entries are read
/// in order, inherit-only entries are skipped, and a denied bit stays denied
/// when the deny entry precedes an allow. Object, callback, audit, mandatory
/// label, and other ACE types do not participate in this check.
fn container_rights(dacl: *const ACL, sids: &[PSID]) -> io::Result<u32> {
    let mut size = ACL_SIZE_INFORMATION::default();
    // SAFETY: `dacl` belongs to a live security descriptor and `size` is a
    // writable output of the exact size declared to Windows.
    if unsafe {
        GetAclInformation(
            dacl,
            (&mut size as *mut ACL_SIZE_INFORMATION).cast(),
            size_of::<ACL_SIZE_INFORMATION>() as u32,
            AclSizeInformation,
        )
    } == 0
    {
        return Err(io::Error::last_os_error());
    }

    let sid_offset = offset_of!(ACCESS_ALLOWED_ACE, SidStart);
    const SID_FIXED_BYTES: usize = 8;
    let mut granted = 0_u32;
    let mut denied = 0_u32;
    for index in 0..size.AceCount {
        let mut raw_ace = ptr::null_mut();
        // SAFETY: `dacl` is live, `index` is below the ACE count returned for
        // it, and `raw_ace` is a local output pointer.
        if unsafe { GetAce(dacl, index, &mut raw_ace) } == 0 {
            return Err(io::Error::last_os_error());
        }
        if raw_ace.is_null() {
            return Err(invalid_acl("Windows returned a null ACE"));
        }
        let ace = raw_ace.cast::<ACCESS_ALLOWED_ACE>();
        // SAFETY: GetAce returned a pointer to an ACE in the live ACL. Every ACE
        // begins with an ACE_HEADER, which is the first field of this layout.
        let header = unsafe { (*ace).Header };
        if u32::from(header.AceFlags) & INHERIT_ONLY_ACE != 0 {
            continue;
        }
        let kind = u32::from(header.AceType);
        if kind != ACCESS_ALLOWED_ACE_TYPE && kind != ACCESS_DENIED_ACE_TYPE {
            continue;
        }
        let ace_size = usize::from(header.AceSize);
        if ace_size < sid_offset + SID_FIXED_BYTES {
            return Err(invalid_acl("an access ACE is too short for its SID"));
        }
        // SAFETY: the ACE size check proves the fixed SID header starts inside
        // this ACE.
        let sid = unsafe { raw_ace.cast::<u8>().add(sid_offset).cast() };
        // SAFETY: the fixed SID header is in bounds, so Windows may validate its
        // revision and sub-authority count without reading beyond that header.
        if unsafe { IsValidSid(sid) } == 0 {
            return Err(invalid_acl("an access ACE contains an invalid SID"));
        }
        // SAFETY: IsValidSid accepted this SID.
        let sid_length = unsafe { GetLengthSid(sid) } as usize;
        if sid_length > ace_size - sid_offset {
            return Err(invalid_acl("an access ACE SID exceeds the ACE"));
        }
        let matches = sids.iter().any(|expected| {
            if expected.is_null() {
                return false;
            }
            // SAFETY: `sid` passed validation and lies in the live ACL; the
            // caller supplies live SIDs for this evaluation.
            unsafe { EqualSid(*expected, sid) != 0 }
        });
        if !matches {
            continue;
        }
        // SAFETY: the ACE size check above is longer than the complete fixed
        // ACCESS_ALLOWED_ACE fields, including Mask.
        let mask = map_file_generic_mask(unsafe { (*ace).Mask });
        if kind == ACCESS_ALLOWED_ACE_TYPE {
            granted |= mask & !denied;
        } else {
            denied |= mask & !granted;
        }
    }
    Ok(granted)
}

fn invalid_acl(message: &str) -> io::Error {
    io::Error::new(io::ErrorKind::InvalidData, message)
}

fn map_file_generic_mask(mut mask: u32) -> u32 {
    const FILE_MAPPING: GENERIC_MAPPING = GENERIC_MAPPING {
        GenericRead: FILE_GENERIC_READ,
        GenericWrite: FILE_GENERIC_WRITE,
        GenericExecute: FILE_GENERIC_EXECUTE,
        GenericAll: FILE_ALL_ACCESS,
    };
    // SAFETY: both pointers refer to live local values for the duration of the
    // call, which only replaces generic bits in `mask`.
    unsafe { MapGenericMask(&mut mask, &FILE_MAPPING) };
    mask
}

fn grant_sid_access(path: &Path, sid: PSID, access: AppContainerAccess) -> io::Result<()> {
    let path = wide_null(path.as_os_str())?;
    let mut old_dacl: *mut ACL = ptr::null_mut();
    let mut descriptor = ptr::null_mut();
    // SAFETY: `path` is NUL-terminated and both outputs are local pointers;
    // Windows returns a LocalAlloc descriptor owned by the guard below.
    let status = unsafe {
        GetNamedSecurityInfoW(
            path.as_ptr(),
            SE_FILE_OBJECT,
            DACL_SECURITY_INFORMATION,
            ptr::null_mut(),
            ptr::null_mut(),
            &mut old_dacl,
            ptr::null_mut(),
            &mut descriptor,
        )
    };
    if status != 0 {
        return Err(io::Error::from_raw_os_error(status as i32));
    }
    let _descriptor = LocalBlock(descriptor.cast());
    let entry = EXPLICIT_ACCESS_W {
        grfAccessPermissions: access_mask(access),
        grfAccessMode: SET_ACCESS,
        grfInheritance: OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE,
        Trustee: TRUSTEE_W {
            pMultipleTrustee: ptr::null_mut(),
            MultipleTrusteeOperation: 0,
            TrusteeForm: TRUSTEE_IS_SID,
            TrusteeType: TRUSTEE_IS_GROUP,
            ptstrName: sid.cast(),
        },
    };
    let mut new_dacl: *mut ACL = ptr::null_mut();
    // SAFETY: `entry` points at the live SID owned by `self`; `old_dacl` is
    // part of the live descriptor, and `new_dacl` is a local output pointer.
    let status = unsafe { SetEntriesInAclW(1, &entry, old_dacl, &mut new_dacl) };
    if status != 0 {
        return Err(io::Error::from_raw_os_error(status as i32));
    }
    let _new_dacl = LocalBlock(new_dacl.cast());
    // SAFETY: the path, descriptor and new DACL all stay live for this call;
    // only the object's DACL is changed, preserving its owner and other ACLs.
    let status = unsafe {
        SetNamedSecurityInfoW(
            path.as_ptr().cast_mut(),
            SE_FILE_OBJECT,
            DACL_SECURITY_INFORMATION,
            ptr::null_mut(),
            ptr::null_mut(),
            new_dacl,
            ptr::null_mut(),
        )
    };
    if status != 0 {
        return Err(io::Error::from_raw_os_error(status as i32));
    }
    Ok(())
}

fn hresult_error(hr: i32) -> io::Error {
    if ((hr as u32 >> 16) & 0x1fff) == 7 {
        io::Error::from_raw_os_error((hr as u32 & 0xffff) as i32)
    } else {
        io::Error::other(format!("HRESULT 0x{:08X}", hr as u32))
    }
}

struct LocalBlock(*mut std::ffi::c_void);

impl Drop for LocalBlock {
    fn drop(&mut self) {
        // SAFETY: the block is allocated by GetNamedSecurityInfoW or
        // SetEntriesInAclW and is freed exactly once with LocalFree.
        unsafe { LocalFree(self.0) };
    }
}

impl std::fmt::Debug for AppContainerProfile {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AppContainerProfile")
            .field("sid", &self.sid)
            .field("capability_count", &self.capability_attributes.len())
            .field("created", &self.created)
            .finish()
    }
}

struct AppContainerSid(PSID);

impl std::fmt::Debug for AppContainerSid {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_tuple("AppContainerSid").field(&self.0).finish()
    }
}

impl Drop for AppContainerSid {
    fn drop(&mut self) {
        // SAFETY: both AppContainer profile APIs allocate the returned SID
        // with the allocator paired with FreeSid, and this wrapper owns it.
        unsafe { FreeSid(self.0) };
    }
}

pub(crate) struct DerivedCapability {
    capability_sids: Vec<PSID>,
    capability_array: *mut PSID,
    group_sids: Vec<PSID>,
    group_array: *mut PSID,
}

impl DerivedCapability {
    pub(crate) fn from_name(name: &str) -> io::Result<Self> {
        let name = wide_null(name)?;
        if name.len() <= 1 {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "capability names must not be empty",
            ));
        }
        let mut group_array = ptr::null_mut();
        let mut group_count = 0_u32;
        let mut capability_array = ptr::null_mut();
        let mut capability_count = 0_u32;
        // SAFETY: the name is NUL-terminated and all output pointers refer to
        // initialized locals. The API allocations are owned and freed below.
        if unsafe {
            DeriveCapabilitySidsFromName(
                name.as_ptr(),
                &mut group_array,
                &mut group_count,
                &mut capability_array,
                &mut capability_count,
            )
        } == 0
        {
            let error = io::Error::last_os_error();
            // SAFETY: failure may still leave one or both API output pointer
            // arrays populated; free every returned array block.
            if !group_array.is_null() {
                // SAFETY: this is an API output allocation from the failed call.
                unsafe { LocalFree(group_array.cast()) };
            }
            if !capability_array.is_null() {
                // SAFETY: this is an API output allocation from the failed call.
                unsafe { LocalFree(capability_array.cast()) };
            }
            return Err(error);
        }

        let capability_sids = if capability_count == 0 || capability_array.is_null() {
            Vec::new()
        } else {
            // SAFETY: Windows returned `capability_count` entries in this array.
            unsafe { std::slice::from_raw_parts(capability_array, capability_count as usize) }
                .to_vec()
        };
        let group_sids = if group_count == 0 || group_array.is_null() {
            Vec::new()
        } else {
            // SAFETY: Windows returned `group_count` entries in this array.
            unsafe { std::slice::from_raw_parts(group_array, group_count as usize) }.to_vec()
        };
        let derived = Self {
            capability_sids,
            capability_array,
            group_sids,
            group_array,
        };
        if capability_count == 0 || capability_array.is_null() {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "Windows resolved no capability SIDs",
            ));
        }
        Ok(derived)
    }

    pub(crate) fn capability_sids(&self) -> &[PSID] {
        &self.capability_sids
    }
}

impl Drop for DerivedCapability {
    fn drop(&mut self) {
        for sid in self.capability_sids.iter().chain(&self.group_sids) {
            if !sid.is_null() {
                // SAFETY: DeriveCapabilitySidsFromName returned each SID as
                // a separately owned LocalAlloc block.
                unsafe { LocalFree((*sid).cast()) };
            }
        }
        if !self.capability_array.is_null() {
            // SAFETY: this is the LocalAlloc pointer array from the API.
            unsafe { LocalFree(self.capability_array.cast()) };
        }
        if !self.group_array.is_null() {
            // SAFETY: this is the LocalAlloc pointer array from the API.
            unsafe { LocalFree(self.group_array.cast()) };
        }
    }
}

const _: () = {
    const fn assert_send_sync<T: Send + Sync>() {}
    assert_send_sync::<AppContainerProfile>();
    assert_send_sync::<crate::Launch<'static>>();
};

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

    #[test]
    fn win32_hresult_preserves_the_win32_error_code() {
        let error = hresult_error(0x8007_0005_u32 as i32);
        assert_eq!(error.raw_os_error(), Some(5));
        assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);
    }

    #[test]
    fn non_win32_hresult_keeps_its_hexadecimal_identity() {
        let error = hresult_error(0x8000_ffff_u32 as i32);
        assert_eq!(error.raw_os_error(), None);
        assert!(error.to_string().contains("HRESULT 0x8000FFFF"));
    }
}