[go: up one dir, main page]

windows-acl 0.3.0

Rust crate to simplify Windows ACL operations
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
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
#![cfg(windows)]

use acl::{ACLEntry, AceType, ACL};
use std::env::current_exe;
use std::fs::{File, OpenOptions};
use std::os::windows::fs::OpenOptionsExt;
use std::os::windows::io::AsRawHandle;
use std::path::PathBuf;
use std::process::Command;
use std::sync::Once;
use utils::{current_user, name_to_sid, sid_to_string, string_to_sid};
use winapi::ctypes::c_void;
use winapi::shared::winerror::ERROR_NOT_ALL_ASSIGNED;
use winapi::um::winnt::{
    FAILED_ACCESS_ACE_FLAG, FILE_ALL_ACCESS, FILE_GENERIC_EXECUTE, FILE_GENERIC_READ,
    FILE_GENERIC_WRITE, GENERIC_READ, GENERIC_WRITE, PSID, SUCCESSFUL_ACCESS_ACE_FLAG, SYNCHRONIZE,
    SYSTEM_MANDATORY_LABEL_NO_EXECUTE_UP, SYSTEM_MANDATORY_LABEL_NO_READ_UP,
    SYSTEM_MANDATORY_LABEL_NO_WRITE_UP, WRITE_DAC,
};

static START: Once = Once::new();

fn support_path() -> Option<PathBuf> {
    if let Ok(mut path) = current_exe() {
        for _ in 0..6 {
            path.pop();

            path.push("support");

            if path.exists() {
                path.push("testfiles");
                return Some(path);
            }

            path.pop();
        }
    } else {
        assert!(false, "current_exe failed");
    }

    None
}

fn run_ps_script(file_name: &str) -> bool {
    if let Some(mut path) = support_path() {
        path.pop();
        path.push(file_name);

        if let Some(script_path) = path.to_str() {
            let mut process = match Command::new("PowerShell.exe")
                .args(&["-ExecutionPolicy", "bypass", "-File", script_path])
                .spawn()
            {
                Ok(process) => process,
                _ => {
                    return false;
                }
            };

            match process.wait() {
                Ok(_code) => {
                    return true;
                }
                Err(_code) => {
                    return false;
                }
            }
        }
    }

    false
}

fn string_sid_by_user(user: &str) -> String {
    let user_sid = name_to_sid(user, None).unwrap_or(Vec::new());
    assert_ne!(user_sid.len(), 0);

    let user_string_sid = sid_to_string(user_sid.as_ptr() as PSID).unwrap_or(String::from(""));
    assert_ne!(user_string_sid.len(), 0);

    user_string_sid
}

fn current_user_string_sid() -> String {
    let username = current_user().unwrap_or(String::from(""));
    assert_ne!(username.len(), 0);

    string_sid_by_user(&username)
}

#[test]
fn lookupname_unit_test() {
    let world_name = "Everyone";
    let world_string_sid = "S-1-1-0";

    let raw_world_sid = name_to_sid(world_name, None).unwrap_or(Vec::new());
    assert_ne!(raw_world_sid.len(), 0);

    let sid_string = sid_to_string(raw_world_sid.as_ptr() as PSID).unwrap_or(String::from(""));
    assert_ne!(sid_string.len(), 0);

    assert_eq!(sid_string, world_string_sid);
}

#[test]
fn sidstring_unit_test() {
    let world_string_sid = "S-1-5-21";

    let sid = string_to_sid(world_string_sid).unwrap_or(Vec::new());
    assert_ne!(sid.len(), 0);

    let sid_string = sid_to_string(sid.as_ptr() as PSID).unwrap_or(String::from(""));
    assert_ne!(sid_string.len(), 0);

    assert_eq!(sid_string, world_string_sid);
}

fn acl_entry_exists(entries: &Vec<ACLEntry>, expected: &ACLEntry) -> Option<usize> {
    for i in 0..(entries.len()) {
        let entry = &entries[i];

        if entry.entry_type == expected.entry_type
            && entry.string_sid == expected.string_sid
            && entry.flags == expected.flags
            && entry.mask == expected.mask
        {
            return Some(i);
        }
    }

    None
}

// Make sure we can read DACL entries set by an external tool (PowerShell)
#[test]
fn query_dacl_unit_test() {
    START.call_once(|| {
        assert!(run_ps_script("setup_acl_test.ps1"));
    });

    let guest_sid = string_sid_by_user("Guest");
    let current_user_sid = current_user_string_sid();

    let mut path_obj = support_path().unwrap_or(PathBuf::new());
    path_obj.push("query_test");
    assert!(path_obj.exists());

    let path = path_obj.to_str().unwrap_or("");
    assert_ne!(path.len(), 0);

    let acl_result = ACL::from_file_path(path, false);
    assert!(acl_result.is_ok());

    let acl = acl_result.unwrap();
    let entries = acl.all().unwrap_or(Vec::new());
    assert_ne!(entries.len(), 0);

    let mut expected = ACLEntry::new();
    expected.entry_type = AceType::AccessDeny;
    expected.string_sid = guest_sid;
    expected.flags = 0;
    expected.mask = (FILE_GENERIC_READ | FILE_GENERIC_EXECUTE) & !SYNCHRONIZE;

    let deny_idx = match acl_entry_exists(&entries, &expected) {
        Some(i) => i,
        None => {
            println!("Expected AccessDeny entry does not exist!");
            assert!(false);
            return;
        }
    };

    expected.entry_type = AceType::AccessAllow;
    expected.string_sid = current_user_sid;
    expected.flags = 0;

    // NOTE(andy): For ACL entries added by CmdLets on files, SYNCHRONIZE is not set
    expected.mask = FILE_ALL_ACCESS;

    let allow_idx = match acl_entry_exists(&entries, &expected) {
        Some(i) => i,
        None => {
            println!("Expected AccessAllow entry does not exist!");
            assert!(false);
            return;
        }
    };

    assert!(deny_idx < allow_idx);
}

// Make sure we can read SACL entries set by external tools (PowerShell/.NET)
#[test]
fn query_sacl_unit_test() {
    START.call_once(|| {
        assert!(run_ps_script("setup_acl_test.ps1"));
    });

    let world_sid = string_sid_by_user("Everyone");

    let mut path_obj = support_path().unwrap_or(PathBuf::new());
    path_obj.push("query_sacl_test");
    assert!(path_obj.exists());

    let path = path_obj.to_str().unwrap_or("");
    assert_ne!(path.len(), 0);

    let acl = match ACL::from_file_path(path, true) {
        Ok(obj) => obj,
        Err(code) => {
            assert_eq!(code, ERROR_NOT_ALL_ASSIGNED);
            println!("INFO: Terminating query_sacl_unit_test early because we are not Admin.");
            return;
        }
    };

    let entries = acl.all().unwrap_or(Vec::new());
    assert_ne!(entries.len(), 0);

    let mut expected = ACLEntry::new();
    expected.entry_type = AceType::SystemAudit;
    expected.string_sid = world_sid;
    expected.flags = SUCCESSFUL_ACCESS_ACE_FLAG | FAILED_ACCESS_ACE_FLAG;
    expected.mask = (FILE_GENERIC_READ | FILE_GENERIC_WRITE) & !SYNCHRONIZE;

    let allow_idx = match acl_entry_exists(&entries, &expected) {
        Some(i) => i,
        None => {
            println!("Expected SystemAudit entry does not exist!");
            assert!(false);
            return;
        }
    };

    assert!(allow_idx > 0);
}

// Ensure that we can add and remove DACL access allow entries
fn add_and_remove_dacl_allow(use_handle: bool) {
    START.call_once(|| {
        assert!(run_ps_script("setup_acl_test.ps1"));
    });

    let current_user = current_user_string_sid();
    let current_user_sid = match string_to_sid(&current_user) {
        Ok(x) => x,
        Err(x) => {
            println!("string_to_sid failed for {}: GLE={}", current_user, x);
            assert_eq!(x, 0);
            return;
        }
    };

    let mut path_obj = support_path().unwrap_or(PathBuf::new());
    path_obj.push(if use_handle {
        "dacl_allow_handle"
    } else {
        "dacl_allow_file"
    });
    assert!(path_obj.exists());

    let path = path_obj.to_str().unwrap_or("");
    assert_ne!(path.len(), 0);

    // NOTE(andy): create() opens for write only or creates new if path doesn't exist. Since we know
    //             that the path exists (see line 257), this will attempt to open for write, which
    //             should fail
    assert!(File::create(path).is_err());
    let file: File;

    let acl_result = if use_handle {
        file = OpenOptions::new()
            .access_mode(GENERIC_READ | WRITE_DAC)
            .open(path)
            .unwrap();
        ACL::from_file_handle(file.as_raw_handle() as *mut c_void, false)
    } else {
        ACL::from_file_path(path, false)
    };
    assert!(acl_result.is_ok());

    let mut acl = acl_result.unwrap();

    match acl.allow(
        current_user_sid.as_ptr() as PSID,
        false,
        FILE_GENERIC_READ | FILE_GENERIC_WRITE,
    ) {
        Ok(x) => assert!(x),
        Err(x) => {
            println!(
                "ACL.allow failed for adding allow ACE for {} to FILE_GENERIC_READ: GLE={}",
                &current_user, x
            );
            assert!(false);
            return;
        }
    }

    // NOTE(andy): Our explicit allow entry should make this pass now
    assert!(File::create(path).is_ok());

    let mut entries = acl.all().unwrap_or(Vec::new());
    assert_ne!(entries.len(), 0);

    let mut expected = ACLEntry::new();
    expected.entry_type = AceType::AccessAllow;
    expected.string_sid = current_user.to_string();
    expected.flags = 0;
    expected.mask = FILE_GENERIC_READ | FILE_GENERIC_WRITE;

    match acl_entry_exists(&entries, &expected) {
        Some(_i) => {}
        None => {
            println!("Expected AccessAllow entry does not exist!");
            assert!(false);
            return;
        }
    };

    match acl.remove(
        current_user_sid.as_ptr() as PSID,
        Some(AceType::AccessAllow),
        Some(false),
    ) {
        Ok(x) => assert_eq!(x, 1),
        Err(x) => {
            println!(
                "ACL.remove failed for removing allow ACE for {} to FILE_GENERIC_READ: GLE={}",
                &current_user, x
            );
            assert!(false);
            return;
        }
    }

    assert!(File::create(path).is_err());

    entries = acl.all().unwrap_or(Vec::new());
    assert_ne!(entries.len(), 0);
    match acl_entry_exists(&entries, &expected) {
        None => {}
        Some(i) => {
            println!("Did not expect to find AccessAllow entry at {}", i);
            assert!(false);
            return;
        }
    }
}

#[test]
fn add_and_remove_dacl_allow_path_test() {
    add_and_remove_dacl_allow(false);
}

#[test]
fn add_and_remove_dacl_allow_handle_test() {
    add_and_remove_dacl_allow(true);
}

// Ensure we can add and remove DACL access deny entries
fn add_and_remove_dacl_deny(use_handle: bool) {
    START.call_once(|| {
        assert!(run_ps_script("setup_acl_test.ps1"));
    });

    let current_user = current_user_string_sid();
    let current_user_sid = match string_to_sid(&current_user) {
        Ok(x) => x,
        Err(x) => {
            println!("string_to_sid failed for {}: GLE={}", current_user, x);
            assert_eq!(x, 0);
            return;
        }
    };

    let mut path_obj = support_path().unwrap_or(PathBuf::new());
    path_obj.push(if use_handle {
        "dacl_deny_handle"
    } else {
        "dacl_deny_file"
    });
    assert!(path_obj.exists());

    let path = path_obj.to_str().unwrap_or("");
    assert_ne!(path.len(), 0);

    // NOTE(andy): create() opens for write only or creates new if path doesn't exist. Since we know
    //             that the path exists (see line 375), this will attempt to open for write, which
    //             should succeed
    let create_res = OpenOptions::new()
        .access_mode(GENERIC_WRITE | WRITE_DAC)
        .open(path);
    assert!(create_res.is_ok());
    let file = create_res.unwrap();

    let acl_result = if use_handle {
        ACL::from_file_handle(file.as_raw_handle() as *mut c_void, false)
    } else {
        ACL::from_file_path(path, false)
    };
    assert!(acl_result.is_ok());

    let mut acl = acl_result.unwrap();
    match acl.deny(current_user_sid.as_ptr() as PSID, false, FILE_GENERIC_WRITE) {
        Ok(x) => assert!(x),
        Err(x) => {
            println!(
                "ACL.deny failed for adding allow ACE for {} to FILE_GENERIC_READ: GLE={}",
                current_user, x
            );
            assert!(false);
            return;
        }
    }

    // NOTE(andy): Since we added a deny entry for WRITE, this should fail
    assert!(File::create(path).is_err());

    let mut entries = acl.all().unwrap_or(Vec::new());
    assert_ne!(entries.len(), 0);

    let mut expected = ACLEntry::new();
    expected.entry_type = AceType::AccessDeny;
    expected.string_sid = current_user.to_string();
    expected.flags = 0;
    expected.mask = FILE_GENERIC_WRITE;

    match acl_entry_exists(&entries, &expected) {
        Some(_i) => {}
        None => {
            println!("Expected AccessDeny entry does not exist!");
            assert!(false);
            return;
        }
    }

    match acl.remove(
        current_user_sid.as_ptr() as PSID,
        Some(AceType::AccessDeny),
        Some(false),
    ) {
        Ok(x) => assert_eq!(x, 1),
        Err(x) => {
            println!(
                "ACL.remove failed for removing deny ACE for {} to FILE_GENERIC_READ: GLE={}",
                current_user, x
            );
            assert!(false);
            return;
        }
    }

    assert!(File::open(path).is_ok());

    entries = acl.all().unwrap_or(Vec::new());
    assert_ne!(entries.len(), 0);

    match acl_entry_exists(&entries, &expected) {
        None => {}
        Some(i) => {
            println!("AccessDeny unexpectedly exists at {}", i);
            assert!(false);
            return;
        }
    }
}

#[test]
fn add_and_remove_dacl_deny_path_test() {
    add_and_remove_dacl_deny(false);
}

#[test]
fn add_and_remove_dacl_deny_handle_test() {
    add_and_remove_dacl_deny(true);
}

// Ensure we can add and remove a SACL mandatory level entry
#[test]
fn add_remove_sacl_mil() {
    START.call_once(|| {
        assert!(run_ps_script("setup_acl_test.ps1"));
    });

    let low_mil_string_sid = "S-1-16-4096";
    let low_mil_sid = match string_to_sid(&low_mil_string_sid) {
        Ok(x) => x,
        Err(x) => {
            println!("string_to_sid failed for {}: GLE={}", low_mil_string_sid, x);
            assert_eq!(x, 0);
            return;
        }
    };

    let mut path_obj = support_path().unwrap_or(PathBuf::new());
    path_obj.push("sacl_mil_file");
    assert!(path_obj.exists());

    let path = path_obj.to_str().unwrap_or("");
    assert_ne!(path.len(), 0);

    let acl_result = ACL::from_file_path(path, true);
    assert!(acl_result.is_ok());

    let mut acl = acl_result.unwrap();
    match acl.integrity_level(
        low_mil_sid.as_ptr() as PSID,
        false,
        SYSTEM_MANDATORY_LABEL_NO_WRITE_UP
            | SYSTEM_MANDATORY_LABEL_NO_READ_UP
            | SYSTEM_MANDATORY_LABEL_NO_EXECUTE_UP,
    ) {
        Ok(x) => assert!(x),
        Err(x) => {
            println!(
                "ACL.integrity_level failed for {}: GLE={}",
                &low_mil_string_sid, x
            );
            assert!(false);
            return;
        }
    }

    let mut entries = acl.all().unwrap_or(Vec::new());
    assert_ne!(entries.len(), 0);

    let mut expected = ACLEntry::new();
    expected.entry_type = AceType::SystemMandatoryLabel;
    expected.string_sid = low_mil_string_sid.to_string();
    expected.flags = 0;
    expected.mask = SYSTEM_MANDATORY_LABEL_NO_EXECUTE_UP
        | SYSTEM_MANDATORY_LABEL_NO_READ_UP
        | SYSTEM_MANDATORY_LABEL_NO_WRITE_UP;

    assert!(acl_entry_exists(&entries, &expected).is_some());

    match acl.remove(
        low_mil_sid.as_ptr() as PSID,
        Some(AceType::SystemMandatoryLabel),
        Some(false),
    ) {
        Ok(x) => assert_eq!(x, 1),
        Err(x) => {
            println!(
                "ACL.remove failed for removing mandatory ACE for {}: GLE={}",
                low_mil_string_sid, x
            );
            assert!(false);
            return;
        }
    }

    entries = acl.all().unwrap_or(Vec::new());
    assert_ne!(entries.len(), 0);

    assert!(acl_entry_exists(&entries, &expected).is_none());
}

// Make sure we can add and remove a SACL audit entry
#[test]
fn add_remove_sacl_audit() {
    START.call_once(|| {
        assert!(run_ps_script("setup_acl_test.ps1"));
    });

    let mut path_obj = support_path().unwrap_or(PathBuf::new());
    path_obj.push("sacl_audit_file");
    assert!(path_obj.exists());

    let current_user = current_user_string_sid();
    let current_user_sid = match string_to_sid(&current_user) {
        Ok(x) => x,
        Err(x) => {
            println!("string_to_sid failed for {}: GLE={}", current_user, x);
            assert_eq!(x, 0);
            return;
        }
    };

    let path = path_obj.to_str().unwrap_or("");
    assert_ne!(path.len(), 0);

    let acl_result = ACL::from_file_path(path, true);
    assert!(acl_result.is_ok());

    let mut acl = acl_result.unwrap();
    match acl.audit(
        current_user_sid.as_ptr() as PSID,
        false,
        FILE_GENERIC_READ,
        true,
        true,
    ) {
        Ok(x) => assert!(x),
        Err(x) => {
            println!("ACL.audit failed for {}: GLE={}", &current_user, x);
            assert!(false);
            return;
        }
    }

    let mut entries = acl.all().unwrap_or(Vec::new());
    assert_ne!(entries.len(), 0);

    let mut expected = ACLEntry::new();
    expected.entry_type = AceType::SystemAudit;
    expected.string_sid = current_user.to_string();
    expected.flags = SUCCESSFUL_ACCESS_ACE_FLAG | FAILED_ACCESS_ACE_FLAG;
    expected.mask = FILE_GENERIC_READ;

    assert!(acl_entry_exists(&entries, &expected).is_some());

    match acl.remove(
        current_user_sid.as_ptr() as PSID,
        Some(AceType::SystemAudit),
        Some(false),
    ) {
        Ok(x) => assert_eq!(x, 1),
        Err(x) => {
            println!(
                "ACL.remove failed for removing mandatory ACE for {}: GLE={}",
                &current_user, x
            );
            assert!(false);
            return;
        }
    }

    entries = acl.all().unwrap_or(Vec::new());
    assert_ne!(entries.len(), 0);

    assert!(acl_entry_exists(&entries, &expected).is_none());
}

// Make sure ACL::get and ACL::remove work as we expect
#[test]
fn acl_get_and_remove_test() {
    START.call_once(|| {
        assert!(run_ps_script("setup_acl_test.ps1"));
    });

    let mut path_obj = support_path().unwrap_or(PathBuf::new());
    path_obj.push("acl_get_and_remove");
    assert!(path_obj.exists());

    let guest = string_sid_by_user("Guest");
    let guest_sid = match string_to_sid(&guest) {
        Ok(x) => x,
        Err(x) => {
            println!("string_to_sid failed for {}: GLE={}", guest, x);
            assert_eq!(x, 0);
            return;
        }
    };

    let world = string_sid_by_user("Everyone");
    let world_sid = string_to_sid(&world).unwrap_or(Vec::new());
    assert_ne!(world_sid.len(), 0);

    let path = path_obj.to_str().unwrap_or("");
    assert_ne!(path.len(), 0);

    let acl_result = ACL::from_file_path(path, true);
    assert!(acl_result.is_ok());

    let mut acl = acl_result.unwrap();

    let mut results = acl
        .get(world_sid.as_ptr() as PSID, None)
        .unwrap_or_else(|_x| {
            assert!(false);
            Vec::new()
        });
    assert_eq!(results.len(), 0);

    results = acl
        .get(guest_sid.as_ptr() as PSID, None)
        .unwrap_or(Vec::new());
    assert_eq!(results.len(), 3);

    results = acl
        .get(guest_sid.as_ptr() as PSID, Some(AceType::AccessAllow))
        .unwrap_or(Vec::new());
    assert_eq!(results.len(), 1);

    results = acl
        .get(guest_sid.as_ptr() as PSID, Some(AceType::AccessDeny))
        .unwrap_or(Vec::new());
    assert_eq!(results.len(), 1);

    results = acl
        .get(guest_sid.as_ptr() as PSID, Some(AceType::SystemAudit))
        .unwrap_or(Vec::new());
    assert_eq!(results.len(), 1);

    let mut removed = acl
        .remove(guest_sid.as_ptr() as PSID, Some(AceType::AccessDeny), None)
        .unwrap_or(0);
    assert_eq!(removed, 1);

    results = acl
        .get(guest_sid.as_ptr() as PSID, None)
        .unwrap_or(Vec::new());
    assert_eq!(results.len(), 2);

    removed = acl
        .remove(guest_sid.as_ptr() as PSID, None, None)
        .unwrap_or(0);
    assert_eq!(removed, 2);
}