-
Notifications
You must be signed in to change notification settings - Fork 1
/
XSEC_tests.cpp
1594 lines (1422 loc) · 50.9 KB
/
XSEC_tests.cpp
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
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
XSEC library
Copyright (c) 2021 Yury Strozhevsky <yury@strozhevsky.com>
Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "pch.h"
#include "CppUnitTest.h"
#include "./lib/index.h"
#include <tuple>
#include <filesystem>
#include <authz.h>
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
using namespace XSEC;
//********************************************************************************
std::tuple<BOOL, std::vector<DWORD>, std::vector<DWORD>, std::vector<std::string>> check_access(
const std::wstring name,
const HANDLE& token,
const XSEC::XSD& sd,
DWORD desired_access,
bool zero_mapping = false,
std::optional<std::vector<OBJECT_TYPE_LIST>> object_type_list = std::nullopt,
std::optional<XSEC::XSID> self = std::nullopt
)
{
#pragma region Initial variables
BOOL check_result = FALSE;
PRIVILEGE_SET privileges = { 0 };
DWORD privileges_length = sizeof(privileges);
BOOL GenerateOnClose = FALSE;
GENERIC_MAPPING mapping;
#pragma endregion
#pragma region Set a correct "mapping" values
if(zero_mapping)
mapping = { 0x00 };
else
{
mapping = { 0xFFFFFFFF };
mapping.GenericRead = FILE_GENERIC_READ;
mapping.GenericWrite = FILE_GENERIC_WRITE;
mapping.GenericExecute = FILE_GENERIC_EXECUTE;
mapping.GenericAll = FILE_ALL_ACCESS;
}
#pragma endregion
#pragma region Initialize values related to "object list"
std::vector<OBJECT_TYPE_LIST> object_list_value = object_type_list.value_or(std::vector<OBJECT_TYPE_LIST>{});
GUID zero = { 0x00000000, 0x0000, 0x0000, { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } };
if(object_list_value.size() == 0)
{
// The object list must have at least one element
// identifying the root object itself
object_list_value.push_back({
0,
0,
&zero
});
}
#pragma endregion
#pragma region Initialize "result values"
size_t size = object_list_value.size();
std::vector<DWORD> granted_access(size, 0);
std::vector<DWORD> access_status(size, 0);
#pragma endregion
#pragma region Initialize correct "PrincipalSelf" substitute value
XSEC::bin_t bin_self;
PSID sid_self = NULL;
if(self)
{
bin_self = (XSEC::bin_t)self.value();
sid_self = bin_self.data();
}
#pragma endregion
#pragma region Convert security descriptor into binary format
auto bin = (XSEC::bin_t)sd;
#pragma endregion
#pragma region Make an impersonation token from primary
HANDLE dup_token;
if(FALSE == DuplicateTokenEx(token, MAXIMUM_ALLOWED, nullptr, SecurityDelegation, TokenImpersonation, &dup_token))
throw std::exception("AccessCheck: cannot duplicate token");
#pragma endregion
#pragma region Check access
check_result = AccessCheckByTypeResultListAndAuditAlarmByHandle(
L"XSEC Tests",
nullptr,
dup_token,
L"Test security descriptor",
name.c_str(),
(PSECURITY_DESCRIPTOR)bin.data(),
sid_self,
desired_access,
AuditEventObjectAccess,
AUDIT_ALLOW_NO_PRIVILEGE,
object_list_value.data(),
object_list_value.size(),
&mapping,
FALSE,
granted_access.data(),
access_status.data(),
&GenerateOnClose
);
if(FALSE == check_result)
{
std::stringstream stream;
stream << "AccessCheck: error during a check, #" << GetLastError() << "\n";
throw std::exception(stream.str().c_str());
}
#pragma endregion
std::vector<std::string> granted_access_string;
std::transform(granted_access.begin(), granted_access.end(), std::back_inserter(granted_access_string), [](DWORD value) -> std::string { return std::bitset<32>(value).to_string(); });
return std::make_tuple(check_result, granted_access, access_status, granted_access_string);
}
//********************************************************************************
BOOL WINAPI CheckCallback(AUTHZ_CLIENT_CONTEXT_HANDLE hAuthzClientContext, PACE_HEADER pAce, PVOID pArgs, PBOOL pbAceApplicable)
{
*pbAceApplicable = TRUE;
return TRUE;
}
//********************************************************************************
std::tuple<BOOL, std::vector<DWORD>, std::vector<DWORD>, std::vector<std::string>> check_access_authz(
const std::wstring name,
const HANDLE& token,
const XSEC::XSD& sd,
DWORD desired_access,
bool zero_mapping = false,
std::optional<std::vector<OBJECT_TYPE_LIST>> object_type_list = std::nullopt,
std::optional<XSEC::XSID> self = std::nullopt
)
{
#pragma region Initial variables
BOOL check_result = FALSE;
PRIVILEGE_SET privileges = { 0 };
DWORD privileges_length = sizeof(privileges);
BOOL GenerateOnClose = FALSE;
GENERIC_MAPPING mapping;
#pragma endregion
#pragma region Set a correct "mapping" values
if(zero_mapping)
mapping = { 0x00 };
else
{
mapping = { 0xFFFFFFFF };
mapping.GenericRead = FILE_GENERIC_READ;
mapping.GenericWrite = FILE_GENERIC_WRITE;
mapping.GenericExecute = FILE_GENERIC_EXECUTE;
mapping.GenericAll = FILE_ALL_ACCESS;
}
#pragma endregion
#pragma region Initialize values related to "object list"
std::vector<OBJECT_TYPE_LIST> object_list_value = object_type_list.value_or(std::vector<OBJECT_TYPE_LIST>{});
GUID zero = { 0x00000000, 0x0000, 0x0000, { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } };
if(object_list_value.size() == 0)
{
// The object list must have at least one element
// identifying the root object itself
object_list_value.push_back({
0,
0,
&zero
});
}
#pragma endregion
#pragma region Initialize "result values"
size_t size = object_list_value.size();
std::vector<DWORD> granted_access(size, 0);
std::vector<DWORD> access_status(size, 0);
std::vector<DWORD> sacl_eval_results(size, 0);
std::vector<DWORD> errors(size, 0);
#pragma endregion
#pragma region Initialize correct "PrincipalSelf" substitute value
XSEC::bin_t bin_self;
PSID sid_self = NULL;
if(self)
{
bin_self = (XSEC::bin_t)self.value();
sid_self = bin_self.data();
}
#pragma endregion
#pragma region Convert security descriptor into binary format
auto bin = (XSEC::bin_t)sd;
#pragma endregion
#pragma region Make an impersonation token from primary
HANDLE dup_token;
if(FALSE == DuplicateTokenEx(token, MAXIMUM_ALLOWED, nullptr, SecurityDelegation, TokenImpersonation, &dup_token))
throw std::exception("AccessCheck: cannot duplicate token");
#pragma endregion
#pragma region Check access
AUTHZ_RESOURCE_MANAGER_HANDLE AuthzResMgrHandle = NULL;
AUTHZ_CLIENT_CONTEXT_HANDLE AuthzClientHandle = NULL;
LUID ZeroLuid = { 0, 0 };
AUTHZ_ACCESS_REQUEST AccessRequest = {
desired_access,
sid_self,
object_list_value.data(),
object_list_value.size(),
NULL
};
AUTHZ_ACCESS_REPLY AccessReply = { 0 };
AccessReply.ResultListLength = object_list_value.size();
AccessReply.GrantedAccessMask = granted_access.data();
AccessReply.SaclEvaluationResults = sacl_eval_results.data();
AccessReply.Error = errors.data();
if(!AuthzInitializeResourceManager(
AUTHZ_RM_FLAG_NO_AUDIT,
NULL, //CheckCallback,
NULL,
NULL,
NULL,
&AuthzResMgrHandle
))
{
throw std::exception("AuthzInitializeResourceManager: error");
}
if(!AuthzInitializeContextFromToken(
0,
dup_token,
AuthzResMgrHandle,
NULL,
ZeroLuid,
NULL,
&AuthzClientHandle
))
{
throw std::exception("AuthzInitializeContextFromToken: error");
}
check_result = AuthzAccessCheck(
0,
AuthzClientHandle,
&AccessRequest,
NULL,
(PSECURITY_DESCRIPTOR)bin.data(),
NULL,
0,
&AccessReply,
NULL
);
if(FALSE == check_result)
{
std::stringstream stream;
stream << "AccessCheck: error during a check, #" << GetLastError() << "\n";
throw std::exception(stream.str().c_str());
}
#pragma endregion
std::vector<std::string> granted_access_string;
std::transform(granted_access.begin(), granted_access.end(), std::back_inserter(granted_access_string), [](DWORD value) -> std::string { return std::bitset<32>(value).to_string(); });
return std::make_tuple(check_result, granted_access, access_status, granted_access_string);
}
//********************************************************************************
namespace XSECTests
{
TEST_CLASS(XSECTests)
{
public:
#pragma region Common variables
XSID fiction_owner{ L"S-1-5-21-3522493417-3251241581-1305895453-513" }; // Fiction owner (in order to exclude additional "common access rights" in case owner are equal with token's owner)
XSID fiction_group{ L"S-1-5-21-3522493417-3251241581-1305895453-514" };
#pragma endregion
TEST_CLASS_INITIALIZE(SetupMethod)
{
CoInitialize(NULL);
HANDLE token;
if(!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES, &token))
throw std::exception("XSEC Test: cannot get process token");
// In order to have audit message generation function working we need to set "SeAuditPrivilege"
// in the PROCESS token, NOT in a thread token. So, even if the access check would be
// against a context from thread token the "SeAuditPrivilege" MUST be set in PROCESS token.
if(FALSE == XTOKEN::ChangePrivileges({ L"SeAuditPrivilege" }, token))
throw std::exception("XSEC Test: cannot set necessary privileges");
CloseHandle(token);
}
TEST_CLASS_CLEANUP(ClearMethod)
{
CoUninitialize();
}
TEST_METHOD(BASIC)
{
auto token = XTOKEN::Create(XSID::CurrentUser);
#pragma region The "null DACL"
// If a security descriptor has no DACL at all (null DACL) then all SIDs allowed
auto [result1, granted_access1, access_status1, granted_access_string1] = check_access(
L"The 'null DACL'",
token,
{ fiction_owner },
FILE_ALL_ACCESS
);
Assert::AreEqual(granted_access1[0], (DWORD)FILE_ALL_ACCESS);
#pragma endregion
#pragma region Empty DACL
// If a security descriptor has an "empty DACL" (DACL exists, but has no ACEs) then no SIDs allowed
auto [result2, granted_access2, access_status2, granted_access_string2] = check_access(
L"Empty DACL",
token,
{ fiction_owner, { std::initializer_list<XACE>{} } },
FILE_ALL_ACCESS
);
Assert::AreEqual(granted_access2[0], (DWORD)0);
// When we set "SeTakeOwnershipPrivilege" in token we can get WRITE_OWNER access even to this "unaccesable" SD
auto [result2_1, granted_access2_1, access_status2_1, granted_access_string2_1] = check_access(
L"Empty DACL but with SeTakeOwnershipPrivilege",
XTOKEN::Create(
XSID::CurrentUser,
XSID::Everyone,
{{ L"SeTakeOwnershipPrivilege" }}
),
{ fiction_owner, { std::initializer_list<XACE>{} } },
WRITE_OWNER
);
Assert::AreEqual(granted_access2_1[0], (DWORD)WRITE_OWNER);
// For an owner in SD there are always "READ_CONTROL + WRITE_DAC" access.
// So, even if here we have "empty DACL" owner can get "READ_CONTROL + WRITE_DAC" access rights.
auto [result2_2, granted_access2_2, access_status2_2, granted_access_string2_2] = check_access(
L"Empty DACL but with special access rights for SD owner",
XTOKEN::Create(
fiction_owner
),
{ fiction_owner, { std::initializer_list<XACE>{} } },
READ_CONTROL | WRITE_DAC
);
Assert::AreEqual(granted_access2_2[0], (DWORD)(READ_CONTROL | WRITE_DAC));
#pragma endregion
#pragma region Common denied ACE
// In a "common case" denied ACEs must be before "allowed" ACEs and should have non-zero access mask
auto [result3, granted_access3, access_status3, granted_access_string3] = check_access(
L"Common denied ACE",
XTOKEN::Create(
XSID::CurrentUser,
fiction_group
),
{
fiction_owner,
{{
XACCESS_DENIED_ACE(
XSID::CurrentUser,
(DWORD)FILE_READ_ACCESS
),
// The "Everyone" group cannot be using as a "all users in the world" always.
// If the "Everyone" group would not exist in token's SIDs then
// "Everyone" would not be considered during access checking.
XACCESS_ALLOWED_ACE(
XSID::Everyone,
(DWORD)(FILE_READ_ACCESS | FILE_WRITE_ACCESS)
),
XACCESS_ALLOWED_ACE(
fiction_group,
(DWORD)(FILE_READ_ACCESS | FILE_WRITE_ACCESS | FILE_APPEND_DATA)
)
}}
},
FILE_READ_ACCESS | FILE_WRITE_ACCESS | FILE_APPEND_DATA
);
// In fact access for this particular token to this particular SD was denied.
// It is because "desired access = FILE_READ_ACCESS | FILE_WRITE_ACCESS | FILE_APPEND_DATA",
// but for user's SID some access was denied (FILE_READ_ACCESS). So, even if "granted access" has a value
// in general access was denied (not all access from "desired access" was satisfied).
Assert::AreEqual(granted_access3[0], (DWORD)(FILE_WRITE_ACCESS | FILE_APPEND_DATA));
#pragma endregion
#pragma region Denied ACE after allowed
// In case of a wrong ACE order the system access checking function would allow
// all access because the the function meet allow rule first
auto [result4, granted_access4, access_status4, granted_access_string4] = check_access(
L"Denied ACE after allowed",
token,
{
fiction_owner,
{{
XACCESS_ALLOWED_ACE(
XSID::Everyone,
(DWORD)FILE_ALL_ACCESS
),
XACCESS_DENIED_ACE(
XSID::CurrentUser,
(DWORD)FILE_READ_ACCESS
)
}}
},
FILE_READ_ACCESS | FILE_WRITE_ACCESS
);
Assert::AreEqual(granted_access4[0], (DWORD)FILE_READ_ACCESS | FILE_WRITE_ACCESS);
#pragma endregion
#pragma region Denied ACE with zero access mask
// In case of a correct ACE order but when denied ACE has zero access mask system access
// cheching function do not count the denied ACE (the denied ACE deny nothing)
auto [result5, granted_access5, access_status5, granted_access_string5] = check_access(
L"Denied ACE with zero access mask",
token,
{
fiction_owner,
{{
XACCESS_DENIED_ACE(
XSID::CurrentUser,
(DWORD)0
),
XACCESS_ALLOWED_ACE(
XSID::Everyone,
(DWORD)FILE_ALL_ACCESS
)
}}
},
FILE_READ_ACCESS | FILE_WRITE_ACCESS
);
Assert::AreEqual(granted_access5[0], (DWORD)FILE_READ_ACCESS | FILE_WRITE_ACCESS);
#pragma endregion
#pragma region Denied access for group
// In this case there is a "deny rule" for group in token. But the group do not have "SE_GROUP_ENABLED" flag set.
// That is why access checking would not consider the "deny rule" and will grant full access to the SD.
auto [result6, granted_access6, access_status6, granted_access_string6] = check_access(
L"Denied access for group",
XTOKEN::Create(
XSID::CurrentUser,
XSID::Everyone,
{},
{ { fiction_group, (DWORD)0 } }
),
{
fiction_owner,
{{
XACCESS_DENIED_ACE(
fiction_group,
(DWORD)FILE_ALL_ACCESS
),
XACCESS_ALLOWED_ACE(
XSID::Everyone,
(DWORD)FILE_ALL_ACCESS
)
}}
},
FILE_ALL_ACCESS
);
Assert::AreEqual(granted_access6[0], (DWORD)FILE_ALL_ACCESS);
// In order to not allow any user to disable critical groups the group in token must have at least "SE_GROUP_MANDATORY" flag set
auto [result6_1, granted_access6_1, access_status6_1, granted_access_string6_1] = check_access(
L"Denied access for group but with SE_GROUP_MANDATORY flag set",
XTOKEN::Create(
XSID::CurrentUser,
XSID::Everyone,
{},
{ { fiction_group, { SidAndAttributesMeaningDefault, { L"SE_GROUP_MANDATORY" } } } }
),
{
fiction_owner,
{{
XACCESS_DENIED_ACE(
fiction_group,
(DWORD)FILE_ALL_ACCESS
),
XACCESS_ALLOWED_ACE(
XSID::Everyone,
(DWORD)FILE_ALL_ACCESS
)
}}
},
FILE_ALL_ACCESS
);
Assert::AreEqual(granted_access6_1[0], (DWORD)0);
#pragma endregion
#pragma region Inheritence in ACE
auto [result7, granted_access7, access_status7, granted_access_string7] = check_access(
L"Inheritence in ACE",
XTOKEN::Create(
XSID::CurrentUser,
XSID::Everyone,
{},
{ { fiction_group, { SidAndAttributesMeaningDefault, { L"SE_GROUP_MANDATORY" } } } }
),
{
fiction_owner,
{{
// This ACE would not count because it has "INHERIT_ONLY_ACE" flag set
XACCESS_DENIED_ACE(
fiction_group,
(DWORD)FILE_ALL_ACCESS,
{ ByteBitsMeaningAceFlags, { L"INHERIT_ONLY_ACE" } }
),
XACCESS_ALLOWED_ACE(
XSID::Everyone,
(DWORD)FILE_ALL_ACCESS,
{
ByteBitsMeaningAceFlags,
{
L"INHERITED_ACE", // Simple flag representing the ACE was inhirited
L"OBJECT_INHERIT_ACE", // It will be applicable to all descendant files
L"CONTAINER_INHERIT_ACE", // It will be applicable to all descendant folders
L"NO_PROPAGATE_INHERIT_ACE" // If the ACE is inherited by a child object, the system clears the OBJECT_INHERIT_ACE and CONTAINER_INHERIT_ACE flags in the inherited ACE. This prevents the ACE from being inherited by subsequent generations of objects
}
}
)
}}
},
FILE_ALL_ACCESS
);
Assert::AreEqual(granted_access7[0], (DWORD)FILE_ALL_ACCESS);
#pragma endregion
#pragma region Using of "Principal Self SID" in ACE
auto [result8, granted_access8, access_status8, granted_access_string8] = check_access(
L"Using of 'Principal Self SID' in ACE",
XTOKEN::Create(
XSID::CurrentUser,
fiction_group
),
{
fiction_owner,
{{
XACCESS_ALLOWED_ACE(
XSID::PlaceholderPrincipalSelf,
(DWORD)FILE_ALL_ACCESS
)
}}
},
FILE_ALL_ACCESS,
false,
std::nullopt,
fiction_group // The "PrincipalSelf" in all ACEs would be replaced by this SID
);
Assert::AreEqual(granted_access8[0], (DWORD)FILE_ALL_ACCESS);
#pragma endregion
#pragma region Audit: common audit message
// NOTE: in order to generate any audit messages the calling PROCESS token must have "SeAuditPrivilege" enabled.
// In this test we set "SeAuditPrivilege" in process token in "TEST_CLASS_INITIALIZE" function.
// Privileges in the token participating in access checking does not matter.
auto [result9, granted_access9, access_status9, granted_access_string9] = check_access(
L"Audit: common audit message",
XTOKEN::Create(
XSID::CurrentUser,
fiction_group
),
{
fiction_owner,
{{
XACCESS_DENIED_ACE(
XSID::CurrentUser,
(DWORD)FILE_READ_ACCESS
),
XACCESS_ALLOWED_ACE(
fiction_group,
(DWORD)FILE_ALL_ACCESS
)
}},
{{
// Does not matter which flags to put here: if a mask is in "desired access" then logging would be performed.
// In case access was denied (as in this case) it would be "denied message".
XSYSTEM_AUDIT_ACE(
// Even if we put "Everyone" here audit message have a chance to be suspended.
// The audit message would be generated only if the SID from SYSTEM_AUDIT_ACE exists
// in user's token. So, if there is no "Everyone" SID in token then no audit messages
/// would be generated for "XSYSTEM_AUDIT_ACE(Everyone)".
fiction_group,
(DWORD)FILE_WRITE_ACCESS,
{ ByteBitsMeaningAceFlags, { L"SUCCESSFUL_ACCESS_ACE_FLAG", L"FAILED_ACCESS_ACE_FLAG" } }
)
}}
},
FILE_READ_ACCESS | FILE_WRITE_ACCESS
);
Assert::AreEqual(granted_access9[0], (DWORD)FILE_WRITE_ACCESS);
#pragma endregion
#pragma region Audit: missing FAILED_ACCESS_ACE_FLAG flag
auto [result10, granted_access10, access_status10, granted_access_string10] = check_access(
L"Audit: missing FAILED_ACCESS_ACE_FLAG flag",
XTOKEN::Create(
XSID::CurrentUser,
fiction_group
),
{
fiction_owner,
{{
XACCESS_DENIED_ACE(
XSID::CurrentUser,
(DWORD)FILE_READ_ACCESS
),
XACCESS_ALLOWED_ACE(
fiction_group,
(DWORD)FILE_ALL_ACCESS
)
}},
{{
// Audit message would not be generated due to missing "FAILED_ACCESS_ACE_FLAG" flag
XSYSTEM_AUDIT_ACE(
fiction_group,
(DWORD)FILE_WRITE_ACCESS,
{ ByteBitsMeaningAceFlags, { L"SUCCESSFUL_ACCESS_ACE_FLAG" } }
)
}}
},
FILE_READ_ACCESS | FILE_WRITE_ACCESS
);
Assert::AreEqual(granted_access10[0], (DWORD)FILE_WRITE_ACCESS);
#pragma endregion
#pragma region Audit: conditional audit message
auto [result11, granted_access11, access_status11, granted_access_string11] = check_access(
L"Audit: conditional audit message",
XTOKEN::Create(
XSID::CurrentUser,
fiction_group,
{},
{},
std::nullopt,
{
{{L"Title", { L"VP" }}}
}
),
{
fiction_owner,
{{
XACCESS_DENIED_ACE(
XSID::CurrentUser,
(DWORD)FILE_READ_ACCESS
),
XACCESS_ALLOWED_ACE(
fiction_group,
(DWORD)FILE_ALL_ACCESS
)
}},
{{
XSYSTEM_AUDIT_CALLBACK_ACE(
fiction_group,
(DWORD)FILE_WRITE_ACCESS,
XUser(L"Title") == L"VP"
)
}}
},
FILE_READ_ACCESS | FILE_WRITE_ACCESS
);
Assert::AreEqual(granted_access11[0], (DWORD)FILE_WRITE_ACCESS);
#pragma endregion
}
TEST_METHOD(FILE_EXAMPLE)
{
// How system creates DACL for new objects
// https://docs.microsoft.com/en-us/windows/win32/secauthz/dacl-for-a-new-object
#pragma region Check directory exists and remove it if necessary
auto current = std::filesystem::current_path();
if(std::filesystem::exists(current / "inherited"))
std::filesystem::remove_all(current / "inherited");
#pragma endregion
#pragma region Create a sample directory with a default security descriptor
if(!std::filesystem::create_directory(current / "inherited"))
throw std::exception("Cannot make 'inherited' directory");
#pragma endregion
#pragma region Change DACL for the newly created directory
XSD sd{
XSID::CurrentUser,
{{
XACCESS_ALLOWED_ACE(
XSID::Everyone,
(DWORD)FILE_ALL_ACCESS
),
}}
};
bin_t bin = (bin_t)sd;
BOOL result = SetFileSecurity(L"inherited", DACL_SECURITY_INFORMATION, (PSECURITY_DESCRIPTOR)bin.data());
if(FALSE == result)
{
std::stringstream stream;
stream << "Error on changing SD: " << GetLastError();
throw std::exception(stream.str().c_str());
}
#pragma endregion
#pragma region Make a token with "default DACL" and create a subdirectory with the token
auto token = XTOKEN::Create(
fiction_owner,
fiction_group,
{
{ L"SeChangeNotifyPrivilege" } // Bypass traverse checking
},
{ XSID::Everyone }, // Need this group in order to access root directory
std::nullopt,
std::nullopt,
std::nullopt,
std::nullopt,
{},
std::nullopt,
{ {
XACCESS_ALLOWED_ACE(
XSID::Everyone,
(DWORD)FILE_ALL_ACCESS,
{ ByteBitsMeaningAceFlags, { L"OBJECT_INHERIT_ACE", L"CONTAINER_INHERIT_ACE" } }
),
XACCESS_ALLOWED_ACE(
XSID::PlaceholderPrincipalSelf, // Requires separate parameter during access check
{ DwordMeaningFile, { L"GENERIC_ALL" } },
{ ByteBitsMeaningAceFlags, { L"INHERIT_ONLY_ACE", L"OBJECT_INHERIT_ACE", L"CONTAINER_INHERIT_ACE" } }
),
XACCESS_ALLOWED_ACE(
XSID::PlaceholderCreatorOwner, // Substitute with "Owner" from active token
{ DwordMeaningFile, { L"GENERIC_ALL" } },
{ ByteBitsMeaningAceFlags, { L"INHERIT_ONLY_ACE", L"OBJECT_INHERIT_ACE", L"CONTAINER_INHERIT_ACE" } }
),
XACCESS_ALLOWED_ACE(
XSID::PlaceholderCreatorGroup, // Substitute with "PrimaryGroup" from active token
{ DwordMeaningFile, { L"GENERIC_ALL" } },
{ ByteBitsMeaningAceFlags, { L"INHERIT_ONLY_ACE", L"OBJECT_INHERIT_ACE", L"CONTAINER_INHERIT_ACE" } }
),
XACCESS_ALLOWED_ACE(
XSID::PlaceholderOwnerServer, // Disapears from final DACL
{ DwordMeaningFile, { L"GENERIC_ALL" } },
{ ByteBitsMeaningAceFlags, { L"INHERIT_ONLY_ACE", L"OBJECT_INHERIT_ACE", L"CONTAINER_INHERIT_ACE" } }
),
XACCESS_ALLOWED_ACE(
XSID::PlaceholderGroupServer, // Disapears from final DACL
{ DwordMeaningFile, { L"GENERIC_ALL" } },
{ ByteBitsMeaningAceFlags, { L"INHERIT_ONLY_ACE", L"OBJECT_INHERIT_ACE", L"CONTAINER_INHERIT_ACE" } }
)
} }
);
HANDLE dup_token;
if(FALSE == DuplicateTokenEx(token, MAXIMUM_ALLOWED, nullptr, SecurityDelegation, TokenImpersonation, &dup_token))
throw std::exception("Cannot duplicate token");
if(FALSE == SetThreadToken(nullptr, dup_token))
throw std::exception("Cannot set token for thread");
if(!std::filesystem::create_directory(current / "inherited/subdirectory"))
throw std::exception("Cannot make 'inherited' directory");
#pragma region Create a file using "manually made" token
// The "PlaceholderCreatorOwner" and "PlaceholderCreatorGroup" values
// are from "manually made" token. But a system also append values from "process token" somehow.
std::ofstream(current / "inherited/subdirectory/file1.txt");
#pragma endregion
SetThreadToken(nullptr, nullptr); // Set back default token for current thread
#pragma endregion
#pragma region Get security descriptor from newly created file and store it to XML
auto sd_file1 = XSD::GetFromFileObject(L"inherited/subdirectory/file1.txt");
XSave(sd_file1, L"sd_file1.xml");
#pragma endregion
#pragma region Create a new file inside the subfolder using "default values"
// Now on the file we will have a correctly set substitutes for
// "PlaceholderCreatorOwner" and "PlaceholderCreatorGroup".
// NOTE: all these values came from PROCESS token, not from the
// token we manually made before (with default DACL).
std::ofstream(current / "inherited/subdirectory/file2.txt");
#pragma endregion
}
TEST_METHOD(INTEGRITY_CHECK)
{
#pragma region The "null DACL" with low integrity level in token
// Access the security descriptor with "null DACL" (all SIDs allowed), but making a token with "UntrustedMandatoryLevel"
// and at the same time security descriptor has "SystemMandatoryLevel" (with all flags set).
auto [result1, granted_access1, access_status1, granted_access_string1] = check_access(
L"The 'null DACL' with low integrity level in token",
XTOKEN::Create(
XSID::CurrentUser,
fiction_group,
{},
{
{ XSID::UntrustedMandatoryLevel, { SidAndAttributesMeaningDefault, { L"SE_GROUP_INTEGRITY", L"SE_GROUP_INTEGRITY_ENABLED" } }}
}
),
{
fiction_owner,
std::nullopt,
{{
XSYSTEM_MANDATORY_LABEL_ACE(
XSID::SystemMandatoryLevel,
{ DwordMeaningMandatoryLabel, { L"SYSTEM_MANDATORY_LABEL_NO_WRITE_UP", L"SYSTEM_MANDATORY_LABEL_NO_READ_UP", L"SYSTEM_MANDATORY_LABEL_NO_EXECUTE_UP" } }
)
}}
},
FILE_ALL_ACCESS
);
Assert::AreEqual(granted_access1[0], (DWORD)0);
// Same configuration, but with "SYSTEM_MANDATORY_LABEL_NO_READ_UP = 0" in SD and access requested in only FILE_READ_DATA.
// The access would be granted, even for "UntrustedMandatoryLevel" in token.
auto [result1_1, granted_access1_1, access_status1_1, granted_access_string1_1] = check_access(
L"The 'null DACL' with low integrity level in token but with 'SYSTEM_MANDATORY_LABEL_NO_READ_UP = 0'",
XTOKEN::Create(
XSID::CurrentUser,
fiction_group,
{},
{
{ XSID::UntrustedMandatoryLevel, { SidAndAttributesMeaningDefault, { L"SE_GROUP_INTEGRITY", L"SE_GROUP_INTEGRITY_ENABLED" } }}
}
),
{
fiction_owner,
std::nullopt,
{{
XSYSTEM_MANDATORY_LABEL_ACE(
XSID::SystemMandatoryLevel,
{ DwordMeaningMandatoryLabel, { L"SYSTEM_MANDATORY_LABEL_NO_WRITE_UP", L"SYSTEM_MANDATORY_LABEL_NO_EXECUTE_UP" } }
)
}}
},
FILE_READ_DATA
);
Assert::AreEqual(granted_access1_1[0], (DWORD)FILE_READ_DATA);
// Same configuration, but with "SYSTEM_MANDATORY_LABEL_NO_READ_UP = 0" in SD and access requested in only FILE_READ_DATA.
// But in this case in access checking function we do not use "generic rights mapping" and if the "mapping" is not used
// the access check would be performed again using only two integrity levels comparision (no check for "SYSTEM_MANDATORY_LABEL_NO_READ_UP = 0").
auto [result1_2, granted_access1_2, access_status1_2, granted_access_string1_2] = check_access(
L"The 'null DACL' with low integrity level in token but with 'SYSTEM_MANDATORY_LABEL_NO_READ_UP = 0' but without 'mapping'",
XTOKEN::Create(
XSID::CurrentUser,
fiction_group,
{},
{
{ XSID::UntrustedMandatoryLevel, { SidAndAttributesMeaningDefault, { L"SE_GROUP_INTEGRITY", L"SE_GROUP_INTEGRITY_ENABLED" } }}
}
),
{
fiction_owner,
std::nullopt,
{{
XSYSTEM_MANDATORY_LABEL_ACE(
XSID::SystemMandatoryLevel,
{ DwordMeaningMandatoryLabel, { L"SYSTEM_MANDATORY_LABEL_NO_WRITE_UP", L"SYSTEM_MANDATORY_LABEL_NO_EXECUTE_UP" } }
)
}}
},
FILE_READ_DATA,
true // Flag for "not to use generic rights mapping"
);
Assert::AreEqual(granted_access1_2[0], (DWORD)0);
// Same input as in previous case, but now we set 0 to "mandatory policy flags" in token.
// It allows completely bypass any integrity checks and again check would be done for "null DACL" only (all SIDs allowed).
auto [result1_3, granted_access1_3, access_status1_3, granted_access_string1_3] = check_access(
L"The 'null DACL' with low integrity level in token but with 'SYSTEM_MANDATORY_LABEL_NO_READ_UP = 0' but without 'mapping' and 'mandatory policy flags = 0'",
XTOKEN::Create(
XSID::CurrentUser,
fiction_group,
{},
{
{ XSID::UntrustedMandatoryLevel, { SidAndAttributesMeaningDefault, { L"SE_GROUP_INTEGRITY", L"SE_GROUP_INTEGRITY_ENABLED" } }}
},
std::nullopt,
std::nullopt,
std::nullopt,
std::nullopt,
{},
(DWORD)0 // Mandatory policy flags
),
{
fiction_owner,
std::nullopt,
{{
XSYSTEM_MANDATORY_LABEL_ACE(
XSID::SystemMandatoryLevel,
{ DwordMeaningMandatoryLabel, { L"SYSTEM_MANDATORY_LABEL_NO_WRITE_UP", L"SYSTEM_MANDATORY_LABEL_NO_EXECUTE_UP" } }
)
}}
},
FILE_ALL_ACCESS,
true // Flag for "not to use generic rights mapping"
);
Assert::AreEqual(granted_access1_3[0], (DWORD)FILE_ALL_ACCESS);
#pragma endregion
#pragma region Administrative privileges on token with low level
//
// Certain administrative Windows privileges can be assigned to an access token only with at least a high integrity
// level.If the access token integrity level is less than high, then specific administrative privileges are not allowed
// and are removed from the access token (or just set to 0). The administrative privileges associated with a high integrity level are:
// SeCreateTokenPrivilege
// SeTcbPrivilege
// SeTakeOwnershipPrivilege
// SeLoadDriverPrivilege
// SeBackupPrivilege
// SeRestorePrivilege
// SeDebugPrivilege
// SeImpersonatePrivilege
// SeRelabelPrivilege
// SeDelegateSessionUserImpersonatePrivilege
//
auto token = XTOKEN::Create(
XSID::CurrentUser,
fiction_group,
{
{ L"SeCreateTokenPrivilege" },
{ L"SeTcbPrivilege" },
{ L"SeTakeOwnershipPrivilege" },
{ L"SeLoadDriverPrivilege" },
{ L"SeBackupPrivilege" },
{ L"SeRestorePrivilege" },
{ L"SeDebugPrivilege" },
{ L"SeImpersonatePrivilege" },
{ L"SeRelabelPrivilege" },
{ L"SeDelegateSessionUserImpersonatePrivilege" }
},
{
{ XSID::MediumMandatoryLevel, { SidAndAttributesMeaningDefault, { L"SE_GROUP_INTEGRITY", L"SE_GROUP_INTEGRITY_ENABLED" } }}
}
);
DWORD attributes = 0;
for(auto&& element : XTOKEN::GetTokenInfo<TokenPrivileges>(token))
attributes += (DWORD)*element.Attributes;
Assert::AreEqual(attributes, (DWORD)0);