summaryrefslogtreecommitdiffstats
path: root/src/meta/windows_utils.rs
blob: e647c26a521b83c437b97733922dd5765f4786de (plain)
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
use std::ffi::{OsStr, OsString};
use std::io;
use std::mem::MaybeUninit;
use std::os::windows::ffi::{OsStrExt, OsStringExt};
use std::path::Path;

use windows::Win32::Foundation::PSID;
use windows::Win32::Security::{self, Authorization::TRUSTEE_W, ACL};

use super::{Owner, Permissions};

const BUF_SIZE: u32 = 256;

pub fn get_file_data(path: &Path) -> Result<(Owner, Permissions), io::Error> {
    // Overall design:
    // This function allocates some data with GetNamedSecurityInfoW,
    // manipulates it only through WinAPI calls (treating the pointers as
    // opaque) and then frees it at the end with LocalFree.
    //
    // For memory safety, the critical things are:
    // - No pointer is valid before the return value of GetNamedSecurityInfoW
    //   is checked
    // - LocalFree must be called before returning
    // - No pointer is valid after the call to LocalFree

    let windows_path = buf_from_os(path.as_os_str());

    // These pointers will be populated by GetNamedSecurityInfoW
    // sd_ptr points at a new buffer that must be freed
    // The others point at (opaque) things inside that buffer
    let mut owner_sid_ptr = MaybeUninit::uninit();
    let mut group_sid_ptr = MaybeUninit::uninit();
    let mut dacl_ptr = MaybeUninit::uninit();
    let mut sd_ptr = MaybeUninit::uninit();

    // Assumptions:
    // - windows_path is a null-terminated WTF-16-encoded string
    // - The return value is checked against ERROR_SUCCESS before pointers are used
    // - All pointers are opaque and should only be used with WinAPI calls
    // - Pointers are only valid if their corresponding X_SECURITY_INFORMATION
    //   flags are set
    // - sd_ptr must be freed with LocalFree
    let error_code = unsafe {
        Security::Authorization::GetNamedSecurityInfoW(
            windows::core::PCWSTR::from_raw(windows_path.as_ptr()),
            Security::Authorization::SE_FILE_OBJECT,
            Security::OWNER_SECURITY_INFORMATION
                | Security::GROUP_SECURITY_INFORMATION
                | Security::DACL_SECURITY_INFORMATION,
            Some(owner_sid_ptr.as_mut_ptr()),
            Some(group_sid_ptr.as_mut_ptr()),
            Some(dacl_ptr.as_mut_ptr()),
            None,
            sd_ptr.as_mut_ptr(),
        )
    };

    if error_code.is_err() {
        return Err(std::io::Error::from_raw_os_error(error_code.0 as i32));
    }

    // Assumptions:
    // - owner_sid_ptr is valid
    // - group_sid_ptr is valid
    // (both OK because GetNamedSecurityInfoW returned success)
    let owner_sid_ptr = unsafe { owner_sid_ptr.assume_init() };
    let group_sid_ptr = unsafe { group_sid_ptr.assume_init() };
    let dacl_ptr = unsafe { dacl_ptr.assume_init() };
    let sd_ptr = unsafe { sd_ptr.assume_init() };

    let owner = match unsafe { lookup_account_sid(owner_sid_ptr) } {
        Ok((n, d)) => {
            let owner_name = os_from_buf(&n);
            let owner_domain = os_from_buf(&d);

            format!(
                "{}\\{}",
                owner_domain.to_string_lossy(),
                &owner_name.to_string_lossy()
            )
        }
        Err(_) => String::from("-"),
    };

    let group = match unsafe { lookup_account_sid(group_sid_ptr) } {
        Ok((n, d)) => {
            let group_name = os_from_buf(&n);
            let group_domain = os_from_buf(&d);

            format!(
                "{}\\{}",
                group_domain.to_string_lossy(),
                &group_name.to_string_lossy()
            )
        }
        Err(_) => String::from("-"),
    };

    // This structure will be returned
    let owner = Owner::new(owner, group);

    // Get the size and allocate bytes for a 1-sub-authority SID
    // 1 sub-authority because the Windows World SID is always S-1-1-0, with
    // only a single sub-authority.
    //
    // Assumptions: None
    // "This function cannot fail"
    //     -- Windows Dev Center docs
    let mut world_sid_len: u32 = unsafe { Security::GetSidLengthRequired(1) };
    let mut world_sid = vec![0u8; world_sid_len as usize];
    let world_sid_ptr = PSID(world_sid.as_mut_ptr() as *mut _);

    // Assumptions:
    // - world_sid_len is no larger than the number of bytes available at
    //   world_sid
    // - world_sid is appropriately aligned (if there are strange crashes this
    //   might be why)
    let result = unsafe {
        Security::CreateWellKnownSid(
            Security::WinWorldSid,
            PSID::default(),
            world_sid_ptr,
            &mut world_sid_len,
        )
    };

    if result.ok().is_err() {
        // Failed to create the SID
        // Assumptions: Same as the other identical calls
        unsafe {
            windows::Win32::System::Memory::LocalFree(sd_ptr.0 as _);
        }

        // Assumptions: None (GetLastError shouldn't ever fail)
        return Err(io::Error::from_raw_os_error(unsafe {
            windows::Win32::Foundation::GetLastError().0
        } as i32));
    }

    // Assumptions:
    // - xxxxx_sid_ptr are valid pointers to SIDs
    // - xxxxx_trustee is only valid as long as its SID pointer is
    let owner_trustee = unsafe { trustee_from_sid(owner_sid_ptr) };
    let group_trustee = unsafe { trustee_from_sid(group_sid_ptr) };
    let world_trustee = unsafe { trustee_from_sid(world_sid_ptr) };

    // Assumptions:
    // - xxxxx_trustee are still valid (including underlying SID)
    // - dacl_ptr is still valid
    let owner_access_mask = unsafe { get_acl_access_mask(dacl_ptr, &owner_trustee) }?;

    let group_access_mask = unsafe { get_acl_access_mask(dacl_ptr, &group_trustee) }?;

    let world_access_mask = unsafe { get_acl_access_mask(dacl_ptr, &world_trustee) }?;

    let permissions = {
        use windows::Win32::Storage::FileSystem::{
            FILE_ACCESS_FLAGS, FILE_GENERIC_EXECUTE, FILE_GENERIC_READ, FILE_GENERIC_WRITE,
        };
        let has_bit = |field: u32, bit: FILE_ACCESS_FLAGS| field & bit.0 != 0;
        Permissions {
            user_read: has_bit(owner_access_mask, FILE_GENERIC_READ),
            user_write: has_bit(owner_access_mask, FILE_GENERIC_WRITE),
            user_execute: has_bit(owner_access_mask, FILE_GENERIC_EXECUTE),

            group_read: has_bit(group_access_mask, FILE_GENERIC_READ),
            group_write: has_bit(group_access_mask, FILE_GENERIC_WRITE),
            group_execute: has_bit(group_access_mask, FILE_GENERIC_EXECUTE),

            other_read: has_bit(world_access_mask, FILE_GENERIC_READ),
            other_write: has_bit(world_access_mask, FILE_GENERIC_WRITE),
            other_execute: has_bit(world_access_mask, FILE_GENERIC_EXECUTE),

            sticky: false,
            setuid: false,
            setgid: false,
        }
    };

    // Assumptions:
    // - sd_ptr was previously allocated with WinAPI functions
    // - All pointers into the memory are now invalid
    // - The free succeeds (currently unchecked -- there's no real recovery
    //   options. It's not much memory, so leaking it on failure is
    //   *probably* fine)
    unsafe {
        windows::Win32::System::Memory::LocalFree(sd_ptr.0 as _);
    }

    Ok((owner, permissions))
}

/// Evaluate an ACL for a particular trustee and get its access rights
///
/// Assumptions:
/// - acl_ptr points to a valid ACL data structure
/// - trustee_ptr points to a valid trustee data structure
/// - Both remain valid through the function call (no long-term requirement)
unsafe fn get_acl_access_mask(
    acl_ptr: *const ACL,
    trustee_ptr: *const TRUSTEE_W,
) -> Result<u32, io::Error> {
    let mut access_mask = 0;

    // Assumptions:
    // - All function assumptions
    // - Result is not valid until return value is checked
    let err_code =
        Security::Authorization::GetEffectiveRightsFromAclW(acl_ptr, trustee_ptr, &mut access_mask);

    if err_code.is_ok() {
        Ok(access_mask)
    } else {
        Err(io::Error::from_raw_os_error(err_code.0 as i32))
    }
}

/// Get a trustee buffer from a SID
///
/// Assumption: sid is valid, and the trustee is only valid as long as the SID
/// is
///
/// Note: winapi's TRUSTEE_W looks different from the one in the MS docs because
/// of some unusual pre-processor macros in the original .h file. The winapi
/// version is correct (MS's doc generator messed up)
unsafe fn trustee_from_sid<P: Into<PSID>>(sid_ptr: P) -> TRUSTEE_W {
    let mut trustee = TRUSTEE_W::default();

    Security::Authorization::BuildTrusteeWithSidW(&mut trustee, sid_ptr);

    trustee
}

/// Get a username and domain name from a SID
///
/// Assumption: sid is a valid pointer that remains valid through the entire
/// function execution
///
/// Returns null-terminated Vec's, one for the name and one for the domain.
unsafe fn lookup_account_sid(sid: PSID) -> Result<(Vec<u16>, Vec<u16>), std::io::Error> {
    let mut name_size: u32 = BUF_SIZE;
    let mut domain_size: u32 = BUF_SIZE;

    loop {
        let mut name: Vec<u16> = vec![0; name_size as usize];
        let mut domain: Vec<u16> = vec![0; domain_size as usize];

        let old_name_size = name_size;
        let old_domain_size = domain_size;

        let mut sid_name_use = MaybeUninit::uninit();

        // Assumptions:
        // - sid is a valid pointer to a SID data structure
        // - name_size and domain_size accurately reflect the sizes
        let result = Security::LookupAccountSidW(
            None,
            sid,
            windows::core::PWSTR(name.as_mut_ptr()),
            &mut name_size,
            windows::core::PWSTR(domain.as_mut_ptr()),