exarch-core 0.10.0

Memory-safe archive extraction library with security validation
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
//! Test-only reader of a directory's DACL, for the Windows tests that check
//! who may reach a staging directory.

#![deny(clippy::undocumented_unsafe_blocks)]
#![allow(clippy::unwrap_used, clippy::expect_used)]

use std::fs::OpenOptions;
use std::io;
use std::mem::MaybeUninit;
use std::mem::offset_of;
use std::mem::size_of;
use std::os::windows::fs::OpenOptionsExt;
use std::os::windows::io::AsRawHandle;
use std::path::Path;
use std::ptr::NonNull;
use std::ptr::null_mut;

use windows_sys::Win32::Foundation::ERROR_SUCCESS;
use windows_sys::Win32::Foundation::LocalFree;
use windows_sys::Win32::Security::ACCESS_ALLOWED_ACE;
use windows_sys::Win32::Security::ACE_HEADER;
use windows_sys::Win32::Security::ACL;
use windows_sys::Win32::Security::ACL_REVISION;
use windows_sys::Win32::Security::ACL_SIZE_INFORMATION;
use windows_sys::Win32::Security::AclSizeInformation;
use windows_sys::Win32::Security::AddAccessAllowedAceEx;
use windows_sys::Win32::Security::Authorization::ConvertSecurityDescriptorToStringSecurityDescriptorW;
use windows_sys::Win32::Security::Authorization::ConvertSidToStringSidW;
use windows_sys::Win32::Security::Authorization::ConvertStringSecurityDescriptorToSecurityDescriptorW;
use windows_sys::Win32::Security::Authorization::ConvertStringSidToSidW;
use windows_sys::Win32::Security::Authorization::GetSecurityInfo;
use windows_sys::Win32::Security::Authorization::SDDL_REVISION_1;
use windows_sys::Win32::Security::Authorization::SE_FILE_OBJECT;
use windows_sys::Win32::Security::Authorization::SetNamedSecurityInfoW;
use windows_sys::Win32::Security::DACL_SECURITY_INFORMATION;
use windows_sys::Win32::Security::GetAce;
use windows_sys::Win32::Security::GetAclInformation;
use windows_sys::Win32::Security::GetSecurityDescriptorControl;
use windows_sys::Win32::Security::GetSecurityDescriptorDacl;
use windows_sys::Win32::Security::ImpersonateSelf;
use windows_sys::Win32::Security::InitializeAcl;
use windows_sys::Win32::Security::PROTECTED_DACL_SECURITY_INFORMATION;
use windows_sys::Win32::Security::PSECURITY_DESCRIPTOR;
use windows_sys::Win32::Security::RevertToSelf;
use windows_sys::Win32::Security::SE_DACL_AUTO_INHERITED;
use windows_sys::Win32::Security::SE_DACL_PROTECTED;
use windows_sys::Win32::Security::SecurityImpersonation;
use windows_sys::Win32::Security::UNPROTECTED_DACL_SECURITY_INFORMATION;
use windows_sys::Win32::Storage::FileSystem::FILE_FLAG_BACKUP_SEMANTICS;
use windows_sys::Win32::Storage::FileSystem::FILE_FLAG_OPEN_REPARSE_POINT;

use super::nt::security::EffectiveToken;
use super::nt::security::TokenUser;
use super::nt::win32;

const ACCESS_ALLOWED_ACE_TYPE: u8 = 0;
const READ_CONTROL: u32 = 0x0002_0000;
/// The `FILE_ALL_ACCESS` mask.
pub(crate) const FILE_ALL_ACCESS: u32 = 0x001F_01FF;
const OBJECT_INHERIT_ACE: u8 = 0x01;
const CONTAINER_INHERIT_ACE: u8 = 0x02;
/// `OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE`, the `OICI` of SDDL.
pub(crate) const OICI: u8 = OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE;

/// One entry of a DACL.
#[derive(Debug, PartialEq, Eq)]
pub(crate) struct Ace {
    /// Whether it is an `ACCESS_ALLOWED_ACE`.
    pub(crate) allows: bool,
    /// The `AceFlags` byte (`INHERITED_ACE` is 0x10).
    pub(crate) flags: u8,
    /// The access mask; zero for an entry that is not an allow entry.
    pub(crate) mask: u32,
    /// The SID in string form.
    pub(crate) sid: String,
}

impl Ace {
    /// Whether the system marked this entry as inherited from a parent.
    pub(crate) const fn inherited(&self) -> bool {
        self.flags & 0x10 != 0
    }

    /// Whether children of the directory carrying this entry inherit it.
    pub(crate) const fn inheritable(&self) -> bool {
        self.flags & (OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE) != 0
    }
}

/// A DACL as the tests need it.
#[derive(Debug)]
pub(crate) struct Dacl {
    /// `SE_DACL_PROTECTED`: the parent's entries are ignored.
    pub(crate) protected: bool,
    /// `SE_DACL_AUTO_INHERITED`: the entries marked inherited were derived by
    /// the system.
    pub(crate) auto_inherited: bool,
    /// Whether there is no DACL at all, which grants everyone full access.
    pub(crate) null: bool,
    pub(crate) aces: Vec<Ace>,
}

impl Dacl {
    /// Whether `other` has the same bits and entries, in the same order.
    pub(crate) fn same_as(&self, other: &Self) -> bool {
        self.protected == other.protected
            && self.auto_inherited == other.auto_inherited
            && self.null == other.null
            && self.aces == other.aces
    }
}

/// A thread that impersonates the process user, reverted on drop.
pub(crate) struct Impersonation;

impl Impersonation {
    /// Starts impersonating on the calling thread.
    pub(crate) fn start() -> Self {
        // SAFETY: `ImpersonateSelf` takes only an impersonation level.
        let ok = unsafe { ImpersonateSelf(SecurityImpersonation) };
        assert_ne!(ok, 0, "ImpersonateSelf failed");
        Self
    }
}

impl Drop for Impersonation {
    fn drop(&mut self) {
        // SAFETY: `RevertToSelf` takes no arguments.
        unsafe { RevertToSelf() };
    }
}

/// The string SID of the user running the tests.
pub(crate) fn current_user() -> String {
    sid_string_of(&EffectiveToken::open().unwrap().user().unwrap())
}

/// The string form of the SID of `user`.
pub(in crate::formats) fn sid_string_of(user: &TokenUser) -> String {
    // SAFETY: `user` owns a valid SID.
    unsafe { sid_to_string(user.sid()) }.unwrap()
}

/// The string form of `sid`.
///
/// # Safety
///
/// `sid` must point at a valid SID.
unsafe fn sid_to_string(sid: *mut std::ffi::c_void) -> io::Result<String> {
    let mut slot = MaybeUninit::<*mut u16>::uninit();
    // SAFETY: the caller guarantees `sid` is a valid SID, and `slot` is valid
    // for writes.
    win32(unsafe { ConvertSidToStringSidW(sid, slot.as_mut_ptr()) })?;
    // SAFETY: the call succeeded, so it wrote the string pointer to `slot`.
    let text = NonNull::new(unsafe { slot.assume_init() })
        .ok_or_else(|| io::Error::from(io::ErrorKind::InvalidData))?;
    let parsed = String::from_utf16(&wide_text(text.as_ptr()))
        .map_err(|_| io::Error::from(io::ErrorKind::InvalidData));
    // SAFETY: `text` was allocated by `ConvertSidToStringSidW` with
    // `LocalAlloc`, the copy above no longer reads it, and it is freed once.
    unsafe { LocalFree(text.as_ptr().cast()) };
    parsed
}

/// A copy of the NUL-terminated UTF-16 string at `text`, without the NUL.
fn wide_text(text: *const u16) -> Vec<u16> {
    // SAFETY: the callers pass a NUL-terminated string the OS allocated, so
    // every offset up to the NUL is readable.
    unsafe {
        let mut len = 0;
        while *text.add(len) != 0 {
            len += 1;
        }
        std::slice::from_raw_parts(text, len).to_vec()
    }
}

/// Reads the DACL of the file or directory at `path`, following a link there.
pub(crate) fn read(path: &Path) -> Dacl {
    read_with(path, FILE_FLAG_BACKUP_SEMANTICS)
}

/// Reads the DACL of the entry at `path` itself, without following a link.
pub(crate) fn read_itself(path: &Path) -> Dacl {
    read_with(
        path,
        FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
    )
}

fn read_with(path: &Path, flags: u32) -> Dacl {
    let file = OpenOptions::new()
        .access_mode(READ_CONTROL)
        .custom_flags(flags)
        .open(path)
        .unwrap();
    let mut acl: *mut ACL = null_mut();
    let mut descriptor: PSECURITY_DESCRIPTOR = null_mut();
    // SAFETY: the handle is live, and the owner, group and SACL out-pointers
    // are null because only the DACL is requested; `acl` and `descriptor` are
    // valid for writes.
    let code = unsafe {
        GetSecurityInfo(
            file.as_raw_handle(),
            SE_FILE_OBJECT,
            DACL_SECURITY_INFORMATION,
            null_mut(),
            null_mut(),
            &raw mut acl,
            null_mut(),
            &raw mut descriptor,
        )
    };
    assert_eq!(code, ERROR_SUCCESS, "GetSecurityInfo failed");
    let control = control(descriptor);
    let dacl = Dacl {
        protected: control & SE_DACL_PROTECTED != 0,
        auto_inherited: control & SE_DACL_AUTO_INHERITED != 0,
        null: acl.is_null(),
        aces: entries(acl).unwrap(),
    };
    // SAFETY: `descriptor` was allocated by `GetSecurityInfo` with
    // `LocalAlloc`, and `acl` points into it and is no longer used.
    unsafe { LocalFree(descriptor) };
    dacl
}

/// Replaces the DACL of the directory `path` with a protected one holding a
/// single, non-inheritable entry that grants the current user full access, so
/// that children created below it inherit nothing.
pub(crate) fn restrict_to_current_user_without_inheritance(path: &Path) {
    use std::os::windows::ffi::OsStrExt;

    let mut sid = MaybeUninit::<*mut std::ffi::c_void>::uninit();
    let text: Vec<u16> = current_user()
        .encode_utf16()
        .chain(std::iter::once(0))
        .collect();
    // SAFETY: `text` is NUL-terminated and `sid` is valid for writes.
    let ok = unsafe { ConvertStringSidToSidW(text.as_ptr(), sid.as_mut_ptr()) };
    assert_ne!(ok, 0, "ConvertStringSidToSidW failed");
    // SAFETY: the call succeeded, so it wrote the SID pointer to `sid`.
    let sid = unsafe { sid.assume_init() };

    // Room for the header, one entry and a SID of the maximum length.
    let mut acl = [0_u32; 32];
    // SAFETY: `acl` is writable, 4-aligned and exactly the length passed.
    let ok = unsafe {
        InitializeAcl(
            acl.as_mut_ptr().cast(),
            u32::try_from(size_of_val(&acl)).unwrap(),
            ACL_REVISION,
        )
    };
    assert_ne!(ok, 0, "InitializeAcl failed");
    // SAFETY: `acl` was initialized above with room for the entry, and `sid`
    // is a valid SID.
    let ok = unsafe {
        AddAccessAllowedAceEx(
            acl.as_mut_ptr().cast(),
            ACL_REVISION,
            0,
            FILE_ALL_ACCESS,
            sid,
        )
    };
    assert_ne!(ok, 0, "AddAccessAllowedAceEx failed");

    let name: Vec<u16> = path
        .as_os_str()
        .encode_wide()
        .chain(std::iter::once(0))
        .collect();
    // SAFETY: `name` is NUL-terminated, the owner, group and SACL are null
    // because only the DACL is selected, and `acl` is a valid ACL that outlives
    // the call.
    let code = unsafe {
        SetNamedSecurityInfoW(
            name.as_ptr(),
            SE_FILE_OBJECT,
            DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION,
            null_mut(),
            null_mut(),
            acl.as_ptr().cast(),
            std::ptr::null(),
        )
    };
    // SAFETY: `sid` was allocated by `ConvertStringSidToSidW` with `LocalAlloc`
    // and is no longer used.
    unsafe { LocalFree(sid) };
    assert_eq!(code, ERROR_SUCCESS, "SetNamedSecurityInfoW failed");
    let dacl = read(path);
    assert!(
        dacl.aces.iter().all(|ace| !ace.inheritable()),
        "the fixture parent still has inheritable entries: {:?}",
        dacl.aces
    );
}

/// Sets the DACL of the directory `path` from the SDDL string `sddl`, with the
/// protection its `P` flag says; `D:NO_ACCESS_CONTROL` gives a null DACL.
pub(crate) fn set_dacl_from_sddl(path: &Path, sddl: &str) {
    use std::os::windows::ffi::OsStrExt;

    let descriptor = parse_sddl(sddl);
    let mut present = 0;
    let mut defaulted = 0;
    let mut acl: *mut ACL = null_mut();
    // SAFETY: `descriptor` is valid, and the three out-pointers are valid for
    // writes.
    let ok = unsafe {
        GetSecurityDescriptorDacl(
            descriptor,
            &raw mut present,
            &raw mut acl,
            &raw mut defaulted,
        )
    };
    assert_ne!(ok, 0, "GetSecurityDescriptorDacl failed");
    let protection = if control(descriptor) & SE_DACL_PROTECTED == 0 {
        UNPROTECTED_DACL_SECURITY_INFORMATION
    } else {
        PROTECTED_DACL_SECURITY_INFORMATION
    };
    let name: Vec<u16> = path
        .as_os_str()
        .encode_wide()
        .chain(std::iter::once(0))
        .collect();
    // SAFETY: `name` is NUL-terminated, the owner, group and SACL are null
    // because only the DACL is selected, and `acl` is null or points into
    // `descriptor`, which outlives the call.
    let code = unsafe {
        SetNamedSecurityInfoW(
            name.as_ptr(),
            SE_FILE_OBJECT,
            DACL_SECURITY_INFORMATION | protection,
            null_mut(),
            null_mut(),
            acl,
            std::ptr::null(),
        )
    };
    // SAFETY: `descriptor` was allocated by the conversion with `LocalAlloc`
    // and is no longer used.
    unsafe { LocalFree(descriptor) };
    assert_eq!(code, ERROR_SUCCESS, "SetNamedSecurityInfoW failed");
}

/// The descriptor `sddl` describes, allocated with `LocalAlloc`; the caller
/// frees it.
fn parse_sddl(sddl: &str) -> PSECURITY_DESCRIPTOR {
    let text: Vec<u16> = sddl.encode_utf16().chain(std::iter::once(0)).collect();
    let mut descriptor: PSECURITY_DESCRIPTOR = null_mut();
    // SAFETY: `text` is NUL-terminated, `descriptor` is valid for writes and
    // the size out-pointer is null, which the API allows.
    let ok = unsafe {
        ConvertStringSecurityDescriptorToSecurityDescriptorW(
            text.as_ptr(),
            SDDL_REVISION_1,
            &raw mut descriptor,
            null_mut(),
        )
    };
    assert_ne!(ok, 0, "the SDDL string {sddl} does not parse");
    descriptor
}

/// The DACL of the valid `descriptor` as an SDDL string.
pub(crate) fn dacl_sddl_of(descriptor: *const std::ffi::c_void) -> String {
    let mut text: *mut u16 = null_mut();
    // SAFETY: `descriptor` is a valid descriptor, `text` is valid for writes
    // and the length out-pointer is null, which the API allows.
    let ok = unsafe {
        ConvertSecurityDescriptorToStringSecurityDescriptorW(
            descriptor.cast_mut(),
            SDDL_REVISION_1,
            DACL_SECURITY_INFORMATION,
            &raw mut text,
            null_mut(),
        )
    };
    assert_ne!(
        ok, 0,
        "ConvertSecurityDescriptorToStringSecurityDescriptorW failed"
    );
    let sddl = String::from_utf16(&wide_text(text)).unwrap();
    // SAFETY: `text` is no longer used and is freed once.
    unsafe { LocalFree(text.cast()) };
    sddl
}

/// `sddl` as the OS writes it back after parsing: SID aliases such as `SY` and
/// the order of flags no longer depend on how the string was spelled.
pub(crate) fn normalized_sddl(sddl: &str) -> String {
    let descriptor = parse_sddl(sddl);
    let normalized = dacl_sddl_of(descriptor);
    // SAFETY: `descriptor` was allocated by the parse with `LocalAlloc` and is
    // no longer used.
    unsafe { LocalFree(descriptor) };
    normalized
}

fn control(descriptor: PSECURITY_DESCRIPTOR) -> u16 {
    let mut control = 0_u16;
    let mut revision = 0_u32;
    // SAFETY: `descriptor` is a valid descriptor and both out-pointers are
    // valid for writes.
    let ok =
        unsafe { GetSecurityDescriptorControl(descriptor, &raw mut control, &raw mut revision) };
    assert_ne!(ok, 0, "GetSecurityDescriptorControl failed");
    control
}

fn entries(acl: *const ACL) -> io::Result<Vec<Ace>> {
    if acl.is_null() {
        return Ok(Vec::new());
    }
    let mut size = ACL_SIZE_INFORMATION::default();
    // SAFETY: `acl` is a valid ACL, and `size` is writable and of exactly the
    // length passed.
    let ok = unsafe {
        GetAclInformation(
            acl,
            (&raw mut size).cast(),
            u32::try_from(size_of::<ACL_SIZE_INFORMATION>()).unwrap(),
            AclSizeInformation,
        )
    };
    win32(ok)?;
    (0..size.AceCount).map(|index| entry(acl, index)).collect()
}

fn entry(acl: *const ACL, index: u32) -> io::Result<Ace> {
    let mut slot = MaybeUninit::uninit();
    // SAFETY: `acl` is a valid ACL, `index` is below its entry count, and
    // `slot` is valid for writes.
    win32(unsafe { GetAce(acl, index, slot.as_mut_ptr()) })?;
    // SAFETY: `GetAce` returned non-zero, so it wrote the entry pointer to
    // `slot`.
    let ace = NonNull::new(unsafe { slot.assume_init() })
        .ok_or_else(|| io::Error::from(io::ErrorKind::InvalidData))?;
    // SAFETY: `ace` points at a live entry; every entry starts with an
    // `ACE_HEADER`.
    let header = unsafe { ace.as_ptr().cast::<ACE_HEADER>().read_unaligned() };
    let allows = header.AceType == ACCESS_ALLOWED_ACE_TYPE;
    Ok(Ace {
        allows,
        flags: header.AceFlags,
        mask: if allows {
            // SAFETY: the entry is an `ACCESS_ALLOWED_ACE` (checked above), so
            // its mask is inside the entry.
            unsafe {
                ace.as_ptr()
                    .cast::<u8>()
                    .add(offset_of!(ACCESS_ALLOWED_ACE, Mask))
                    .cast::<u32>()
                    .read_unaligned()
            }
        } else {
            0
        },
        sid: if allows {
            // SAFETY: the entry is an `ACCESS_ALLOWED_ACE` (checked above), so
            // its SID starts at `SidStart`, inside the entry.
            let sid = unsafe {
                ace.as_ptr()
                    .cast::<u8>()
                    .add(offset_of!(ACCESS_ALLOWED_ACE, SidStart))
            };
            // SAFETY: `sid` points at the entry's SID, and the ACL outlives the
            // call.
            unsafe { sid_to_string(sid.cast())? }
        } else {
            String::new()
        },
    })
}