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
//! Security descriptors, SIDs and token privileges.
//!
//! A descriptor Windows hands back is a single `LocalAlloc` block whose inner
//! pointers (owner, DACL, ACEs, SIDs) all point inside it. The types in the
//! `acl` submodule turn that block into bounds-checked byte views before
//! anything is read, so a malformed or hostile descriptor is rejected by
//! offset arithmetic rather than dereferenced.
#![allow(unsafe_code)]

mod acl;

use std::ffi::c_void;
use std::io;
use std::marker::PhantomData;
use std::mem::size_of;
use std::os::windows::io::{AsHandle, AsRawHandle, OwnedHandle, RawHandle};
use std::path::Path;
use std::ptr::{self, NonNull};
use std::sync::{Mutex, MutexGuard, PoisonError};

use windows_sys::Win32::Foundation::{
    LocalFree, SetLastError, ERROR_INSUFFICIENT_BUFFER, ERROR_NOT_ALL_ASSIGNED, ERROR_SUCCESS, LUID,
};
use windows_sys::Win32::Security::Authorization::{
    ConvertSidToStringSidW, ConvertStringSecurityDescriptorToSecurityDescriptorW,
    GetNamedSecurityInfoW, GetSecurityInfo, TreeSetNamedSecurityInfoW, SDDL_REVISION_1,
    SE_FILE_OBJECT, SE_KERNEL_OBJECT, TREE_SEC_INFO_RESET,
};
use windows_sys::Win32::Security::{
    AdjustTokenPrivileges, CheckTokenMembership, GetSecurityDescriptorControl,
    GetSecurityDescriptorDacl, GetSecurityDescriptorLength, GetSecurityDescriptorOwner,
    GetTokenInformation, LookupPrivilegeValueW, TokenUser, DACL_SECURITY_INFORMATION,
    LUID_AND_ATTRIBUTES, OWNER_SECURITY_INFORMATION, PROTECTED_DACL_SECURITY_INFORMATION,
    PSECURITY_DESCRIPTOR, SECURITY_ATTRIBUTES, SE_PRIVILEGE_ENABLED, TOKEN_ADJUST_PRIVILEGES,
    TOKEN_PRIVILEGES, TOKEN_QUERY, TOKEN_USER,
};
use windows_sys::Win32::System::Threading::OpenProcessToken;

pub use acl::{
    AclValidationError, AllowedAce, OwnedSid, SecurityAclError, ValidatedDacl, ValidatedSid,
};

use crate::bounded_read::{probe_word_aligned, CallOutcome};
use crate::handle::{current_process, owned_from_creation};
use crate::wide::{bounded_units, wide_null};

const MAX_TOKEN_INFORMATION_BYTES: usize = 64 * 1024;
const MAX_SID_STRING_UNITS: usize = 32_768;

/// A security descriptor built from SDDL, for creating objects
/// ([`crate::PipeServer`], [`crate::NamedMutex`], [`crate::Job`]) and for
/// resetting the ACLs of a directory tree.
///
/// ```no_run
/// # fn main() -> std::io::Result<()> {
/// use win_custody::SecurityDescriptor;
///
/// // LocalSystem and the built-in Administrators get full access; nobody
/// // else gets any, and the DACL does not inherit from its parent.
/// let descriptor = SecurityDescriptor::from_sddl("D:P(A;;GA;;;SY)(A;;GA;;;BA)")?;
/// # Ok(())
/// # }
/// ```
#[derive(Debug)]
pub struct SecurityDescriptor(NonNull<c_void>);

// SAFETY: the descriptor is an immutable LocalAlloc block owned by this value;
// Windows only reads it, so it may be moved to and shared between threads.
unsafe impl Send for SecurityDescriptor {}
// SAFETY: see `Send`; no method mutates the block.
unsafe impl Sync for SecurityDescriptor {}

impl SecurityDescriptor {
    /// Parses an SDDL string. The error carries the Win32 code
    /// (`ERROR_INVALID_PARAMETER` for malformed SDDL).
    pub fn from_sddl(sddl: &str) -> io::Result<Self> {
        let sddl = wide_null(sddl)?;
        let mut descriptor = ptr::null_mut();
        // SAFETY: `sddl` is NUL-terminated; `descriptor` is a live out pointer
        // that receives a LocalAlloc block owned by the returned value.
        let converted = unsafe {
            ConvertStringSecurityDescriptorToSecurityDescriptorW(
                sddl.as_ptr(),
                SDDL_REVISION_1,
                &mut descriptor,
                ptr::null_mut(),
            )
        };
        if converted == 0 || descriptor.is_null() {
            return Err(io::Error::last_os_error());
        }
        Ok(Self(
            NonNull::new(descriptor).expect("checked non-null descriptor"),
        ))
    }

    /// A `SECURITY_ATTRIBUTES` block pointing at this descriptor, for object
    /// creation calls. It borrows the descriptor and cannot outlive it.
    pub(crate) fn attributes(&self, inherit_handle: bool) -> SecurityAttributes<'_> {
        SecurityAttributes {
            raw: SECURITY_ATTRIBUTES {
                nLength: size_of::<SECURITY_ATTRIBUTES>() as u32,
                lpSecurityDescriptor: self.0.as_ptr(),
                bInheritHandle: i32::from(inherit_handle),
            },
            _descriptor: PhantomData,
        }
    }

    /// Applies this descriptor's DACL to `path` and its whole subtree,
    /// resetting every inherited entry. With `protect` the tree also stops
    /// inheriting from its parent. The error carries the Win32 status.
    pub fn apply_to_tree(&self, path: &Path, protect: bool) -> io::Result<()> {
        let mut present = 0;
        let mut defaulted = 0;
        let mut dacl = ptr::null_mut();
        // SAFETY: `self.0` is a live descriptor and every out pointer is a
        // local; the DACL pointer stays valid while `self` is borrowed.
        let read = unsafe {
            GetSecurityDescriptorDacl(self.0.as_ptr(), &mut present, &mut dacl, &mut defaulted)
        };
        if read == 0 {
            return Err(io::Error::last_os_error());
        }
        if present == 0 || dacl.is_null() {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "the descriptor has no DACL to apply",
            ));
        }
        let information = if protect {
            DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION
        } else {
            DACL_SECURITY_INFORMATION
        };
        let wide = wide_null(path)?;
        // SAFETY: `wide` is NUL-terminated; `dacl` points into the live
        // descriptor; owner, group, and SACL are null with matching flags
        // absent; no progress callback is installed.
        let status = unsafe {
            TreeSetNamedSecurityInfoW(
                wide.as_ptr(),
                SE_FILE_OBJECT,
                information,
                ptr::null_mut(),
                ptr::null_mut(),
                dacl,
                ptr::null_mut(),
                TREE_SEC_INFO_RESET,
                None,
                0,
                ptr::null(),
            )
        };
        if status != ERROR_SUCCESS {
            return Err(io::Error::from_raw_os_error(status as i32));
        }
        Ok(())
    }
}

impl Drop for SecurityDescriptor {
    fn drop(&mut self) {
        // SAFETY: the block came from the converter and is freed exactly once.
        unsafe { LocalFree(self.0.as_ptr()) };
    }
}

/// A `SECURITY_ATTRIBUTES` block that borrows its descriptor.
pub(crate) struct SecurityAttributes<'a> {
    raw: SECURITY_ATTRIBUTES,
    _descriptor: PhantomData<&'a SecurityDescriptor>,
}

impl SecurityAttributes<'_> {
    pub(crate) fn as_ptr(&self) -> *const SECURITY_ATTRIBUTES {
        &self.raw
    }
}

/// The security descriptor of an existing object, with accessors that
/// validate its parts before exposing them. Use it to verify that a pipe,
/// file or directory carries the ACL you expect.
#[derive(Debug)]
pub struct ObjectSecurityDescriptor(NonNull<c_void>);

// SAFETY: the descriptor is a LocalAlloc block owned by this value and only
// read; moving or sharing it across threads is sound.
unsafe impl Send for ObjectSecurityDescriptor {}
// SAFETY: see `Send`.
unsafe impl Sync for ObjectSecurityDescriptor {}

impl ObjectSecurityDescriptor {
    /// The DACL of the file or directory at `path`. The error carries the
    /// Win32 status, so callers can recognize a vanished path.
    pub fn query_file(path: &Path) -> io::Result<Self> {
        let wide = wide_null(path)?;
        let mut descriptor = ptr::null_mut();
        // SAFETY: `wide` is NUL-terminated, every optional output is null, and
        // `descriptor` is a live out pointer whose ownership transfers below.
        let status = unsafe {
            GetNamedSecurityInfoW(
                wide.as_ptr(),
                SE_FILE_OBJECT,
                DACL_SECURITY_INFORMATION,
                ptr::null_mut(),
                ptr::null_mut(),
                ptr::null_mut(),
                ptr::null_mut(),
                &mut descriptor,
            )
        };
        Self::from_query_result(status, descriptor)
    }

    /// The owner and DACL of the kernel object behind `handle`. The handle
    /// needs `READ_CONTROL`.
    pub fn query_kernel_object(handle: &impl AsHandle) -> io::Result<Self> {
        let raw = handle.as_handle().as_raw_handle();
        let mut descriptor = ptr::null_mut();
        // SAFETY: the handle is live for the call; all optional outputs are
        // null and `descriptor` is a live out pointer.
        let status = unsafe {
            GetSecurityInfo(
                raw,
                SE_KERNEL_OBJECT,
                OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
                ptr::null_mut(),
                ptr::null_mut(),
                ptr::null_mut(),
                ptr::null_mut(),
                &mut descriptor,
            )
        };
        Self::from_query_result(status, descriptor)
    }

    fn from_query_result(status: u32, descriptor: PSECURITY_DESCRIPTOR) -> io::Result<Self> {
        if status != ERROR_SUCCESS || descriptor.is_null() {
            if !descriptor.is_null() {
                // SAFETY: a non-null descriptor from these APIs is a LocalAlloc
                // block, even on a partial failure; it is freed exactly once.
                unsafe { LocalFree(descriptor) };
            }
            let status = if status == ERROR_SUCCESS {
                io::Error::new(io::ErrorKind::InvalidData, "Windows returned no descriptor")
            } else {
                io::Error::from_raw_os_error(status as i32)
            };
            return Err(status);
        }
        Ok(Self(
            NonNull::new(descriptor).expect("checked non-null descriptor"),
        ))
    }

    /// The descriptor control bits (for example `SE_DACL_PROTECTED`).
    pub fn control(&self) -> io::Result<u16> {
        let mut control = 0_u16;
        let mut revision = 0_u32;
        // SAFETY: `self.0` is a live descriptor; both outputs are locals.
        let read =
            unsafe { GetSecurityDescriptorControl(self.0.as_ptr(), &mut control, &mut revision) };
        if read == 0 {
            return Err(io::Error::last_os_error());
        }
        Ok(control)
    }

    /// The owner SID. Only present when the query asked for it
    /// ([`query_kernel_object`](Self::query_kernel_object) does).
    pub fn owner(&self) -> Result<ValidatedSid, SecurityAclError> {
        let mut owner = ptr::null_mut();
        let mut defaulted = 0;
        // SAFETY: `self.0` is a live descriptor; both outputs are locals. The
        // returned owner pointer is range-checked before it is read.
        let read =
            unsafe { GetSecurityDescriptorOwner(self.0.as_ptr(), &mut owner, &mut defaulted) };
        if read == 0 {
            return Err(io::Error::last_os_error().into());
        }
        if owner.is_null() {
            return Err(AclValidationError::MissingOwner.into());
        }
        ValidatedSid::from_bounded_bytes(self.bytes_from_pointer(owner.cast())?).map_err(Into::into)
    }

    /// The DACL, provided every entry in it is an access-allowed ACE.
    pub fn dacl(&self) -> Result<ValidatedDacl, SecurityAclError> {
        let mut present = 0;
        let mut defaulted = 0;
        let mut dacl = ptr::null_mut();
        // SAFETY: `self.0` is a live descriptor; all outputs are locals. The
        // returned DACL pointer is range-checked before it is read.
        let read = unsafe {
            GetSecurityDescriptorDacl(self.0.as_ptr(), &mut present, &mut dacl, &mut defaulted)
        };
        if read == 0 {
            return Err(io::Error::last_os_error().into());
        }
        if present == 0 || dacl.is_null() {
            return Err(AclValidationError::MissingDacl.into());
        }
        ValidatedDacl::from_bytes(self.bytes_from_pointer(dacl.cast())?).map_err(Into::into)
    }

    /// The bytes of the descriptor block from `pointer` to its end, provided
    /// `pointer` lies inside the block.
    fn bytes_from_pointer(&self, pointer: *const u8) -> Result<&[u8], AclValidationError> {
        // SAFETY: `self.0` is a live descriptor owned for this call.
        let length = unsafe { GetSecurityDescriptorLength(self.0.as_ptr()) } as usize;
        if length == 0 {
            return Err(AclValidationError::DescriptorRange);
        }
        let offset = (pointer as usize)
            .checked_sub(self.0.as_ptr() as usize)
            .filter(|offset| *offset < length)
            .ok_or(AclValidationError::DescriptorRange)?;
        // SAFETY: Windows reports `length` for this live LocalAlloc block, and
        // the offset was proven to fall inside it.
        let bytes = unsafe { std::slice::from_raw_parts(self.0.as_ptr().cast::<u8>(), length) };
        Ok(&bytes[offset..])
    }
}

impl Drop for ObjectSecurityDescriptor {
    fn drop(&mut self) {
        // SAFETY: this value uniquely owns the LocalAlloc block.
        unsafe { LocalFree(self.0.as_ptr()) };
    }
}

/// The calling process's user SID in string form, such as `S-1-5-18`.
pub fn current_user_sid_string() -> io::Result<String> {
    let token = open_current_process_token(TOKEN_QUERY)?;
    token_user_sid_string(token.as_raw_handle())
}

/// The user SID of the token `raw`, in string form. The handle must be live
/// and opened with `TOKEN_QUERY`.
pub(crate) fn token_user_sid_string(raw: RawHandle) -> io::Result<String> {
    let information = probe_word_aligned(
        size_of::<TOKEN_USER>(),
        MAX_TOKEN_INFORMATION_BYTES,
        |buffer, capacity, needed| {
            // SAFETY: the token is live; the protocol passes either the
            // documented null size probe or word-aligned writable storage
            // described by `capacity`, and `needed` is a live out value.
            let result =
                unsafe { GetTokenInformation(raw, TokenUser, buffer.cast(), capacity, needed) };
            if result != 0 {
                return Ok(CallOutcome::Complete);
            }
            let error = io::Error::last_os_error();
            if error.raw_os_error() == Some(ERROR_INSUFFICIENT_BUFFER as i32) {
                Ok(CallOutcome::MoreData(error))
            } else {
                Err(error)
            }
        },
    )
    .map_err(|error| error.into_io("token user information"))?;
    // SAFETY: GetTokenInformation succeeded and the protocol verified that its
    // reported byte range holds a complete, word-aligned TOKEN_USER header.
    let user = unsafe { information.read::<TOKEN_USER>() }
        .expect("token information header size and alignment were checked");
    let sid_offset = (user.User.Sid as usize).checked_sub(information.as_ptr() as usize);
    if sid_offset.map_or(true, |offset| offset >= information.len()) {
        return Err(io::Error::new(
            io::ErrorKind::InvalidData,
            "the token user SID lies outside the returned buffer",
        ));
    }
    let mut string = ptr::null_mut();
    // SAFETY: the SID pointer lies inside the live token-information buffer
    // and `string` is a local output receiving a LocalAlloc allocation.
    if unsafe { ConvertSidToStringSidW(user.User.Sid, &mut string) } == 0 || string.is_null() {
        return Err(io::Error::last_os_error());
    }
    // SAFETY: ConvertSidToStringSidW returned a readable NUL-terminated string;
    // it is read within a fixed bound before conversion.
    let units = unsafe { bounded_units(string, MAX_SID_STRING_UNITS) };
    let result = units
        .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "SID string exceeds the bound"))
        .and_then(|units| {
            String::from_utf16(units).map_err(|_| {
                io::Error::new(io::ErrorKind::InvalidData, "SID string is not valid UTF-16")
            })
        });
    // SAFETY: the string was allocated by ConvertSidToStringSidW and is freed
    // exactly once after the bounded copy.
    unsafe { LocalFree(string.cast()) };
    result
}

/// Whether the calling thread's token (or the process token, when the thread
/// is not impersonating) has `group` as an enabled group.
pub fn current_token_is_member_of(group: &OwnedSid) -> io::Result<bool> {
    let mut is_member = 0;
    // SAFETY: a null token means the current thread or process token; the
    // SID is a live LocalAlloc block owned by `group`; the output is a local.
    let checked = unsafe { CheckTokenMembership(ptr::null_mut(), group.as_ptr(), &mut is_member) };
    if checked == 0 {
        return Err(io::Error::last_os_error());
    }
    Ok(is_member != 0)
}

/// A privilege enabled in the process token for this value's lifetime.
///
/// Every thread shares the process token, so guards for the same privilege
/// are counted: the privilege stays enabled until the last of them is dropped
/// and is disabled then. A privilege that was already enabled before its first
/// guard, such as `SeChangeNotifyPrivilege` in every token, is left enabled.
pub struct PrivilegeGuard {
    token: OwnedHandle,
    luid: LUID,
    /// Whether this guard is one of those counted in [`TURNED_ON`].
    counted: bool,
}

/// The privileges guards turned on, as `(LowPart, HighPart)` of the LUID, each
/// with the number of live guards. A privilege that was enabled before its
/// first guard is absent: no guard turned it on, so none turns it off.
static TURNED_ON: Mutex<Vec<((u32, i32), usize)>> = Mutex::new(Vec::new());

fn lock_turned_on() -> MutexGuard<'static, Vec<((u32, i32), usize)>> {
    // The list is consistent after every statement that changes it, so a
    // panic elsewhere while it was locked leaves nothing to repair.
    TURNED_ON.lock().unwrap_or_else(PoisonError::into_inner)
}

impl std::fmt::Debug for PrivilegeGuard {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("PrivilegeGuard")
            .field("token", &self.token)
            .field("luid_high", &self.luid.HighPart)
            .field("luid_low", &self.luid.LowPart)
            .finish()
    }
}

impl PrivilegeGuard {
    /// Enables the privilege `name`, such as `SeBackupPrivilege`. A token
    /// that does not hold the privilege fails with
    /// [`io::ErrorKind::PermissionDenied`]; enabling only works for
    /// privileges the token already has.
    pub fn enable(name: &str) -> io::Result<PrivilegeGuard> {
        let token = open_current_process_token(TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY)?;
        let name_wide = wide_null(name)?;
        let mut luid = LUID::default();
        // SAFETY: `name_wide` is NUL-terminated and `luid` is a local output.
        if unsafe { LookupPrivilegeValueW(ptr::null(), name_wide.as_ptr(), &mut luid) } == 0 {
            return Err(io::Error::last_os_error());
        }
        let privileges = token_privileges(luid, SE_PRIVILEGE_ENABLED);
        let mut previous = TOKEN_PRIVILEGES::default();
        let mut previous_bytes = 0_u32;
        // Held across the adjustment, so that a guard being dropped on another
        // thread cannot disable the privilege between the call and the count.
        let mut turned_on = lock_turned_on();
        // SAFETY: clearing last-error is required because a successful
        // AdjustTokenPrivileges reports partial assignment through last-error.
        unsafe { SetLastError(ERROR_SUCCESS) };
        // SAFETY: the token has adjust and query rights and `privileges` is a
        // complete, live one-entry TOKEN_PRIVILEGES value; `previous` is a
        // local one-entry buffer of the stated size, enough for the one
        // privilege that can change, and `previous_bytes` is a local output.
        let adjusted = unsafe {
            AdjustTokenPrivileges(
                token.as_raw_handle(),
                0,
                &privileges,
                size_of::<TOKEN_PRIVILEGES>() as u32,
                &mut previous,
                &mut previous_bytes,
            )
        };
        if adjusted == 0 {
            return Err(io::Error::last_os_error());
        }
        let assignment = io::Error::last_os_error();
        if assignment.raw_os_error() == Some(ERROR_NOT_ALL_ASSIGNED as i32) {
            return Err(io::Error::new(
                io::ErrorKind::PermissionDenied,
                format!("the current token does not hold {name}"),
            ));
        }
        // Windows reports only the privileges the call changed, so an empty
        // previous state means this one was enabled already.
        let changed = previous.PrivilegeCount != 0;
        let key = (luid.LowPart, luid.HighPart);
        let counted = match turned_on.iter_mut().find(|entry| entry.0 == key) {
            Some(entry) => {
                entry.1 += 1;
                true
            }
            None if changed => {
                turned_on.push((key, 1));
                true
            }
            None => false,
        };
        Ok(Self {
            token,
            luid,
            counted,
        })
    }
}

impl Drop for PrivilegeGuard {
    fn drop(&mut self) {
        if !self.counted {
            return;
        }
        let mut turned_on = lock_turned_on();
        let key = (self.luid.LowPart, self.luid.HighPart);
        let Some(index) = turned_on.iter().position(|entry| entry.0 == key) else {
            return;
        };
        turned_on[index].1 -= 1;
        if turned_on[index].1 != 0 {
            return;
        }
        turned_on.swap_remove(index);
        let privileges = token_privileges(self.luid, 0);
        // SAFETY: the token remains live through drop and `privileges` is a
        // complete one-entry value; disabling is best effort by contract.
        unsafe {
            AdjustTokenPrivileges(
                self.token.as_raw_handle(),
                0,
                &privileges,
                0,
                ptr::null_mut(),
                ptr::null_mut(),
            )
        };
    }
}

fn token_privileges(luid: LUID, attributes: u32) -> TOKEN_PRIVILEGES {
    TOKEN_PRIVILEGES {
        PrivilegeCount: 1,
        Privileges: [LUID_AND_ATTRIBUTES {
            Luid: luid,
            Attributes: attributes,
        }],
    }
}

fn open_current_process_token(access: u32) -> io::Result<OwnedHandle> {
    let mut token = ptr::null_mut();
    // SAFETY: the process pseudo-handle is always valid and `token` is a local
    // out pointer whose handle is owned immediately below.
    if unsafe { OpenProcessToken(current_process(), access, &mut token) } == 0 {
        return Err(io::Error::last_os_error());
    }
    owned_from_creation(token)
}

#[cfg(test)]
mod tests {
    use std::os::windows::io::AsRawHandle;
    use std::ptr::null;

    use windows_sys::Win32::Foundation::{ERROR_INVALID_PARAMETER, LUID};
    use windows_sys::Win32::Security::{
        LookupPrivilegeValueW, PrivilegeCheck, LUID_AND_ATTRIBUTES, PRIVILEGE_SET, TOKEN_QUERY,
    };
    use windows_sys::Win32::System::SystemServices::PRIVILEGE_SET_ALL_NECESSARY;

    use super::{
        current_token_is_member_of, current_user_sid_string, open_current_process_token,
        ObjectSecurityDescriptor, OwnedSid, PrivilegeGuard, SecurityDescriptor,
    };
    use crate::wide::wide_null;

    #[test]
    fn a_tree_reset_from_sddl_reads_back_as_the_same_allowed_aces() {
        let directory = tempfile::tempdir().unwrap();
        let child = directory.path().join("child");
        std::fs::create_dir(&child).unwrap();
        let current_user = current_user_sid_string().unwrap();
        let sddl = format!("D:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;FA;;;{current_user})");
        let descriptor = SecurityDescriptor::from_sddl(&sddl).unwrap();
        descriptor.apply_to_tree(directory.path(), true).unwrap();

        let system = OwnedSid::from_string("S-1-5-18").unwrap();
        let queried = ObjectSecurityDescriptor::query_file(&child).unwrap();
        let dacl = queried.dacl().unwrap();
        assert_eq!(dacl.len(), 3);
        assert!(dacl.allowed_aces().any(|ace| ace.trustee_matches(&system)));
        assert!(ObjectSecurityDescriptor::query_file(&directory.path().join("missing")).is_err());
    }

    #[test]
    fn malformed_sddl_reports_invalid_parameter() {
        let error = SecurityDescriptor::from_sddl("D:(not sddl").unwrap_err();
        assert_eq!(error.raw_os_error(), Some(ERROR_INVALID_PARAMETER as i32));
    }

    #[test]
    fn the_current_user_sid_has_a_decimal_sid_shape() {
        let sid = current_user_sid_string().unwrap();
        assert!(sid.starts_with("S-1-"), "unexpected SID {sid}");
        assert!(sid[4..].split('-').all(|component| !component.is_empty()

            && component.bytes().all(|byte| byte.is_ascii_digit())));
    }

    #[test]
    fn every_token_is_a_member_of_everyone() {
        let everyone = OwnedSid::from_string("WD").unwrap();
        assert!(current_token_is_member_of(&everyone).unwrap());
    }

    #[test]
    fn held_privileges_enable_and_unknown_names_fail() {
        drop(PrivilegeGuard::enable("SeChangeNotifyPrivilege").unwrap());
        assert!(PrivilegeGuard::enable("SeNotARealPrivilege").is_err());
    }

    /// Whether `name` is enabled in the process token right now.
    fn privilege_is_enabled(name: &str) -> bool {
        let token = open_current_process_token(TOKEN_QUERY).unwrap();
        let name = wide_null(name).unwrap();
        let mut luid = LUID::default();
        // SAFETY: `name` is NUL-terminated and `luid` is a local output.
        let found = unsafe { LookupPrivilegeValueW(null(), name.as_ptr(), &mut luid) };
        assert_ne!(found, 0, "{}", std::io::Error::last_os_error());
        let mut required = PRIVILEGE_SET {
            PrivilegeCount: 1,
            Control: PRIVILEGE_SET_ALL_NECESSARY,
            Privilege: [LUID_AND_ATTRIBUTES {
                Luid: luid,
                Attributes: 0,
            }],
        };
        let mut enabled = 0;
        // SAFETY: the token is live with query access, `required` is a
        // complete one-entry set and `enabled` is a local output.
        let checked = unsafe { PrivilegeCheck(token.as_raw_handle(), &mut required, &mut enabled) };
        assert_ne!(checked, 0, "{}", std::io::Error::last_os_error());
        enabled != 0
    }

    #[test]
    fn a_guard_leaves_a_privilege_that_was_already_enabled_enabled() {
        // Every token holds SeChangeNotifyPrivilege, enabled from the start.
        // Without it a child cannot pass through directories it may not list.
        assert!(privilege_is_enabled("SeChangeNotifyPrivilege"));
        drop(PrivilegeGuard::enable("SeChangeNotifyPrivilege").unwrap());
        assert!(privilege_is_enabled("SeChangeNotifyPrivilege"));
    }

    #[test]
    fn a_privilege_stays_enabled_until_its_last_guard_is_dropped() {
        // Held by every user, and disabled until asked for.
        let name = "SeIncreaseWorkingSetPrivilege";
        assert!(!privilege_is_enabled(name));
        let first = PrivilegeGuard::enable(name).unwrap();
        let second = PrivilegeGuard::enable(name).unwrap();
        assert!(privilege_is_enabled(name));
        drop(first);
        assert!(privilege_is_enabled(name));
        drop(second);
        assert!(!privilege_is_enabled(name));
    }
}