├── README.md
├── driver
├── NtCreateLowboxToken.vcxproj
├── LowboxToken.h
└── LowboxToken.c
├── tests
├── CLTTest.vcxproj
└── CLTTest.cpp
└── LICENSE
/README.md:
--------------------------------------------------------------------------------
1 | # Precise Reimplementation of NtCreateLowBoxToken System Call
2 |
3 | A meticulously reverse-engineered implementation of the Windows NT kernel's NtCreateLowBoxToken native system call. This sophisticated reimplementation provides a comprehensive and binary-compatible replacement for the original system call functionality, with particular emphasis on security token manipulation and process isolation mechanisms.
4 |
5 | ## Architectural Overview
6 |
7 | This repository presents an independently developed reproduction of the `NtCreateLowBoxToken` native API implementation, a critical component in Windows security token manipulation and process isolation architecture. The implementation has been systematically reconstructed through precise reverse engineering of Windows 11 24H2 system call interfaces, ensuring behavioral consistency with the native implementation at the binary level.
8 |
9 | ## Technical Capabilities
10 |
11 | - Binary-compatible replacement for the native NtCreateLowBoxToken system call interface
12 | - Precise reproduction of Windows 11 24H2's internal token manipulation mechanisms
13 | - Comprehensive support for AppContainer security context creation and management
14 | - Kernel-mode driver implementation for system call interception
15 | - Demonstration of programmatic security boundary establishment
16 |
17 | ## Platform Compatibility Matrix
18 |
19 | Extensively validated across contemporary Windows NT-based operating systems:
20 | - Windows 11 Version 24H2 (10.0.26100.2605)
21 | - Windows 11 Version 23H2 (10.0.22631.4602)
22 | - Windows 10 Version 22H2 (10.0.19045.5247)
23 |
24 | ## Demonstration Implementation
25 | The repository incorporates a comprehensive demonstration application that:
26 |
27 | Facilitates kernel-mode driver installation and initialization
28 |
29 | Implements system call interception mechanisms
30 |
31 | Demonstrates programmatic AppContainer security context establishment
32 |
33 | Executes Notepad.exe within an AppContainer security boundary
34 |
35 | The demonstration utilizes select components from MalwareTech's AppContainerSandbox implementation
36 |
37 | ## Repository Architecture
38 |
39 | ├── driver/ # Kernel-mode implementation
40 |
41 | └── tests/ # Validation suite
42 |
43 | ## Build Requirements
44 | Prerequisites
45 |
46 | Microsoft Visual Studio 2022 Development Environment
47 |
48 | Windows Driver Development Kit (WDK)
49 |
50 | Windows Software Development Kit (SDK) 10.0.22621.0 or subsequent releases
51 |
52 | ## Attribution
53 | Demonstration implementation incorporates components from MalwareTech's AppContainerSandbox
54 |
55 | ## Licensing
56 | This implementation is distributed under the GNU General Public License v3.0. Refer to the LICENSE document for comprehensive terms.
57 |
58 | ## Implementation Notes
59 | Independent implementation, not affiliated with Microsoft Corporation
60 |
61 | Implementation deployed at operator's discretion.
62 |
63 | Not recommended for production environment deployment
64 |
65 | ## Community Participation
66 | Technical contributions are welcomed. Please initiate discussion through issue submission prior to modification proposals.
67 |
--------------------------------------------------------------------------------
/driver/NtCreateLowboxToken.vcxproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | x64
7 |
8 |
9 | Release
10 | x64
11 |
12 |
13 | Debug
14 | ARM64
15 |
16 |
17 | Release
18 | ARM64
19 |
20 |
21 |
22 | {BCD776BB-9E6A-4F29-A737-3207F60912A4}
23 | {dd38f7fc-d7bd-488b-9242-7d8754cde80d}
24 | v4.5
25 | 12.0
26 | Debug
27 | x64
28 | NtCreateLowboxToken
29 |
30 |
31 |
32 | Windows10
33 | true
34 | WindowsKernelModeDriver10.0
35 | Driver
36 | WDM
37 |
38 |
39 | Windows10
40 | false
41 | WindowsKernelModeDriver10.0
42 | Driver
43 | WDM
44 | false
45 |
46 |
47 | Windows10
48 | true
49 | WindowsKernelModeDriver10.0
50 | Driver
51 | WDM
52 |
53 |
54 | Windows10
55 | false
56 | WindowsKernelModeDriver10.0
57 | Driver
58 | WDM
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 | DbgengKernelDebugger
70 |
71 |
72 | DbgengKernelDebugger
73 |
74 |
75 | DbgengKernelDebugger
76 |
77 |
78 | DbgengKernelDebugger
79 |
80 |
81 |
82 | sha256
83 |
84 |
85 |
86 |
87 | sha256
88 |
89 |
90 | false
91 | true
92 | OnlyExplicitInline
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
--------------------------------------------------------------------------------
/tests/CLTTest.vcxproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | Win32
7 |
8 |
9 | Release
10 | Win32
11 |
12 |
13 | Debug
14 | x64
15 |
16 |
17 | Release
18 | x64
19 |
20 |
21 |
22 | 17.0
23 | Win32Proj
24 | {dfd28bd9-9745-4a89-8784-d9b632f4b524}
25 | CLTTest
26 | 10.0
27 |
28 |
29 |
30 | Application
31 | true
32 | v143
33 | Unicode
34 |
35 |
36 | Application
37 | false
38 | v143
39 | true
40 | Unicode
41 |
42 |
43 | Application
44 | true
45 | v143
46 | Unicode
47 |
48 |
49 | Application
50 | false
51 | v143
52 | true
53 | Unicode
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 | Level3
76 | true
77 | WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)
78 | true
79 |
80 |
81 | Console
82 | true
83 |
84 |
85 |
86 |
87 | Level3
88 | true
89 | true
90 | true
91 | WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)
92 | true
93 |
94 |
95 | Console
96 | true
97 | true
98 | true
99 |
100 |
101 |
102 |
103 | Level3
104 | true
105 | _DEBUG;_CONSOLE;%(PreprocessorDefinitions)
106 | true
107 |
108 |
109 | Console
110 | true
111 |
112 |
113 |
114 |
115 | Level3
116 | true
117 | true
118 | true
119 | NDEBUG;_CONSOLE;%(PreprocessorDefinitions)
120 | true
121 |
122 |
123 | Console
124 | true
125 | true
126 | true
127 |
128 |
129 |
130 |
131 |
132 |
133 |
134 |
135 |
--------------------------------------------------------------------------------
/tests/CLTTest.cpp:
--------------------------------------------------------------------------------
1 | #include "windows.h"
2 | #include
3 | #pragma comment(lib, "shlwapi.lib")
4 | HANDLE hKernel;
5 | WCHAR KernelDev[] = L"\\\\.\\NtCreateLowboxToken";
6 | WCHAR DriverName[] = L"NtCreateLowboxToken";
7 | #include "winioctl.h"
8 | BOOL LoadKernelDriver()
9 | {
10 | WCHAR CurrentPath[MAX_PATH] = { 0 };
11 | WCHAR driverPath[MAX_PATH] = L"\\??\\";
12 | SC_HANDLE hSCManager = NULL;
13 | SC_HANDLE hService = NULL;
14 | BOOL success = FALSE;
15 |
16 | __try {
17 |
18 | hKernel = CreateFile(KernelDev, FILE_READ_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
19 |
20 | if (hKernel != INVALID_HANDLE_VALUE)
21 | {
22 | success = TRUE;
23 | __leave;
24 | }
25 |
26 | // Get Windows directory and create full driver path
27 | if (!GetCurrentDirectoryW(MAX_PATH , (LPWSTR)CurrentPath)) {
28 | __leave;
29 | }
30 |
31 | PathAppend(driverPath, CurrentPath);
32 |
33 |
34 | PathAppend(driverPath, L"\\NtCreateLowboxToken.sys");
35 |
36 | // Open SCM
37 | hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
38 | if (!hSCManager) {
39 | __leave;
40 | }
41 |
42 | // Check if service exists
43 | hService = OpenService(hSCManager, DriverName, SERVICE_ALL_ACCESS);
44 | if (hService) {
45 |
46 | StartService(hService, 0, 0);
47 |
48 |
49 | hKernel = CreateFile(KernelDev, FILE_READ_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
50 |
51 | if (hKernel != INVALID_HANDLE_VALUE)
52 | {
53 | success = TRUE;
54 | }
55 | __leave;
56 |
57 | }
58 |
59 | // Create service
60 | hService = CreateService(
61 | hSCManager,
62 | DriverName,
63 | DriverName,
64 | SERVICE_ALL_ACCESS,
65 | SERVICE_KERNEL_DRIVER,
66 | SERVICE_DEMAND_START,
67 | SERVICE_ERROR_NORMAL,
68 | driverPath,
69 | NULL,
70 | NULL,
71 | NULL,
72 | NULL,
73 | NULL
74 | );
75 |
76 | if (!hService) {
77 | __leave;
78 | }
79 |
80 | // Start service
81 | if (!StartService(hService, 0, NULL)) {
82 | DWORD error = GetLastError();
83 | if (error != ERROR_SERVICE_ALREADY_RUNNING) {
84 | __leave;
85 | }
86 | }
87 |
88 | hKernel = CreateFile(KernelDev, FILE_READ_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
89 |
90 | if (hKernel != INVALID_HANDLE_VALUE)
91 | {
92 | success = TRUE;
93 | }
94 | }
95 | __finally {
96 | // Cleanup
97 | if (hService) {
98 | CloseServiceHandle(hService);
99 | }
100 | if (hSCManager) {
101 | CloseServiceHandle(hSCManager);
102 | }
103 |
104 |
105 | }
106 |
107 |
108 |
109 | return success;
110 |
111 | }
112 |
113 | #include "stdio.h"
114 |
115 | #include
116 | #include
117 |
118 | #pragma comment(lib, "dbghelp.lib")
119 | #pragma comment(lib, "psapi.lib")
120 |
121 | typedef NTSTATUS(WINAPI* NtQuerySystemInformation_t)(
122 | ULONG SystemInformationClass,
123 | PVOID SystemInformation,
124 | ULONG SystemInformationLength,
125 | PULONG ReturnLength
126 | );
127 | typedef struct _SYSTEM_MODULE_ENTRY {
128 | HANDLE Section;
129 | PVOID MappedBase;
130 | PVOID ImageBase;
131 | ULONG ImageSize;
132 | ULONG Flags;
133 | USHORT LoadOrderIndex;
134 | USHORT InitOrderIndex;
135 | USHORT LoadCount;
136 | USHORT OffsetToFileName;
137 | UCHAR FullPathName[256];
138 | } SYSTEM_MODULE_ENTRY, * PSYSTEM_MODULE_ENTRY;
139 |
140 | typedef struct _SYSTEM_MODULE_INFORMATION {
141 | ULONG Count;
142 | SYSTEM_MODULE_ENTRY Module[1];
143 | } SYSTEM_MODULE_INFORMATION, * PSYSTEM_MODULE_INFORMATION;
144 |
145 | #define SystemModuleInformation 11
146 | PVOID GetKernelBase() {
147 | HMODULE ntdll = GetModuleHandleA("ntdll.dll");
148 | if (!ntdll) return NULL;
149 |
150 | NtQuerySystemInformation_t NtQuerySystemInformation =
151 | (NtQuerySystemInformation_t)GetProcAddress(ntdll, "NtQuerySystemInformation");
152 | if (!NtQuerySystemInformation) return NULL;
153 |
154 | ULONG size = 0;
155 | NtQuerySystemInformation(SystemModuleInformation, NULL, 0, &size);
156 |
157 | PSYSTEM_MODULE_INFORMATION moduleInfo = (PSYSTEM_MODULE_INFORMATION)malloc(size);
158 | if (!moduleInfo) return NULL;
159 |
160 | if (NtQuerySystemInformation(SystemModuleInformation, moduleInfo, size, &size) != 0) {
161 | free(moduleInfo);
162 | return NULL;
163 | }
164 | PVOID kernelBase = moduleInfo->Module[0].ImageBase;
165 | free(moduleInfo);
166 |
167 | return kernelBase;
168 | }
169 |
170 |
171 |
172 | BOOL GetKernelSymbolAddress(const char* symbolPath, const char* symbolName, DWORD64* address) {
173 | HANDLE process = GetCurrentProcess();
174 | DWORD64 baseAddr;
175 | char ntos[MAX_PATH];
176 |
177 | GetSystemDirectoryA(ntos, sizeof(ntos));
178 | strcat_s(ntos, sizeof(ntos), "\\ntoskrnl.exe");
179 |
180 | if (!SymInitialize(process, symbolPath, FALSE)) {
181 | printf("SymInitialize failed: %d\n", GetLastError());
182 | return FALSE;
183 | }
184 | baseAddr = SymLoadModule64(
185 | process,
186 | NULL,
187 | ntos,
188 | NULL,
189 | 0,
190 | 0
191 | );
192 |
193 | if (!baseAddr) {
194 | printf("SymLoadModule64 failed: %d\n", GetLastError());
195 | SymCleanup(process);
196 | return FALSE;
197 | }
198 |
199 | SYMBOL_INFO* symbolInfo;
200 | symbolInfo = (SYMBOL_INFO*)malloc(sizeof(SYMBOL_INFO) + MAX_SYM_NAME);
201 | memset(symbolInfo, 0, sizeof(SYMBOL_INFO) + MAX_SYM_NAME);
202 | symbolInfo->SizeOfStruct = sizeof(SYMBOL_INFO);
203 | symbolInfo->MaxNameLen = MAX_SYM_NAME;
204 |
205 | if (!SymFromName(process, symbolName, symbolInfo)) {
206 | printf("SymFromName failed: %s %d\n",symbolName, GetLastError());
207 | free(symbolInfo);
208 | SymCleanup(process);
209 | return FALSE;
210 | }
211 |
212 | *address = symbolInfo->Address - baseAddr;
213 |
214 | free(symbolInfo);
215 | SymCleanup(process);
216 | return TRUE;
217 | }
218 | #include
219 |
220 | #define IOCTL_NTCREATELOWBOXTOKEN CTL_CODE(FILE_DEVICE_UNKNOWN , 0x100 , METHOD_BUFFERED , FILE_ANY_ACCESS)
221 | #define IOCTL_GET_SYSTEM_SYMBOLS CTL_CODE(FILE_DEVICE_UNKNOWN , 0x101 , METHOD_BUFFERED , FILE_ANY_ACCESS)
222 |
223 | typedef struct _LOWBOXTOKEN_PARAMS {
224 | PHANDLE TokenHandle; // _Out_
225 | HANDLE ExistingTokenHandle; // _In_
226 | ACCESS_MASK DesiredAccess; // _In_
227 | POBJECT_ATTRIBUTES ObjectAttributes; // _In_
228 | PSID PackageSid; // _In_
229 | ULONG CapabilityCount; // _In_
230 | PSID_AND_ATTRIBUTES Capabilities; // _In_
231 | ULONG HandleCount; // _In_
232 | HANDLE* Handles; // _In_
233 | } LOWBOXTOKEN_PARAMS, * PLOWBOXTOKEN_PARAMS;
234 | const char* symbols[] = {
235 | "LowboxSessionMapLock",
236 | "g_SessionLowboxArray",
237 | "g_SessionLowboxMap",
238 | "SepLearningModeTokenCount",
239 | "g_SepSidMapping",
240 | "SepTokenCapabilitySidSharingEnabled",
241 | "SepDuplicateToken"
242 | };
243 |
244 | PVOID KernelSymbols[sizeof(symbols) / sizeof(char*)];
245 |
246 | typedef struct SYSTEM_SYMBOLS_PARAMS {
247 | PVOID LowboxSessionMapLock;
248 | PVOID g_SessionLowboxArray;
249 | PVOID g_SessionLowboxMap;
250 | PVOID SepLearningModeTokenCount;
251 | PVOID g_SepSidMapping;
252 | PVOID SepTokenCapabilitySidSharingEnabled;
253 | PVOID SepDuplicateToken;
254 | }SYSTEM_SYMBOLS_PARAMS, * PSYSTEM_SYMBOLS_PARAMS;
255 |
256 | BYTE g_original_bytes[16];
257 | PVOID g_original_func;
258 | #pragma comment(lib, "ntdll.lib")
259 | NTSTATUS
260 | NTSYSAPI
261 | RtlGetLastNtStatus(
262 | VOID
263 | );
264 | typedef NTSTATUS(*PNT_CREATE_LOWBOX_TOKEN)(
265 | _Out_ PHANDLE TokenHandle,
266 | _In_ HANDLE ExistingTokenHandle,
267 | _In_ ACCESS_MASK DesiredAccess,
268 | _In_ POBJECT_ATTRIBUTES ObjectAttributes,
269 | _In_ PSID PackageSid,
270 | _In_ ULONG CapabilityCount,
271 | _In_ PSID_AND_ATTRIBUTES Capabilities,
272 | _In_ ULONG HandleCount,
273 | _In_ HANDLE* Handles);
274 |
275 | PNT_CREATE_LOWBOX_TOKEN NtCreateLowboxToken;
276 |
277 | NTSTATUS NTAPI MyNtCreateLowboxToken(
278 | _Out_ PHANDLE TokenHandle,
279 | _In_ HANDLE ExistingTokenHandle,
280 | _In_ ACCESS_MASK DesiredAccess,
281 | _In_ POBJECT_ATTRIBUTES ObjectAttributes,
282 | _In_ PSID PackageSid,
283 | _In_ ULONG CapabilityCount,
284 | _In_ PSID_AND_ATTRIBUTES Capabilities,
285 | _In_ ULONG HandleCount,
286 | _In_ HANDLE* Handles)
287 | {
288 | LOWBOXTOKEN_PARAMS lowbox;
289 |
290 | lowbox.TokenHandle = TokenHandle;
291 | lowbox.ExistingTokenHandle = ExistingTokenHandle;
292 | lowbox.DesiredAccess = DesiredAccess;
293 | lowbox.ObjectAttributes = ObjectAttributes;
294 | lowbox.PackageSid = PackageSid;
295 | lowbox.CapabilityCount = CapabilityCount;
296 | lowbox.Capabilities = Capabilities;
297 | lowbox.HandleCount = HandleCount;
298 | lowbox.Handles = Handles;
299 |
300 | DWORD btr;
301 |
302 | if (DeviceIoControl(hKernel, IOCTL_NTCREATELOWBOXTOKEN, &lowbox, sizeof(lowbox), NULL, 0, &btr, NULL) == FALSE)
303 | {
304 | printf("error %08x\n", *(NTSTATUS*)((ULONG_PTR)NtCurrentTeb() + 0x1250));
305 | return *(NTSTATUS*)((ULONG_PTR)NtCurrentTeb() + 0x1250); //teb->lastntstatusvalue
306 | }
307 | else
308 | {
309 | return 0;
310 | }
311 | }
312 |
313 | BOOL InstallHook()
314 | {
315 | BYTE jump[] = {
316 | 0x48, 0xB8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // mov rax, addr
317 | 0xFF, 0xE0 // jmp rax
318 | };
319 |
320 | HMODULE hNtdll = GetModuleHandleA("ntdll.dll");
321 | if (!hNtdll) return FALSE;
322 |
323 | g_original_func = GetProcAddress(hNtdll, "NtCreateLowBoxToken");
324 | if (!g_original_func)
325 | {
326 | printf("no ntclt \n");
327 | return FALSE;
328 | }
329 |
330 | memcpy(g_original_bytes, g_original_func, 16);
331 |
332 | PVOID pBuf = VirtualAlloc(NULL, 0x20, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
333 |
334 | memcpy(pBuf, g_original_func, 0x20);
335 |
336 | NtCreateLowboxToken = (PNT_CREATE_LOWBOX_TOKEN)pBuf;
337 |
338 | *(UINT64*)(jump + 2) = (UINT64)MyNtCreateLowboxToken;
339 |
340 | DWORD oldProtect;
341 | if (!VirtualProtect(g_original_func, 16, PAGE_EXECUTE_READWRITE, &oldProtect))
342 | {
343 | printf("vp failed %u\n ", GetLastError());
344 |
345 | }
346 |
347 |
348 | memcpy(g_original_func, jump, sizeof(jump));
349 |
350 |
351 | VirtualProtect(g_original_func, 16, PAGE_EXECUTE_READ, &oldProtect);
352 |
353 | return TRUE;
354 | }
355 | #include
356 | #include
357 | #include
358 | #include
359 |
360 | #pragma comment(lib, "Userenv.lib")
361 |
362 | //List of allowed capabilities for the application
363 | extern WELL_KNOWN_SID_TYPE app_capabilities[] =
364 | {
365 | WinCapabilityPrivateNetworkClientServerSid,
366 | };
367 |
368 | WCHAR container_name[] = L"MtSandboxTest";
369 | WCHAR container_desc[] = L"MalwareTech Sandbox Test";
370 |
371 |
372 | BOOL IsInAppContainer();
373 | BOOL SetSecurityCapabilities(PSID container_sid, SECURITY_CAPABILITIES* capabilities, PDWORD num_capabilities);
374 | BOOL GrantNamedObjectAccess(PSID appcontainer_sid, CHAR* object_name, SE_OBJECT_TYPE object_type, DWORD access_mask);
375 |
376 | BOOL RunExecutableInContainer(CHAR* executable_path)
377 | {
378 | PSID sid = NULL;
379 | HRESULT result;
380 | SECURITY_CAPABILITIES SecurityCapabilities = { 0 };
381 | DWORD num_capabilities = 0;
382 | SIZE_T attribute_size = 0;
383 | STARTUPINFOEXA startup_info = { 0 };
384 | PROCESS_INFORMATION process_info = { 0 };
385 | CHAR desktop_file[MAX_PATH];
386 | HANDLE file_handle = INVALID_HANDLE_VALUE;
387 | CHAR* string_sid = NULL;
388 | BOOL success = FALSE;
389 |
390 | do //Not a loop
391 | {
392 | result = CreateAppContainerProfile(container_name, container_name, container_desc, NULL, 0, &sid);
393 | if (!SUCCEEDED(result))
394 | {
395 | if (HRESULT_CODE(result) == ERROR_ALREADY_EXISTS)
396 | {
397 | result = DeriveAppContainerSidFromAppContainerName(container_name, &sid);
398 | if (!SUCCEEDED(result))
399 | {
400 | printf("Failed to get existing AppContainer name, error code: %d", HRESULT_CODE(result));
401 | break;
402 | }
403 | }
404 | else {
405 | printf("Failed to create AppContainer, last error: %d\n", HRESULT_CODE(result));
406 | break;
407 | }
408 | }
409 |
410 | printf("[Container Info]\nname: %ws\ndescription: %ws\n", container_name, container_desc);
411 |
412 | if (ConvertSidToStringSidA(sid, &string_sid))
413 | printf("Sid: %s\n\n", string_sid);
414 |
415 | if (!SetSecurityCapabilities(sid, &SecurityCapabilities, &num_capabilities))
416 | {
417 | printf("Failed to set security capabilities, last error: %d\n", GetLastError());
418 | break;
419 | }
420 |
421 | ExpandEnvironmentStringsA("%userprofile%\\desktop\\allowed_test.txt", desktop_file, MAX_PATH - 1);
422 |
423 | file_handle = CreateFileA(desktop_file, GENERIC_ALL, NULL, NULL, OPEN_ALWAYS, NULL, NULL);
424 | if (file_handle == INVALID_HANDLE_VALUE)
425 | {
426 | printf("Failed to create file %s, last error: %d\n", desktop_file, GetLastError());
427 | break;
428 | }
429 |
430 | if (!GrantNamedObjectAccess(sid, desktop_file, SE_FILE_OBJECT, FILE_ALL_ACCESS))
431 | {
432 | printf("Failed to grant explicit access to %s\n", desktop_file);
433 | break;
434 | }
435 |
436 | InitializeProcThreadAttributeList(NULL, 1, NULL, &attribute_size);
437 | startup_info.lpAttributeList = (LPPROC_THREAD_ATTRIBUTE_LIST)malloc(attribute_size);
438 |
439 | if (!InitializeProcThreadAttributeList(startup_info.lpAttributeList, 1, NULL, &attribute_size))
440 | {
441 | printf("InitializeProcThreadAttributeList() failed, last error: %d", GetLastError());
442 | break;
443 | }
444 |
445 | if (!UpdateProcThreadAttribute(startup_info.lpAttributeList, 0, PROC_THREAD_ATTRIBUTE_SECURITY_CAPABILITIES,
446 | &SecurityCapabilities, sizeof(SecurityCapabilities), NULL, NULL))
447 | {
448 | printf("UpdateProcThreadAttribute() failed, last error: %d", GetLastError());
449 | break;
450 | }
451 |
452 | if (!CreateProcessA(executable_path, NULL, NULL, NULL, FALSE, EXTENDED_STARTUPINFO_PRESENT, NULL, NULL,
453 | (LPSTARTUPINFOA)&startup_info, &process_info))
454 | {
455 | printf("Failed to create process %s, last error: %d\n", executable_path, GetLastError());
456 | break;
457 | }
458 |
459 | printf("Successfully executed %s in AppContainer\n", executable_path);
460 | success = TRUE;
461 |
462 | } while (FALSE);
463 |
464 | if (startup_info.lpAttributeList)
465 | DeleteProcThreadAttributeList(startup_info.lpAttributeList);
466 |
467 | if (SecurityCapabilities.Capabilities)
468 | free(SecurityCapabilities.Capabilities);
469 |
470 | if (sid)
471 | FreeSid(sid);
472 |
473 | if (string_sid)
474 | LocalFree(string_sid);
475 |
476 | if (file_handle != INVALID_HANDLE_VALUE)
477 | CloseHandle(file_handle);
478 |
479 | if (file_handle != INVALID_HANDLE_VALUE && !success)
480 | DeleteFileA(desktop_file);
481 |
482 | return success;
483 | }
484 | BOOL SetSecurityCapabilities(PSID container_sid, SECURITY_CAPABILITIES* capabilities, PDWORD num_capabilities)
485 | {
486 | DWORD sid_size = SECURITY_MAX_SID_SIZE;
487 | DWORD num_capabilities_ = sizeof(app_capabilities) / sizeof(DWORD);
488 | SID_AND_ATTRIBUTES* attributes;
489 | BOOL success = TRUE;
490 |
491 | attributes = (SID_AND_ATTRIBUTES*)malloc(sizeof(SID_AND_ATTRIBUTES) * num_capabilities_);
492 |
493 | ZeroMemory(capabilities, sizeof(SECURITY_CAPABILITIES));
494 | ZeroMemory(attributes, sizeof(SID_AND_ATTRIBUTES) * num_capabilities_);
495 |
496 | for (unsigned int i = 0; i < num_capabilities_; i++)
497 | {
498 | attributes[i].Sid = malloc(SECURITY_MAX_SID_SIZE);
499 | if (!CreateWellKnownSid(app_capabilities[i], NULL, attributes[i].Sid, &sid_size))
500 | {
501 | success = FALSE;
502 | break;
503 | }
504 | attributes[i].Attributes = SE_GROUP_ENABLED;
505 | }
506 |
507 | if (success == FALSE)
508 | {
509 | for (unsigned int i = 0; i < num_capabilities_; i++)
510 | {
511 | if (attributes[i].Sid)
512 | LocalFree(attributes[i].Sid);
513 | }
514 |
515 | free(attributes);
516 | attributes = NULL;
517 | num_capabilities_ = 0;
518 | }
519 |
520 | capabilities->Capabilities = attributes;
521 | capabilities->CapabilityCount = num_capabilities_;
522 | capabilities->AppContainerSid = container_sid;
523 | *num_capabilities = num_capabilities_;
524 |
525 | return success;
526 | }
527 |
528 | /*
529 | Explicitly grants the container access to a named object (file, section, etc)
530 | */
531 | BOOL GrantNamedObjectAccess(PSID appcontainer_sid, CHAR* object_name, SE_OBJECT_TYPE object_type, DWORD access_mask)
532 | {
533 | EXPLICIT_ACCESS_A explicit_access;
534 | PACL original_acl = NULL, new_acl = NULL;
535 | DWORD status;
536 | BOOL success = FALSE;
537 |
538 | do
539 | {
540 | explicit_access.grfAccessMode = GRANT_ACCESS;
541 | explicit_access.grfAccessPermissions = access_mask;
542 | explicit_access.grfInheritance = OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE;
543 |
544 | explicit_access.Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
545 | explicit_access.Trustee.pMultipleTrustee = NULL;
546 | explicit_access.Trustee.ptstrName = (CHAR*)appcontainer_sid;
547 | explicit_access.Trustee.TrusteeForm = TRUSTEE_IS_SID;
548 | explicit_access.Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
549 |
550 | status = GetNamedSecurityInfoA(object_name, object_type, DACL_SECURITY_INFORMATION, NULL, NULL, &original_acl,
551 | NULL, NULL);
552 | if (status != ERROR_SUCCESS)
553 | {
554 | printf("GetNamedSecurityInfoA() failed for %s, error: %d\n", object_name, status);
555 | break;
556 | }
557 |
558 | status = SetEntriesInAclA(1, &explicit_access, original_acl, &new_acl);
559 | if (status != ERROR_SUCCESS)
560 | {
561 | printf("SetEntriesInAclA() failed for %s, error: %d\n", object_name, status);
562 | break;
563 | }
564 |
565 | status = SetNamedSecurityInfoA(object_name, object_type, DACL_SECURITY_INFORMATION, NULL, NULL, new_acl, NULL);
566 | if (status != ERROR_SUCCESS)
567 | {
568 | printf("SetNamedSecurityInfoA() failed for %s, error: %d\n", object_name, status);
569 | break;
570 | }
571 |
572 | success = TRUE;
573 |
574 | } while (FALSE);
575 |
576 | /* if (original_acl)
577 | LocalFree(original_acl);
578 |
579 | if (new_acl)
580 | LocalFree(new_acl);*/
581 |
582 | return success;
583 | }
584 | BOOL LoadSymbol()
585 | {
586 | //replace with your symbol path
587 | //you'd better have the latest dbghelp.dll placed with this exe
588 |
589 | const char* symPath = "c:\\Symbols";
590 | DWORD64 address;
591 | PVOID kernelbase = GetKernelBase();
592 | LOWBOXTOKEN_PARAMS tp;
593 |
594 |
595 | printf("Kernel Base: %p\n", kernelbase);
596 |
597 |
598 |
599 | for (int i = 0; i < sizeof(symbols) / sizeof(symbols[0]); i++) {
600 | address = 0;
601 | GetKernelSymbolAddress(symPath, symbols[i], &address);
602 |
603 | if (address == 0)
604 | {
605 | KernelSymbols[i] = 0;
606 |
607 | if (strcmp(symbols[i], "SepLearningModeTokenCount") == 0)
608 | {
609 | printf("SepLearningModeTokenCount not found , allowed\n");
610 | }
611 | else
612 | {
613 | printf("failed to get kernel symbol\n");
614 | return FALSE;
615 | }
616 | }
617 | else
618 | {
619 | *(ULONG_PTR*)((ULONG_PTR)&tp + sizeof(ULONG_PTR) * i ) = (ULONG_PTR)(address + (ULONG_PTR)kernelbase);
620 | }
621 | printf("%s Kernel Address: %p\n", symbols[i], *(ULONG_PTR*)((ULONG_PTR)&tp + sizeof(ULONG_PTR) * i));
622 | }
623 |
624 | DWORD btr;
625 |
626 | if (DeviceIoControl(hKernel, IOCTL_GET_SYSTEM_SYMBOLS, &tp, sizeof(tp), NULL, 0, &btr, NULL) == FALSE)
627 | {
628 | printf("load system symbol failed %u\n", GetLastError());
629 | return FALSE;
630 | }
631 |
632 | return TRUE;
633 |
634 | }
635 | int main()
636 | {
637 | if (LoadKernelDriver() == FALSE)
638 | {
639 | printf("load driver failed %u\n", GetLastError());
640 | return 0;
641 | }
642 |
643 | if (LoadSymbol() == FALSE)
644 | {
645 | return 0;
646 | }
647 |
648 | if (InstallHook() == FALSE)
649 | {
650 | return 0;
651 | }
652 |
653 |
654 |
655 |
656 | CHAR Name[] = "c:\\windows\\system32\\notepad.exe";
657 |
658 | RunExecutableInContainer(Name);
659 |
660 |
661 |
662 | }
663 |
--------------------------------------------------------------------------------
/driver/LowboxToken.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 | #include "ntddk.h"
3 | #include
4 |
5 | UNICODE_STRING DeviceName = RTL_CONSTANT_STRING(L"\\Device\\NtCreateLowboxToken");
6 | UNICODE_STRING DosDeviceName = RTL_CONSTANT_STRING(L"\\DosDevices\\NtCreateLowboxToken");
7 |
8 | #define IOCTL_NTCREATELOWBOXTOKEN CTL_CODE(FILE_DEVICE_UNKNOWN , 0x100 , METHOD_BUFFERED , FILE_ANY_ACCESS)
9 | #define IOCTL_GET_SYSTEM_SYMBOLS CTL_CODE(FILE_DEVICE_UNKNOWN , 0x101 , METHOD_BUFFERED , FILE_ANY_ACCESS)
10 |
11 | typedef struct _LOWBOXTOKEN_PARAMS {
12 | PHANDLE TokenHandle; // _Out_
13 | HANDLE ExistingTokenHandle; // _In_
14 | ACCESS_MASK DesiredAccess; // _In_
15 | POBJECT_ATTRIBUTES ObjectAttributes; // _In_
16 | PSID PackageSid; // _In_
17 | ULONG CapabilityCount; // _In_
18 | PSID_AND_ATTRIBUTES Capabilities; // _In_
19 | ULONG HandleCount; // _In_
20 | HANDLE* Handles; // _In_
21 | } LOWBOXTOKEN_PARAMS, * PLOWBOXTOKEN_PARAMS;
22 |
23 | typedef NTSTATUS(*PSEP_DUPLICATE_TOKEN)(
24 | PVOID ExistingToken,
25 | POBJECT_ATTRIBUTES ObjectAttributes,
26 | BOOLEAN EffectiveOnly,
27 | TOKEN_TYPE TokenType,
28 | SECURITY_IMPERSONATION_LEVEL ImpersonationLevel,
29 | KPROCESSOR_MODE RequestorMode,
30 | BOOLEAN SkipNonInheritableSecurityAttributes,
31 | PVOID* DuplicateToken
32 | );
33 |
34 | typedef struct SYSTEM_SYMBOLS_PARAMS {
35 | PVOID LowboxSessionMapLock;
36 | PVOID g_SessionLowboxArray;
37 | PVOID g_SessionLowboxMap;
38 | PVOID SepLearningModeTokenCount;
39 | PVOID g_SepSidMapping;
40 | PVOID SepTokenCapabilitySidSharingEnabled;
41 | PSEP_DUPLICATE_TOKEN SepDuplicateToken;
42 | }SYSTEM_SYMBOLS_PARAMS , *PSYSTEM_SYMBOLS_PARAMS;
43 |
44 |
45 | FORCEINLINE
46 | VOID
47 | ProbeForWriteHandle( PHANDLE Address)
48 |
49 | {
50 | if (Address >= (HANDLE* const)MM_USER_PROBE_ADDRESS) {
51 | Address = (HANDLE* const)MM_USER_PROBE_ADDRESS;
52 | }
53 |
54 | *((volatile HANDLE*)Address) = *Address;
55 | return;
56 | }
57 |
58 |
59 | FORCEINLINE
60 | UCHAR
61 | ProbeAndReadUchar(UCHAR* Address)
62 |
63 | {
64 | if (Address >= (UCHAR* const)MM_USER_PROBE_ADDRESS) {
65 | Address = (UCHAR* const)MM_USER_PROBE_ADDRESS;
66 | }
67 |
68 | _ReadWriteBarrier();
69 | return *((volatile UCHAR*)Address);
70 | }
71 |
72 |
73 |
74 | #define SepAcquireTokenReadLock(T) KeEnterCriticalRegion(); \
75 | ExAcquireResourceSharedLite((T)->TokenLock, TRUE)
76 |
77 | #define SepAcquireTokenWriteLock(T) KeEnterCriticalRegion(); \
78 | ExAcquireResourceExclusiveLite((T)->TokenLock, TRUE); \
79 | KeMemoryBarrier();
80 |
81 | #define SepReleaseTokenReadLock(T) ExReleaseResourceLite((T)->TokenLock); \
82 | KeLeaveCriticalRegion()
83 |
84 | #define SepReleaseTokenWriteLock(T,M) \
85 | { \
86 | if ((M)) { \
87 | ZwAllocateLocallyUniqueId( &((PTOKEN)(T))->ModifiedId ); \
88 | } \
89 | KeMemoryBarrier(); \
90 | SepReleaseTokenReadLock( T ); \
91 | }
92 |
93 | //
94 | // Currently define Flags for "OBJECT" ACE types.
95 | //
96 |
97 | #define ACE_OBJECT_TYPE_PRESENT 0x1
98 | #define ACE_INHERITED_OBJECT_TYPE_PRESENT 0x2
99 |
100 | #define IsAllowedAceType(Ace) ( \
101 | (((PACE_HEADER)(Ace))->AceType == ACCESS_ALLOWED_ACE_TYPE || \
102 | ((PACE_HEADER)(Ace))->AceType == ACCESS_DENIED_ACE_TYPE || \
103 | ((PACE_HEADER)(Ace))->AceType == SYSTEM_AUDIT_ACE_TYPE || \
104 | ((PACE_HEADER)(Ace))->AceType == SYSTEM_ALARM_ACE_TYPE || \
105 | ((PACE_HEADER)(Ace))->AceType == ACCESS_ALLOWED_CALLBACK_ACE_TYPE || \
106 | ((PACE_HEADER)(Ace))->AceType == ACCESS_DENIED_CALLBACK_ACE_TYPE || \
107 | ((PACE_HEADER)(Ace))->AceType == SYSTEM_AUDIT_CALLBACK_ACE_TYPE || \
108 | ((PACE_HEADER)(Ace))->AceType == SYSTEM_ALARM_CALLBACK_ACE_TYPE || \
109 | ((PACE_HEADER)(Ace))->AceType == SYSTEM_MANDATORY_LABEL_ACE_TYPE || \
110 | ((PACE_HEADER)(Ace))->AceType == SYSTEM_RESOURCE_ATTRIBUTE_ACE_TYPE || \
111 | ((PACE_HEADER)(Ace))->AceType == SYSTEM_SCOPED_POLICY_ID_ACE_TYPE || \
112 | ((PACE_HEADER)(Ace))->AceType == SYSTEM_PROCESS_TRUST_LABEL_ACE_TYPE || \
113 | ((PACE_HEADER)(Ace))->AceType == SYSTEM_ACCESS_FILTER_ACE_TYPE) \
114 | )
115 |
116 | #define IsCompoundAceType(Ace) ( \
117 | (((PACE_HEADER)(Ace))->AceType == ACCESS_ALLOWED_COMPOUND_ACE_TYPE))
118 |
119 | #define IsObjectAceType(Ace) ( \
120 | (((PACE_HEADER)(Ace))->AceType >= ACCESS_MIN_MS_OBJECT_ACE_TYPE) && \
121 | (((PACE_HEADER)(Ace))->AceType <= ACCESS_MAX_MS_OBJECT_ACE_TYPE) \
122 | )
123 |
124 | #define IsCallbackObjectAceType(Ace) ( \
125 | (((PACE_HEADER)(Ace))->AceType >= ACCESS_ALLOWED_CALLBACK_OBJECT_ACE_TYPE) && \
126 | (((PACE_HEADER)(Ace))->AceType <= ACCESS_DENIED_CALLBACK_OBJECT_ACE_TYPE) \
127 | )
128 |
129 | #define IsSytstemCallbackObjectAceType(Ace) ( \
130 | (((PACE_HEADER)(Ace))->AceType >= SYSTEM_AUDIT_CALLBACK_OBJECT_ACE_TYPE) && \
131 | (((PACE_HEADER)(Ace))->AceType <= SYSTEM_ALARM_CALLBACK_OBJECT_ACE_TYPE) \
132 | )
133 | #define RtlObjectAceObjectTypePresent( Ace ) \
134 | ((((PKNOWN_OBJECT_ACE)(Ace))->Flags & ACE_OBJECT_TYPE_PRESENT) != 0 )
135 | #define RtlObjectAceInheritedObjectTypePresent( Ace ) \
136 | ((((PKNOWN_OBJECT_ACE)(Ace))->Flags & ACE_INHERITED_OBJECT_TYPE_PRESENT) != 0 )
137 |
138 | #define RtlObjectAceSid( Ace ) \
139 | ((PSID)(((PUCHAR)&(((PKNOWN_OBJECT_ACE)(Ace))->SidStart)) + \
140 | (RtlObjectAceObjectTypePresent(Ace) ? sizeof(GUID) : 0 ) + \
141 | (RtlObjectAceInheritedObjectTypePresent(Ace) ? sizeof(GUID) : 0 )))
142 |
143 |
144 | #define FirstAce(Acl) ((PVOID)((PUCHAR)(Acl) + sizeof(ACL)))
145 | #define NextAce(Ace) ((PVOID)((PUCHAR)(Ace) + ((PACE_HEADER)(Ace))->AceSize))
146 |
147 | #define SID_HASH_ULONG(s) ((((PISID)s)->SubAuthority[((PISID)s)->SubAuthorityCount - 1]))
148 | #define AUTHZ_SID_HASH_BYTE(s) ((UCHAR)(((PISID)s)->SubAuthority[((PISID)s)->SubAuthorityCount - 1]))
149 | #define AUTHZ_SID_HASH_HIGH 16
150 | #define AUTHZ_SID_HASH_LOOKUP(table, byte) (((table)[(byte) & 0xf]) & ((table)[AUTHZ_SID_HASH_HIGH + (((byte) & 0xf0) >> 4)]))
151 | #define AUTHZI_SID_HASH_ENTRY_NUM_BITS (8*sizeof(SID_HASH_ENTRY))
152 |
153 | #define RtlLengthRequiredSidCount(Count) (8 + (4 * Count))
154 |
155 | #define LongAlignSize(Size) (((ULONG)(Size) + 3) & -4)
156 |
157 | const UCHAR SidHashByteToIndexLookupTable[] = {
158 | 0x09, 0x00, 0x01, 0x00, 0x02, 0x00, 0x01, 0x00, 0x03, 0x00, 0x01, 0x00, 0x02, 0x00, 0x01, 0x00,
159 | 0x04, 0x00, 0x01, 0x00, 0x02, 0x00, 0x01, 0x00, 0x03, 0x00, 0x01, 0x00, 0x02, 0x00, 0x01, 0x00,
160 | 0x05, 0x00, 0x01, 0x00, 0x02, 0x00, 0x01, 0x00, 0x03, 0x00, 0x01, 0x00, 0x02, 0x00, 0x01, 0x00,
161 | 0x04, 0x00, 0x01, 0x00, 0x02, 0x00, 0x01, 0x00, 0x03, 0x00, 0x01, 0x00, 0x02, 0x00, 0x01, 0x00,
162 | 0x06, 0x00, 0x01, 0x00, 0x02, 0x00, 0x01, 0x00, 0x03, 0x00, 0x01, 0x00, 0x02, 0x00, 0x01, 0x00,
163 | 0x04, 0x00, 0x01, 0x00, 0x02, 0x00, 0x01, 0x00, 0x03, 0x00, 0x01, 0x00, 0x02, 0x00, 0x01, 0x00,
164 | 0x05, 0x00, 0x01, 0x00, 0x02, 0x00, 0x01, 0x00, 0x03, 0x00, 0x01, 0x00, 0x02, 0x00, 0x01, 0x00,
165 | 0x04, 0x00, 0x01, 0x00, 0x02, 0x00, 0x01, 0x00, 0x03, 0x00, 0x01, 0x00, 0x02, 0x00, 0x01, 0x00,
166 | 0x07, 0x00, 0x01, 0x00, 0x02, 0x00, 0x01, 0x00, 0x03, 0x00, 0x01, 0x00, 0x02, 0x00, 0x01, 0x00,
167 | 0x04, 0x00, 0x01, 0x00, 0x02, 0x00, 0x01, 0x00, 0x03, 0x00, 0x01, 0x00, 0x02, 0x00, 0x01, 0x00,
168 | 0x05, 0x00, 0x01, 0x00, 0x02, 0x00, 0x01, 0x00, 0x03, 0x00, 0x01, 0x00, 0x02, 0x00, 0x01, 0x00,
169 | 0x04, 0x00, 0x01, 0x00, 0x02, 0x00, 0x01, 0x00, 0x03, 0x00, 0x01, 0x00, 0x02, 0x00, 0x01, 0x00,
170 | 0x06, 0x00, 0x01, 0x00, 0x02, 0x00, 0x01, 0x00, 0x03, 0x00, 0x01, 0x00, 0x02, 0x00, 0x01, 0x00,
171 | 0x04, 0x00, 0x01, 0x00, 0x02, 0x00, 0x01, 0x00, 0x03, 0x00, 0x01, 0x00, 0x02, 0x00, 0x01, 0x00,
172 | 0x05, 0x00, 0x01, 0x00, 0x02, 0x00, 0x01, 0x00, 0x03, 0x00, 0x01, 0x00, 0x02, 0x00, 0x01, 0x00,
173 | 0x04, 0x00, 0x01, 0x00, 0x02, 0x00, 0x01, 0x00, 0x03, 0x00, 0x01, 0x00, 0x02, 0x00, 0x01, 0x00
174 | };
175 |
176 |
177 |
178 | #define RtlpSaclAddrSecurityDescriptor( SD ) \
179 | ( (!((SD)->Control & SE_SACL_PRESENT) ) ? \
180 | (PACL)NULL : \
181 | ( ((SD)->Control & SE_SELF_RELATIVE) ? \
182 | ( (((SECURITY_DESCRIPTOR_RELATIVE *) (SD))->Sacl == 0) ? ((PACL) NULL) : \
183 | (PACL)RtlOffsetToPointer((SD), ((SECURITY_DESCRIPTOR_RELATIVE *) (SD))->Sacl) \
184 | ) : \
185 | (PACL)((SD)->Sacl) \
186 | ) \
187 | )
188 |
189 |
190 | #define RtlpDaclAddrSecurityDescriptor( SD ) \
191 | ( (!((SD)->Control & SE_DACL_PRESENT) ) ? \
192 | (PACL)NULL : \
193 | ( ((SD)->Control & SE_SELF_RELATIVE) ? \
194 | ( (((SECURITY_DESCRIPTOR_RELATIVE *) (SD))->Dacl == 0) ? ((PACL) NULL) : \
195 | (PACL)RtlOffsetToPointer((SD), ((SECURITY_DESCRIPTOR_RELATIVE *) (SD))->Dacl) \
196 | ) : \
197 | (PACL)((SD)->Dacl) \
198 | ) \
199 | )
200 |
201 | #define ValidAclRevision(Acl) ((Acl)->AclRevision >= MIN_ACL_REVISION && \
202 | (Acl)->AclRevision <= MAX_ACL_REVISION )
203 |
204 | //
205 | // Macro to copy the state of the passed bits from the old security
206 | // descriptor (OldSD) into the Control field of the new one (NewSD)
207 | //
208 |
209 | #define RtlpPropagateControlBits( NewSD, OldSD, Bits ) \
210 | ( NewSD )->Control |= \
211 | ( \
212 | ( OldSD )->Control & ( Bits ) \
213 | )
214 |
215 | #define SEP_MAX_GROUP_COUNT 4096
216 |
217 |
218 | #define SEP_SID_AND_ATTRIBUTES_TAG 'aSeS'
219 | #define SEP_SECURITY_DESCRIPTOR_TAG 'dSeS'
220 | #define SEP_TOKEN_DYNAMIC_PART_TAG 'dTeS'
221 | #define SEP_SID_TAG 'iSeS'
222 | #define SEP_OBJECT_NAME_INFORMATION_TAG 'nOeS'
223 | #define SEP_SECURITY_ATTRIBUTES_TAG 'tAeS'
224 | #define SEP_SID_SHARING_TAG 'sSeS'
225 | #define SEP_LOWBOX_SESSION_TAG 'sLeS'
226 | #define RTL_PRIVATE_BUFFER_TAG 'bPtR'
227 | #define SEP_HANDLES_CAPTURE_TAG 'cHeS'
228 | #define SEP_ACL_TAG 'cAeS'
229 |
230 | typedef enum _APPCONTAINER_SID_TYPE
231 | {
232 | NotAppContainerSidType,
233 | ChildAppContainerSidType,
234 | ParentAppContainerSidType,
235 | InvalidAppContainerSidType,
236 | MaxAppContainerSidType
237 | } APPCONTAINER_SID_TYPE, * PAPPCONTAINER_SID_TYPE;
238 |
239 | typedef struct _SEP_TOKEN_PRIVILEGES {
240 | ULONGLONG Present;
241 | ULONGLONG Enabled;
242 | ULONGLONG EnabledByDefault;
243 | } SEP_TOKEN_PRIVILEGES, * PSEP_TOKEN_PRIVILEGES;
244 |
245 | typedef struct _SEP_AUDIT_POLICY {
246 | TOKEN_AUDIT_POLICY AdtTokenPolicy;
247 | UCHAR PolicySetStatus;
248 | } SEP_AUDIT_POLICY, * PSEP_AUDIT_POLICY;
249 |
250 | typedef struct _OB_HANDLE_REVOCATION_BLOCK {
251 | LIST_ENTRY RevocationInfos;
252 | EX_PUSH_LOCK Lock;
253 | EX_RUNDOWN_REF Rundown;
254 | } OB_HANDLE_REVOCATION_BLOCK, * POB_HANDLE_REVOCATION_BLOCK;
255 |
256 | typedef struct _SEP_CACHED_HANDLES_TABLE {
257 | EX_PUSH_LOCK Lock; // +0x000
258 | PRTL_DYNAMIC_HASH_TABLE HashTable; // +0x008
259 | } SEP_CACHED_HANDLES_TABLE, * PSEP_CACHED_HANDLES_TABLE;
260 |
261 | typedef struct _SEP_LOGON_SESSION_REFERENCES {
262 | struct _SEP_LOGON_SESSION_REFERENCES* Next;
263 | LUID LogonId;
264 | LUID BuddyLogonId;
265 | LONGLONG ReferenceCount;
266 | ULONG Flags;
267 | PVOID pDeviceMap;
268 | PVOID Token;
269 | UNICODE_STRING AccountName;
270 | UNICODE_STRING AuthorityName;
271 | SEP_CACHED_HANDLES_TABLE CachedHandlesTable;
272 | EX_PUSH_LOCK SharedDataLock;
273 | PVOID SharedClaimAttributes;
274 | PVOID SharedSidValues;
275 | OB_HANDLE_REVOCATION_BLOCK RevocationBlock;
276 | PVOID ServerSilo;
277 | LUID SiblingAuthId;
278 | LIST_ENTRY TokenList;
279 | } SEP_LOGON_SESSION_REFERENCES, * PSEP_LOGON_SESSION_REFERENCES;
280 |
281 | typedef struct _TOKEN {
282 | TOKEN_SOURCE TokenSource; // 0x000
283 | LUID TokenId; // 0x010
284 | LUID AuthenticationId; // 0x018
285 | LUID ParentTokenId; // 0x020
286 | LARGE_INTEGER ExpirationTime; // 0x028
287 | PVOID TokenLock; // 0x030
288 | LUID ModifiedId; // 0x038
289 | SEP_TOKEN_PRIVILEGES Privileges; // 0x040
290 | SEP_AUDIT_POLICY AuditPolicy; // 0x058
291 | ULONG SessionId; // 0x078
292 | ULONG UserAndGroupCount; // 0x07c
293 | ULONG RestrictedSidCount; // 0x080
294 | ULONG VariableLength; // 0x084
295 | ULONG DynamicCharged; // 0x088
296 | ULONG DynamicAvailable; // 0x08c
297 | ULONG DefaultOwnerIndex; // 0x090
298 | PSID_AND_ATTRIBUTES UserAndGroups; // 0x098
299 | PSID_AND_ATTRIBUTES RestrictedSids; // 0x0a0
300 | PSID PrimaryGroup; // 0x0a8
301 | PVOID DynamicPart; // 0x0b0
302 | PACL DefaultDacl; // 0x0b8
303 | TOKEN_TYPE TokenType; // 0x0c0
304 | SECURITY_IMPERSONATION_LEVEL ImpersonationLevel; // 0x0c4
305 | ULONG TokenFlags; // 0x0c8
306 | UCHAR TokenInUse; // 0x0cc
307 | ULONG IntegrityLevelIndex; // 0x0d0
308 | ULONG MandatoryPolicy; // 0x0d4
309 | PSEP_LOGON_SESSION_REFERENCES LogonSession; // 0x0d8
310 | LUID OriginatingLogonSession; // 0x0e0
311 | SID_AND_ATTRIBUTES_HASH SidHash; // 0x0e8
312 | SID_AND_ATTRIBUTES_HASH RestrictedSidHash; // 0x1f8
313 | PVOID pSecurityAttributes; // 0x308
314 | PSID Package; // 0x310
315 | PSID_AND_ATTRIBUTES Capabilities; // 0x318
316 | ULONG CapabilityCount; // 0x320
317 | SID_AND_ATTRIBUTES_HASH CapabilitiesHash; // 0x328
318 | PVOID LowboxNumberEntry; // 0x438
319 | PVOID LowboxHandlesEntry; // 0x440
320 | PVOID pClaimAttributes; // 0x448
321 | PSID TrustLevelSid; // 0x450
322 | PVOID TrustLinkedToken; // 0x458
323 | PSID IntegrityLevelSidValue; // 0x460
324 | PVOID TokenSidValues; // 0x468
325 | PVOID IndexEntry; // 0x470
326 | PVOID DiagnosticInfo; // 0x478
327 | PVOID BnoIsolationHandlesEntry; // 0x480
328 | PVOID SessionObject; // 0x488
329 | ULONGLONG VariablePart; // 0x490
330 | } TOKEN, * PTOKEN;
331 |
332 | //
333 | // Group attributes
334 | //
335 |
336 | #define SE_GROUP_MANDATORY (0x00000001L)
337 | #define SE_GROUP_ENABLED_BY_DEFAULT (0x00000002L)
338 | #define SE_GROUP_ENABLED (0x00000004L)
339 | #define SE_GROUP_OWNER (0x00000008L)
340 | #define SE_GROUP_USE_FOR_DENY_ONLY (0x00000010L)
341 | #define SE_GROUP_INTEGRITY (0x00000020L)
342 | #define SE_GROUP_INTEGRITY_ENABLED (0x00000040L)
343 | #define SE_GROUP_LOGON_ID (0xC0000000L)
344 | #define SE_GROUP_RESOURCE (0x20000000L)
345 |
346 | #define SE_GROUP_VALID_ATTRIBUTES (SE_GROUP_MANDATORY | \
347 | SE_GROUP_ENABLED_BY_DEFAULT | \
348 | SE_GROUP_ENABLED | \
349 | SE_GROUP_OWNER | \
350 | SE_GROUP_USE_FOR_DENY_ONLY | \
351 | SE_GROUP_LOGON_ID | \
352 | SE_GROUP_RESOURCE | \
353 | SE_GROUP_INTEGRITY | \
354 | SE_GROUP_INTEGRITY_ENABLED)
355 |
356 | #define SE_MIN_WELL_KNOWN_PRIVILEGE (2L)
357 | #define SE_CREATE_TOKEN_PRIVILEGE (2L)
358 | #define SE_ASSIGNPRIMARYTOKEN_PRIVILEGE (3L)
359 | #define SE_LOCK_MEMORY_PRIVILEGE (4L)
360 | #define SE_INCREASE_QUOTA_PRIVILEGE (5L)
361 | #define SE_UNSOLICITED_INPUT_PRIVILEGE (6L)
362 | #define SE_MACHINE_ACCOUNT_PRIVILEGE (6L)
363 | #define SE_TCB_PRIVILEGE (7L)
364 | #define SE_SECURITY_PRIVILEGE (8L)
365 | #define SE_TAKE_OWNERSHIP_PRIVILEGE (9L)
366 | #define SE_LOAD_DRIVER_PRIVILEGE (10L)
367 | #define SE_SYSTEM_PROFILE_PRIVILEGE (11L)
368 | #define SE_SYSTEMTIME_PRIVILEGE (12L)
369 | #define SE_PROF_SINGLE_PROCESS_PRIVILEGE (13L)
370 | #define SE_INC_BASE_PRIORITY_PRIVILEGE (14L)
371 | #define SE_CREATE_PAGEFILE_PRIVILEGE (15L)
372 | #define SE_CREATE_PERMANENT_PRIVILEGE (16L)
373 | #define SE_BACKUP_PRIVILEGE (17L)
374 | #define SE_RESTORE_PRIVILEGE (18L)
375 | #define SE_SHUTDOWN_PRIVILEGE (19L)
376 | #define SE_DEBUG_PRIVILEGE (20L)
377 | #define SE_AUDIT_PRIVILEGE (21L)
378 | #define SE_SYSTEM_ENVIRONMENT_PRIVILEGE (22L)
379 | #define SE_CHANGE_NOTIFY_PRIVILEGE (23L)
380 | #define SE_REMOTE_SHUTDOWN_PRIVILEGE (24L)
381 | #define SE_UNDOCK_PRIVILEGE (25L)
382 | #define SE_SYNC_AGENT_PRIVILEGE (26L)
383 | #define SE_ENABLE_DELEGATION_PRIVILEGE (27L)
384 | #define SE_MANAGE_VOLUME_PRIVILEGE (28L)
385 | #define SE_IMPERSONATE_PRIVILEGE (29L)
386 | #define SE_CREATE_GLOBAL_PRIVILEGE (30L)
387 | #define SE_TRUSTED_CREDMAN_ACCESS_PRIVILEGE (31L)
388 | #define SE_RELABEL_PRIVILEGE (32L)
389 | #define SE_INC_WORKING_SET_PRIVILEGE (33L)
390 | #define SE_TIME_ZONE_PRIVILEGE (34L)
391 | #define SE_CREATE_SYMBOLIC_LINK_PRIVILEGE (35L)
392 |
393 | //
394 | // Structure representing the mapping for lowbox numbers in the Windows kernel.
395 | //
396 | typedef struct _SEP_LOWBOX_NUMBER_MAPPING {
397 | EX_PUSH_LOCK Lock; // +0x000: Synchronization primitive for accessing the structure.
398 | RTL_BITMAP Bitmap; // +0x008: Bitmap used to track allocated or available lowbox numbers.
399 | PRTL_DYNAMIC_HASH_TABLE HashTable; // +0x018: Pointer to a dynamic hash table storing lowbox-related data.
400 | UCHAR Active; // +0x020: Indicates whether the mapping is active (non-zero) or inactive (zero).
401 | } SEP_LOWBOX_NUMBER_MAPPING, * PSEP_LOWBOX_NUMBER_MAPPING;
402 |
403 | //
404 | // Structure representing an entry in the lowbox number mapping.
405 | //
406 | typedef struct _SEP_LOWBOX_NUMBER_ENTRY {
407 | RTL_DYNAMIC_HASH_TABLE_ENTRY HashEntry; // +0x000: Hash table entry for storing this structure in a dynamic hash table.
408 | LONG64 ReferenceCount; // +0x018: Reference count for this entry.
409 | PVOID PackageSid; // +0x020: Pointer to the SID (Security Identifier) associated with the lowbox.
410 | ULONG LowboxNumber; // +0x028: The lowbox number assigned to this entry.
411 | PVOID AtomTable; // +0x030: Pointer to an atom table for storing additional metadata.
412 | } SEP_LOWBOX_NUMBER_ENTRY, * PSEP_LOWBOX_NUMBER_ENTRY;
413 |
414 | //
415 | // Structure representing a session lowbox map.
416 | //
417 | typedef struct _SESSION_LOWBOX_MAP {
418 | LIST_ENTRY ListEntry; // +0x000: Doubly-linked list entry for linking this structure in a list.
419 | UINT32 SessionId; // +0x010: The session ID associated with this lowbox map.
420 | UINT32 Padding; // +0x014: Padding to align the next member to an 8-byte boundary.
421 | SEP_LOWBOX_NUMBER_MAPPING LowboxMap; // +0x018: The lowbox number mapping for this session.
422 | } SESSION_LOWBOX_MAP, * PSESSION_LOWBOX_MAP;
423 |
424 |
425 |
426 | typedef enum _SEP_CACHED_HANDLES_ENTRY_TYPE {
427 | SepCachedHandlesEntryLowbox = 0,
428 | SepCachedHandlesEntryBnoIsolation = 1
429 | } SEP_CACHED_HANDLES_ENTRY_TYPE, * PSEP_CACHED_HANDLES_ENTRY_TYPE;
430 |
431 | typedef struct _SEP_CACHED_HANDLES_ENTRY_DESCRIPTOR {
432 | SEP_CACHED_HANDLES_ENTRY_TYPE DescriptorType; // +0x000
433 | union {
434 | PSID PackageSid; // +0x008
435 | UNICODE_STRING IsolationPrefix; // +0x008
436 | }u1;
437 | } SEP_CACHED_HANDLES_ENTRY_DESCRIPTOR, * PSEP_CACHED_HANDLES_ENTRY_DESCRIPTOR;
438 |
439 | typedef struct _SEP_CACHED_HANDLES_ENTRY {
440 | RTL_DYNAMIC_HASH_TABLE_ENTRY HashEntry; // +0x000
441 | LONG64 ReferenceCount; // +0x018
442 | SEP_CACHED_HANDLES_ENTRY_DESCRIPTOR EntryDescriptor; // +0x020
443 | ULONG HandleCount; // +0x038
444 | PVOID** Handles; // +0x040
445 | } SEP_CACHED_HANDLES_ENTRY, * PSEP_CACHED_HANDLES_ENTRY;
446 |
447 | //wrk-v1.2
448 | typedef struct _KNOWN_COMPOUND_ACE {
449 | ACE_HEADER Header;
450 | ACCESS_MASK Mask;
451 | USHORT CompoundAceType;
452 | USHORT Reserved;
453 | ULONG SidStart;
454 | } KNOWN_COMPOUND_ACE, * PKNOWN_COMPOUND_ACE;
455 |
456 | typedef struct _KNOWN_OBJECT_ACE {
457 | ACE_HEADER Header;
458 | ACCESS_MASK Mask;
459 | ULONG Flags;
460 | // GUID ObjectType; // Optionally present
461 | // GUID InheritedObjectType; // Optionally present
462 | ULONG SidStart;
463 | } KNOWN_OBJECT_ACE, * PKNOWN_OBJECT_ACE;
464 |
465 | typedef enum _ACL_INFORMATION_CLASS {
466 | AclRevisionInformation = 1,
467 | AclSizeInformation
468 | } ACL_INFORMATION_CLASS;
469 |
470 | typedef struct _ACL_REVISION_INFORMATION {
471 | ULONG AclRevision;
472 | } ACL_REVISION_INFORMATION;
473 | typedef ACL_REVISION_INFORMATION* PACL_REVISION_INFORMATION;
474 |
475 | typedef struct _ACL_SIZE_INFORMATION {
476 | ULONG AceCount;
477 | ULONG AclBytesInUse;
478 | ULONG AclBytesFree;
479 | } ACL_SIZE_INFORMATION;
480 | typedef ACL_SIZE_INFORMATION* PACL_SIZE_INFORMATION;
481 |
482 | #define MAX_OBJECT_PATH 256
483 |
484 | typedef struct _ALLOWED_CACHED_DIRECTORY {
485 | UNICODE_STRING DirectoryName;
486 | BOOLEAN bCheckName;
487 | }ALLOWED_CACHED_DIRECTORY, *PALLOWED_CACHED_DIRECTORY;
488 |
489 | typedef struct _OBJECT_HEADER_NAME_INFO {
490 | PVOID Directory; //POBJECT_DIRECTORY
491 | UNICODE_STRING Name;
492 | LONG ReferenceCount;
493 | ULONG Reserved;
494 | } OBJECT_HEADER_NAME_INFO, * POBJECT_HEADER_NAME_INFO;
495 |
496 | typedef struct _OBJECT_HEADER {
497 | // +0x000 PointerCount
498 | volatile LONG_PTR PointerCount;
499 |
500 | // +0x008 HandleCount / NextToFree (union)
501 | union {
502 | volatile LONG_PTR HandleCount;
503 | struct _OBJECT_HEADER* NextToFree; // Void pointer
504 | };
505 |
506 | // +0x010 Lock
507 | EX_PUSH_LOCK Lock;
508 |
509 | // +0x018 TypeIndex
510 | UCHAR TypeIndex;
511 |
512 | // +0x019 TraceFlags / DbgRefTrace / DbgTracePermanent (bitfields)
513 | union {
514 | UCHAR TraceFlags;
515 | struct {
516 | UCHAR DbgRefTrace : 1;
517 | UCHAR DbgTracePermanent : 1;
518 | };
519 | };
520 |
521 | // +0x01A InfoMask
522 | UCHAR InfoMask;
523 |
524 | // +0x01B Flags / bitfields
525 | union {
526 | UCHAR Flags;
527 | struct {
528 | UCHAR NewObject : 1;
529 | UCHAR KernelObject : 1;
530 | UCHAR KernelOnlyAccess : 1;
531 | UCHAR ExclusiveObject : 1;
532 | UCHAR PermanentObject : 1;
533 | UCHAR DefaultSecurityQuota : 1;
534 | UCHAR SingleHandleEntry : 1;
535 | UCHAR DeletedInline : 1;
536 | };
537 | };
538 |
539 | // +0x01C Reserved
540 | ULONG Reserved;
541 |
542 | // +0x020 ObjectCreateInfo / QuotaBlockCharged (union)
543 | union {
544 | struct _OBJECT_CREATE_INFORMATION* ObjectCreateInfo;
545 | VOID* QuotaBlockCharged;
546 | };
547 |
548 | // +0x028 SecurityDescriptor
549 | VOID* SecurityDescriptor;
550 |
551 | // +0x030 Body
552 | QUAD Body;
553 |
554 | } OBJECT_HEADER, * POBJECT_HEADER;
555 |
556 | typedef struct _KNOWN_ACE {
557 | ACE_HEADER Header;
558 | ACCESS_MASK Mask;
559 | ULONG SidStart;
560 | } KNOWN_ACE, * PKNOWN_ACE;
561 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/driver/LowboxToken.c:
--------------------------------------------------------------------------------
1 | //MJ0011@CyberKunlun 2024.12
2 |
3 | #include
4 | #include
5 | #include
6 |
7 | #include "LowboxToken.h"
8 | #pragma comment(lib, "ntoskrnl.lib")
9 |
10 | SYSTEM_SYMBOLS_PARAMS KernelSymbols;
11 | BOOLEAN bSystemSymbolInitialized = FALSE;
12 |
13 | PSID SeAppSiloSid = NULL;
14 | PSID SeAliasAdminsSid = NULL;
15 | PSID SePrincipalSelfSid = NULL;
16 | PSID SeOwnerRightsSid = NULL;
17 | PSID SeLearningModeLoggingCapabilitySid = NULL;
18 | PSID SePermissiveLearningModeCapabilitySid = NULL;
19 |
20 | PSID SeLpacAppExperienceCapabilitySid = NULL;
21 | PSID SeLpacComCapabilitySid = NULL;
22 | PSID SeLpacCryptoServicesCapabilitySid = NULL;
23 | PSID SeLpacIdentityServicesCapabilitySid = NULL;
24 | PSID SeLpacInstrumentationCapabilitySid = NULL;
25 | PSID SeLpacEnterprisePolicyChangeNotificationsCapabilitySid = NULL;
26 | PSID SeLpacMediaCapabilitySid = NULL;
27 | PSID SeLpacPnpNotificationsCapabilitySid = NULL;
28 | PSID SeRegistryReadCapabilitySid = NULL;
29 | PSID SeLpacServicesManagementCapabilitySid = NULL;
30 | PSID SeLpacSessionManagementCapabilitySid = NULL;
31 | PSID SeLpacPrintingCapabilitySid = NULL;
32 | PSID SeLpacWebPlatformCapabilitySid = NULL;
33 | PSID SeLpacPaymentsCapabilitySid = NULL;
34 | PSID SeLpacClipboardCapabilitySid = NULL;
35 | PSID SeLpacImeCapabilitySid = NULL;
36 | PSID SeLpacPackageManagerOperationCapabilitySid = NULL;
37 | PSID SeLpacDeviceAccessCapabilitySid = NULL;
38 |
39 | const PSID* SeLpacCapabilitySids[] = {
40 | &SeLpacAppExperienceCapabilitySid,
41 | &SeLpacComCapabilitySid,
42 | &SeLpacCryptoServicesCapabilitySid,
43 | &SeLpacIdentityServicesCapabilitySid,
44 | &SeLpacInstrumentationCapabilitySid,
45 | &SeLpacEnterprisePolicyChangeNotificationsCapabilitySid,
46 | &SeLpacMediaCapabilitySid,
47 | &SeLpacPnpNotificationsCapabilitySid,
48 | &SeRegistryReadCapabilitySid,
49 | &SeLpacServicesManagementCapabilitySid,
50 | &SeLpacSessionManagementCapabilitySid,
51 | &SeLpacPrintingCapabilitySid,
52 | &SeLpacWebPlatformCapabilitySid,
53 | &SeLpacPaymentsCapabilitySid,
54 | &SeLpacClipboardCapabilitySid,
55 | &SeLpacImeCapabilitySid,
56 | &SeLpacPackageManagerOperationCapabilitySid,
57 | &SeLpacDeviceAccessCapabilitySid
58 | };
59 |
60 | #define SE_LPAC_CAPABILITY_COUNT (sizeof(SeLpacCapabilitySids) / sizeof(PSID*))
61 |
62 | NTSTATUS NTSYSAPI RtlSidHashInitialize(
63 | PSID_AND_ATTRIBUTES SidAttr,
64 | ULONG SidCount,
65 | PSID_AND_ATTRIBUTES_HASH SidAttrHash
66 | );
67 | NTSTATUS NTSYSAPI RtlQueryInformationAcl(
68 | IN PACL Acl,
69 | OUT PVOID AclInformation,
70 | IN ULONG AclInformationLength,
71 | IN ACL_INFORMATION_CLASS AclInformationClass
72 | );
73 | ULONG NTSYSAPI RtlGetCurrentServiceSessionId();
74 |
75 | POBJECT_TYPE NTSYSAPI ObGetObjectType(PVOID Object);
76 |
77 | POBJECT_HEADER_NAME_INFO NTSYSAPI ObQueryNameInfo(PVOID Object);
78 |
79 | PSID_AND_ATTRIBUTES
80 | NTSYSAPI
81 | RtlSidHashLookup(
82 | _In_ PSID_AND_ATTRIBUTES_HASH SidAttrHash,
83 | _In_ PSID Sid);
84 |
85 |
86 | POBJECT_TYPE ObpSymbolicLinkObjectType;
87 | POBJECT_TYPE ObpDirectoryObjectType;
88 |
89 |
90 | NTSTATUS SeCaptureSid(
91 | __in PSID InputSid,
92 | __in KPROCESSOR_MODE RequestorMode,
93 | __inout_bcount_opt(CaptureBufferLength) PVOID CaptureBuffer,
94 | __in ULONG CaptureBufferLength,
95 | __in POOL_TYPE PoolType,
96 | __in BOOLEAN ForceCapture,
97 | __deref_out PSID* CapturedSid
98 | )
99 |
100 | {
101 |
102 | ULONG GetSidSubAuthorityCount;
103 | ULONG SidSize;
104 |
105 | UNREFERENCED_PARAMETER(CaptureBuffer);
106 | UNREFERENCED_PARAMETER(CaptureBufferLength);
107 | UNREFERENCED_PARAMETER(PoolType);
108 |
109 | if ((RequestorMode == KernelMode) && (ForceCapture == FALSE))
110 | {
111 | (*CapturedSid) = InputSid;
112 |
113 | return STATUS_SUCCESS;
114 | }
115 |
116 | if (RequestorMode != KernelMode)
117 | {
118 |
119 | try
120 | {
121 | GetSidSubAuthorityCount = ProbeAndReadUchar(&(((SID*)(InputSid))->SubAuthorityCount));
122 |
123 | SidSize = RtlLengthRequiredSid(GetSidSubAuthorityCount);
124 |
125 | ProbeForRead(InputSid, SidSize, sizeof(ULONG));
126 |
127 | }
128 | except(EXCEPTION_EXECUTE_HANDLER)
129 | {
130 | return GetExceptionCode();
131 | }
132 |
133 | }
134 | else
135 | {
136 |
137 | GetSidSubAuthorityCount = ((SID*)(InputSid))->SubAuthorityCount;
138 | SidSize = RtlLengthRequiredSid(GetSidSubAuthorityCount);
139 | }
140 |
141 | *CapturedSid = (PSID)ExAllocatePoolWithTag((POOL_TYPE)(PagedPool | POOL_ZERO_ALLOCATION) , SidSize, SEP_SID_TAG);
142 |
143 | if (*CapturedSid == NULL)
144 | {
145 | return STATUS_INSUFFICIENT_RESOURCES;
146 | }
147 |
148 | try
149 | {
150 | RtlCopyMemory((*CapturedSid), InputSid, SidSize);
151 | ((SID*)(*CapturedSid))->SubAuthorityCount = (UCHAR)GetSidSubAuthorityCount;
152 |
153 | }
154 | except(EXCEPTION_EXECUTE_HANDLER)
155 | {
156 | ExFreePool(*CapturedSid);
157 | *CapturedSid = NULL;
158 |
159 | return GetExceptionCode();
160 | }
161 |
162 | if ((!RtlValidSid((*CapturedSid))))
163 | {
164 | ExFreePool((*CapturedSid));
165 | *CapturedSid = NULL;
166 |
167 | return STATUS_INVALID_SID;
168 | }
169 |
170 | return STATUS_SUCCESS;
171 |
172 | }
173 |
174 | SID_IDENTIFIER_AUTHORITY RtlpAppPackageAuthority = { 0 , 0 , 0 , 0 , 0 , 0xF };
175 |
176 | //Determines the type of AppContainer SID.
177 |
178 | /*Parameters
179 | AppContainerSid - the SID to classify.
180 | AppContainerSidType - a pointer to a variable that receives the appcontainer SID type.
181 | */
182 |
183 | NTSTATUS NTAPI RtlGetAppContainerSidType(
184 | _In_ PISID AppContainerSid,
185 | _Out_ PAPPCONTAINER_SID_TYPE AppContainerSidType
186 | )
187 | {
188 | UCHAR SubAuthorityCount;
189 |
190 | if (AppContainerSid->SubAuthorityCount >= SECURITY_BUILTIN_APP_PACKAGE_RID_COUNT &&
191 | AppContainerSid->Revision == SID_REVISION &&
192 | RtlCompareMemory(&AppContainerSid->IdentifierAuthority, &RtlpAppPackageAuthority, sizeof(SID_IDENTIFIER_AUTHORITY)) == sizeof(SID_IDENTIFIER_AUTHORITY) &&
193 | AppContainerSid->SubAuthority[0] == SECURITY_APP_PACKAGE_BASE_RID)
194 | {
195 | SubAuthorityCount = *RtlSubAuthorityCountSid(AppContainerSid);
196 | if (SubAuthorityCount == SECURITY_APP_PACKAGE_RID_COUNT)
197 | {
198 | *AppContainerSidType = ParentAppContainerSidType;
199 | return STATUS_SUCCESS;
200 | }
201 | if (SubAuthorityCount == SECURITY_CHILD_PACKAGE_RID_COUNT)
202 | {
203 | *AppContainerSidType = ChildAppContainerSidType;
204 | return STATUS_SUCCESS;
205 | }
206 | *AppContainerSidType = InvalidAppContainerSidType;
207 | }
208 | else
209 | {
210 | *AppContainerSidType = NotAppContainerSidType;
211 | }
212 | return STATUS_NOT_APPCONTAINER;
213 | }
214 |
215 | //Determines if two SIDs represent a pair of related child and parent AppContainer SIDs.
216 |
217 | // Parameters
218 | // ParentAppContainerSid - a parent AppContainer SID.
219 | // ChildAppContainerSid - a child AppContainer SID.
220 |
221 | BOOLEAN NTAPI RtlIsParentOfChildAppContainer(
222 | _In_ PSID ParentAppContainerSid,
223 | _In_ PSID ChildAppContainerSid
224 |
225 | )
226 | {
227 | ULONG i;
228 | APPCONTAINER_SID_TYPE SidType = 0 ;
229 |
230 | if (NT_SUCCESS(RtlGetAppContainerSidType(ParentAppContainerSid, &SidType)) &&
231 | SidType == ParentAppContainerSidType &&
232 | NT_SUCCESS(RtlGetAppContainerSidType(ChildAppContainerSid, &SidType)) &&
233 | SidType == ChildAppContainerSidType)
234 | {
235 | i = 1;
236 |
237 | for (i = 1; i < SECURITY_APP_PACKAGE_RID_COUNT; i++)
238 | {
239 | if (*RtlSubAuthoritySid(ParentAppContainerSid, i) != *RtlSubAuthoritySid(ChildAppContainerSid, i))
240 | {
241 | return FALSE;
242 | }
243 | }
244 |
245 | return TRUE;
246 | }
247 | return FALSE;
248 | }
249 |
250 | /*
251 | * Check if current process has permission to create a Low Box token
252 | * Returns STATUS_SUCCESS if authorized, STATUS_ACCESS_DENIED otherwise
253 | */
254 |
255 | NTSTATUS SepCheckCreateLowBox(PSID CapturedSid)
256 | {
257 | PTOKEN ClientToken;
258 | SECURITY_SUBJECT_CONTEXT SubjectContext = { 0 };
259 |
260 | // Capture security context
261 | SeCaptureSubjectContext(&SubjectContext);
262 |
263 | // Determine which token to use and verify impersonation level
264 | if (SubjectContext.ClientToken)
265 | {
266 | ClientToken = (PTOKEN)SubjectContext.ClientToken;
267 | if (SubjectContext.ImpersonationLevel < SecurityImpersonation)
268 | {
269 | SeReleaseSubjectContext(&SubjectContext);
270 | return STATUS_ACCESS_DENIED;
271 | }
272 | }
273 | else
274 | {
275 | ClientToken = (PTOKEN)SubjectContext.PrimaryToken;
276 | }
277 |
278 | // Check if token has elevated privileges
279 | if (ClientToken->TokenFlags & TOKEN_NOT_LOW)
280 | {
281 | SeReleaseSubjectContext(&SubjectContext);
282 | return STATUS_SUCCESS;
283 | }
284 | // Perform deep container validation if needed
285 | else if ((ClientToken->TokenFlags & TOKEN_LOWBOX) &&
286 | RtlIsParentOfChildAppContainer(
287 | (PISID)ClientToken->Package,
288 | CapturedSid
289 | ))
290 | {
291 | SeReleaseSubjectContext(&SubjectContext);
292 | return STATUS_SUCCESS;
293 | }
294 | else
295 | {
296 | SeReleaseSubjectContext(&SubjectContext);
297 | return STATUS_ACCESS_DENIED;
298 | }
299 | }
300 |
301 |
302 | NTSTATUS __declspec(noalias) SeCaptureSidAndAttributesArray(
303 | __in_ecount(ArrayCount) PSID_AND_ATTRIBUTES InputArray,
304 | __in ULONG ArrayCount,
305 | __in KPROCESSOR_MODE RequestorMode,
306 | __in_bcount_opt(CaptureBufferLength) PVOID CaptureBuffer,
307 | __in ULONG CaptureBufferLength,
308 | __in POOL_TYPE PoolType, //unused
309 | __in BOOLEAN ForceCapture,//unused
310 | __deref_out_bcount_full(*AlignedArraySize) PSID_AND_ATTRIBUTES* CapturedArray,
311 | __out PULONG AlignedArraySize
312 | )
313 | {
314 |
315 | typedef struct _TEMP_ARRAY_ELEMENT {
316 | PISID Sid;
317 | ULONG SidLength;
318 | } TEMP_ARRAY_ELEMENT;
319 |
320 |
321 |
322 |
323 | TEMP_ARRAY_ELEMENT* TempArray = NULL;
324 |
325 | NTSTATUS CompletionStatus = STATUS_SUCCESS;
326 |
327 | ULONG ArraySize;
328 | ULONG AlignedLengthRequired;
329 |
330 | ULONG NextIndex;
331 |
332 | PSID_AND_ATTRIBUTES NextElement;
333 | PVOID NextBufferLocation;
334 |
335 | ULONG GetSidSubAuthorityCount;
336 | ULONG SidSize;
337 | ULONG AlignedSidSize;
338 |
339 | UNREFERENCED_PARAMETER(ForceCapture);
340 | UNREFERENCED_PARAMETER(PoolType);
341 |
342 | if (ArrayCount == 0)
343 | {
344 | *CapturedArray = NULL;
345 | *AlignedArraySize = 0;
346 | return STATUS_SUCCESS;
347 | }
348 |
349 | if (ArrayCount > SEP_MAX_GROUP_COUNT)
350 | {
351 | return STATUS_INVALID_PARAMETER;
352 | }
353 |
354 |
355 | ArraySize = ArrayCount * (ULONG)sizeof(TEMP_ARRAY_ELEMENT);
356 | AlignedLengthRequired = (ULONG)LongAlignSize(ArraySize);
357 |
358 | if (RequestorMode != KernelMode)
359 | {
360 |
361 | TempArray = (TEMP_ARRAY_ELEMENT*)ExAllocatePoolWithTag((POOL_TYPE)(POOL_ZERO_ALLOCATION | PagedPool), AlignedLengthRequired, 'aTeS');
362 |
363 | if (TempArray == NULL)
364 | {
365 | return STATUS_INSUFFICIENT_RESOURCES;
366 | }
367 |
368 |
369 | try
370 | {
371 |
372 | ProbeForRead(InputArray, ArraySize, sizeof(ULONG));
373 |
374 | NextIndex = 0;
375 |
376 | while (NextIndex < ArrayCount)
377 | {
378 | PSID TempSid;
379 |
380 | TempSid = InputArray[NextIndex].Sid;
381 | GetSidSubAuthorityCount = ProbeAndReadUchar(&((PISID)TempSid)->SubAuthorityCount);
382 |
383 | if (GetSidSubAuthorityCount > SID_MAX_SUB_AUTHORITIES)
384 | {
385 | CompletionStatus = STATUS_INVALID_SID;
386 | break;
387 | }
388 |
389 | TempArray[NextIndex].Sid = ((PISID)(TempSid));
390 | TempArray[NextIndex].SidLength = RtlLengthRequiredSid(GetSidSubAuthorityCount);
391 |
392 | ProbeForRead(TempArray[NextIndex].Sid, TempArray[NextIndex].SidLength, sizeof(ULONG));
393 |
394 | AlignedLengthRequired += (ULONG)LongAlignSize(TempArray[NextIndex].SidLength);
395 |
396 | NextIndex += 1;
397 |
398 | }
399 |
400 | } except(EXCEPTION_EXECUTE_HANDLER) {
401 |
402 | ExFreePool(TempArray);
403 | return GetExceptionCode();
404 | }
405 |
406 | if (!NT_SUCCESS(CompletionStatus))
407 | {
408 | ExFreePool(TempArray);
409 | return CompletionStatus;
410 | }
411 |
412 | }
413 | else
414 | {
415 | NextIndex = 0;
416 |
417 | while (NextIndex < ArrayCount) {
418 |
419 | GetSidSubAuthorityCount = ((PISID)(InputArray[NextIndex].Sid))->SubAuthorityCount;
420 |
421 | AlignedLengthRequired += (ULONG)LongAlignSize(RtlLengthRequiredSid(GetSidSubAuthorityCount));
422 |
423 | NextIndex += 1;
424 |
425 | }
426 |
427 | }
428 |
429 | *AlignedArraySize = AlignedLengthRequired;
430 |
431 | if (ARGUMENT_PRESENT(CaptureBuffer)) {
432 |
433 | if (AlignedLengthRequired > CaptureBufferLength) {
434 |
435 | if (RequestorMode != KernelMode)
436 | {
437 | ExFreePool(TempArray);
438 | }
439 |
440 | return STATUS_BUFFER_TOO_SMALL;
441 |
442 | }
443 | else {
444 |
445 | *CapturedArray = CaptureBuffer;
446 | }
447 |
448 | }
449 | else
450 | {
451 | *CapturedArray = (PSID_AND_ATTRIBUTES)ExAllocatePoolWithTag((POOL_TYPE)(POOL_ZERO_ALLOCATION | PagedPool), AlignedLengthRequired, SEP_SID_AND_ATTRIBUTES_TAG);
452 |
453 | if (*CapturedArray == NULL)
454 | {
455 | if (RequestorMode != KernelMode)
456 | {
457 | ExFreePool(TempArray);
458 | }
459 | return STATUS_INSUFFICIENT_RESOURCES;
460 | }
461 | }
462 |
463 | if (RequestorMode != KernelMode)
464 | {
465 | try
466 | {
467 | NextBufferLocation = (*CapturedArray);
468 | RtlCopyMemory(NextBufferLocation, InputArray, ArraySize);
469 | NextBufferLocation = (PVOID)((ULONG_PTR)NextBufferLocation + (ULONG)LongAlignSize(ArraySize));
470 |
471 | NextIndex = 0;
472 | NextElement = (*CapturedArray);
473 | while ((NextIndex < ArrayCount) && (CompletionStatus == STATUS_SUCCESS))
474 | {
475 | RtlCopyMemory(NextBufferLocation, TempArray[NextIndex].Sid, TempArray[NextIndex].SidLength);
476 |
477 |
478 | NextElement[NextIndex].Sid = (PSID)NextBufferLocation;
479 |
480 | NextBufferLocation = (PVOID)((ULONG_PTR)NextBufferLocation + (ULONG)LongAlignSize(TempArray[NextIndex].SidLength));
481 |
482 | if (NextElement[NextIndex].Attributes & ~(SE_GROUP_VALID_ATTRIBUTES)) {
483 | CompletionStatus = STATUS_INVALID_PARAMETER;
484 | }
485 | else if (!RtlValidSid(NextElement[NextIndex].Sid)) {
486 | CompletionStatus = STATUS_INVALID_SID;
487 | }
488 | else if (RtlLengthSid(NextElement[NextIndex].Sid) != TempArray[NextIndex].SidLength) {
489 | CompletionStatus = STATUS_INVALID_SID;
490 | }
491 |
492 | NextIndex += 1;
493 |
494 | }
495 |
496 |
497 | }
498 | except(EXCEPTION_EXECUTE_HANDLER)
499 | {
500 | if (!ARGUMENT_PRESENT(CaptureBuffer)) {
501 | ExFreePool((*CapturedArray));
502 | *CapturedArray = NULL;
503 | }
504 |
505 | ExFreePool(TempArray);
506 |
507 | return GetExceptionCode();
508 | }
509 | }
510 | else
511 | {
512 |
513 | NextBufferLocation = (*CapturedArray);
514 |
515 | RtlCopyMemory(NextBufferLocation, InputArray, ArraySize);
516 |
517 | NextBufferLocation = (PVOID)((ULONG_PTR)NextBufferLocation + (ULONG)LongAlignSize(ArraySize));
518 |
519 | NextIndex = 0;
520 | NextElement = (*CapturedArray);
521 | while (NextIndex < ArrayCount)
522 | {
523 | GetSidSubAuthorityCount = ((PISID)(NextElement[NextIndex].Sid))->SubAuthorityCount;
524 |
525 | SidSize = RtlLengthRequiredSid(GetSidSubAuthorityCount);
526 |
527 | RtlCopyMemory(NextBufferLocation, NextElement[NextIndex].Sid, SidSize);
528 |
529 | AlignedSidSize = (ULONG)LongAlignSize(SidSize);
530 |
531 | NextElement[NextIndex].Sid = (PSID)NextBufferLocation;
532 |
533 | NextIndex += 1;
534 |
535 | NextBufferLocation = (PVOID)((ULONG_PTR)NextBufferLocation + AlignedSidSize);
536 |
537 | }
538 |
539 | }
540 |
541 | if (RequestorMode != KernelMode)
542 | {
543 | ExFreePool(TempArray);
544 | }
545 |
546 | if (!ARGUMENT_PRESENT(CaptureBuffer) && !NT_SUCCESS(CompletionStatus))
547 | {
548 |
549 | ExFreePool(*CapturedArray);
550 |
551 | *CapturedArray = NULL;
552 | }
553 |
554 | return CompletionStatus;
555 | }
556 |
557 | VOID SeReleaseLuidAndAttributesArray(PSID_AND_ATTRIBUTES Array, KPROCESSOR_MODE Mode , BOOLEAN bForceCapture)
558 | {
559 | if (((Mode == KernelMode) && (bForceCapture == TRUE)) ||
560 | (Mode == UserMode))
561 | {
562 | if (Array != NULL)
563 | {
564 | ExFreePool(Array);
565 | }
566 | }
567 | }
568 |
569 | VOID SeReleaseSid(__in PSID CapturedSid, __in KPROCESSOR_MODE RequestorMode, __in BOOLEAN ForceCapture)
570 | {
571 |
572 | if (((RequestorMode == KernelMode) && (ForceCapture == TRUE)) || (RequestorMode == UserMode)) {
573 |
574 | ExFreePool(CapturedSid);
575 | }
576 |
577 | return;
578 |
579 | }
580 |
581 | NTSTATUS SepCaptureHandles(ULONG HandleCount, HANDLE* InputHandles, PHANDLE* CapturedHandles)
582 | {
583 | HANDLE* AllocatedHandles;
584 | ULONG i;
585 |
586 |
587 | *CapturedHandles = NULL;
588 |
589 | if (HandleCount > 10)
590 | return STATUS_INVALID_PARAMETER_1;
591 |
592 | if (HandleCount == 0)
593 | return STATUS_SUCCESS;
594 |
595 | AllocatedHandles = ExAllocatePool2(POOL_FLAG_PAGED, sizeof(HANDLE) * HandleCount, SEP_HANDLES_CAPTURE_TAG);
596 |
597 | if (AllocatedHandles == NULL)
598 | {
599 | return STATUS_INSUFFICIENT_RESOURCES;
600 | }
601 |
602 | __try
603 | {
604 | for (i = 0; i < HandleCount; i++)
605 | {
606 | AllocatedHandles[i] = InputHandles[i];
607 | }
608 | }
609 | __except (EXCEPTION_EXECUTE_HANDLER)
610 | {
611 | NTSTATUS Status;
612 | Status = GetExceptionCode();
613 |
614 | if (!NT_SUCCESS(Status))
615 | {
616 | ExFreePool(AllocatedHandles);
617 | }
618 |
619 | return Status;
620 | }
621 | *CapturedHandles = AllocatedHandles;
622 | return STATUS_SUCCESS;
623 | }
624 |
625 | BOOLEAN RtlIsPackageSid(PISID Sid)
626 | {
627 | return (Sid->SubAuthorityCount >= SECURITY_BUILTIN_APP_PACKAGE_RID_COUNT &&
628 | Sid->Revision == SID_REVISION &&
629 | RtlCompareMemory(&Sid->IdentifierAuthority, &RtlpAppPackageAuthority, sizeof(SID_IDENTIFIER_AUTHORITY)) == sizeof(SID_IDENTIFIER_AUTHORITY) &&
630 | Sid->SubAuthority[0] == SECURITY_APP_PACKAGE_BASE_RID);
631 | }
632 |
633 | BOOLEAN RtlIsCapabilitySid(PISID Sid)
634 | {
635 | return (Sid->SubAuthorityCount >= SECURITY_BUILTIN_CAPABILITY_RID_COUNT &&
636 | Sid->Revision == SID_REVISION &&
637 | RtlCompareMemory(&Sid->IdentifierAuthority, &RtlpAppPackageAuthority, sizeof(SID_IDENTIFIER_AUTHORITY)) == sizeof(SID_IDENTIFIER_AUTHORITY) &&
638 | Sid->SubAuthority[0] == SECURITY_CAPABILITY_BASE_RID);
639 | }
640 |
641 |
642 | BOOLEAN SepIsLpacCapabilitySid(PSID Sid)
643 | {
644 | ULONG Index;
645 |
646 | for (Index = 0; Index < SE_LPAC_CAPABILITY_COUNT; Index++)
647 | {
648 | if (RtlEqualSid(Sid, *SeLpacCapabilitySids[Index]))
649 | {
650 | return TRUE;
651 | }
652 | }
653 |
654 | return FALSE;
655 | }
656 |
657 |
658 | NTSTATUS SepCheckCapabilities(PACCESS_TOKEN Token, ULONG CapabilityCount, SID_AND_ATTRIBUTES* CapabilityArray, PVOID Unused, BOOLEAN* pbCapLegit)
659 | {
660 | NTSTATUS Status;
661 | ULONG TokenIsLPAC = 0;
662 | TOKEN_GROUPS* TokenGroups = NULL;
663 | ULONG IsAppContainer = 0;
664 | ULONG Index = 0;
665 | ULONG GroupsIndex = 0;
666 | PTOKEN_APPCONTAINER_INFORMATION pTokenAppcontainerSid = NULL;
667 |
668 | UNREFERENCED_PARAMETER(Unused);
669 |
670 |
671 | *pbCapLegit = FALSE;
672 |
673 | // Non-AppContainer tokens are always considered legitimate
674 |
675 | Status = SeQueryInformationToken(Token, TokenIsAppContainer, (PVOID) & IsAppContainer);
676 |
677 | if (!NT_SUCCESS(Status))
678 | {
679 | goto Exit;
680 | }
681 |
682 | if (IsAppContainer == 0)
683 | {
684 | *pbCapLegit = TRUE;
685 | goto Exit;
686 | }
687 |
688 | Status = SeQueryInformationToken(Token, TokenCapabilities, (PVOID)&TokenGroups);
689 |
690 | if (!NT_SUCCESS(Status))
691 | {
692 | goto Exit;
693 | }
694 |
695 | Status = SeQueryInformationToken(Token, TokenIsLessPrivilegedAppContainer, (PVOID)&TokenIsLPAC);
696 |
697 | if (!NT_SUCCESS(Status))
698 | {
699 | goto Exit;
700 | }
701 |
702 | for (Index = 0; Index < CapabilityCount; Index++)
703 | {
704 | //If exisiting token is not LPAC and capability sid is lpac capability sid
705 |
706 | if (TokenIsLPAC == FALSE && SepIsLpacCapabilitySid(CapabilityArray[Index].Sid))
707 | {
708 | continue;
709 | }
710 |
711 | //Already exist capability of existing token
712 |
713 | for (GroupsIndex = 0; GroupsIndex < TokenGroups->GroupCount; GroupsIndex++)
714 | {
715 | if (RtlEqualSid(TokenGroups->Groups[GroupsIndex].Sid, CapabilityArray[Index].Sid) &&
716 | TokenGroups->Groups[GroupsIndex].Attributes == CapabilityArray[Index].Attributes)
717 | {
718 | break;
719 | }
720 | }
721 |
722 | if (GroupsIndex != TokenGroups->GroupCount)
723 | {
724 | continue;
725 | }
726 |
727 | //not existing capability, check installer group
728 |
729 | if (((PISID)CapabilityArray[Index].Sid)->SubAuthorityCount != SECURITY_INSTALLER_GROUP_CAPABILITY_RID_COUNT ||
730 | *(RtlSubAuthoritySid(CapabilityArray[Index].Sid, 0)) != SECURITY_CAPABILITY_BASE_RID)
731 | {
732 | *pbCapLegit = FALSE;
733 | break;
734 | }
735 |
736 | if (pTokenAppcontainerSid == NULL)
737 | {
738 | Status = SeQueryInformationToken(Token, TokenAppContainerSid, &pTokenAppcontainerSid);
739 |
740 | if (!NT_SUCCESS(Status))
741 | {
742 | break;
743 | }
744 | }
745 |
746 | if (*RtlSubAuthorityCountSid(pTokenAppcontainerSid->TokenAppContainer) >= SECURITY_APP_PACKAGE_RID_COUNT &&
747 | RtlCompareMemory(RtlSubAuthoritySid(pTokenAppcontainerSid->TokenAppContainer, 1),
748 | RtlSubAuthoritySid(CapabilityArray[Index].Sid, 1),
749 | (SECURITY_APP_PACKAGE_RID_COUNT - 1) * sizeof(ULONG)) == (SECURITY_APP_PACKAGE_RID_COUNT - 1) * sizeof(ULONG))
750 | {
751 | continue;
752 | }
753 | else
754 | {
755 | *pbCapLegit = FALSE;
756 | break;
757 | }
758 | }
759 |
760 | if (CapabilityCount == Index)
761 | {
762 | *pbCapLegit = TRUE;
763 | }
764 |
765 | Exit:
766 | if (TokenGroups)
767 | ExFreePool(TokenGroups);
768 | if (pTokenAppcontainerSid)
769 | ExFreePool(pTokenAppcontainerSid);
770 | return Status;
771 | }
772 |
773 | NTSTATUS
774 | SepDuplicateToken(
775 | __in PTOKEN ExistingToken,
776 | __in POBJECT_ATTRIBUTES ObjectAttributes,
777 | __in BOOLEAN EffectiveOnly,
778 | __in TOKEN_TYPE TokenType,
779 | __in SECURITY_IMPERSONATION_LEVEL ImpersonationLevel,
780 | __in KPROCESSOR_MODE RequestorMode,
781 | __in BOOLEAN SkipNonInheritableSecurityAttributes,
782 | __deref_out PTOKEN* DuplicateToken
783 | )
784 | {
785 | return KernelSymbols.SepDuplicateToken(ExistingToken, ObjectAttributes, EffectiveOnly, TokenType, ImpersonationLevel, RequestorMode, SkipNonInheritableSecurityAttributes, DuplicateToken);
786 | }
787 |
788 | NTSTATUS SeSetMandatoryPolicyToken(PTOKEN Token, PTOKEN_MANDATORY_POLICY MandatoryPolicy)
789 | {
790 | if (MandatoryPolicy->Policy & (~TOKEN_MANDATORY_POLICY_VALID_MASK))
791 | {
792 | return STATUS_INVALID_PARAMETER;
793 | }
794 |
795 | SepAcquireTokenWriteLock(Token);
796 |
797 | Token->MandatoryPolicy = MandatoryPolicy->Policy;
798 |
799 | SepReleaseTokenWriteLock(Token, TRUE);
800 | return STATUS_SUCCESS;
801 | }
802 |
803 | PSID_AND_ATTRIBUTES SepLocateTokenIntegrity(PTOKEN Token)
804 | {
805 | if (Token->IntegrityLevelIndex == -1)
806 | {
807 | return NULL;
808 | }
809 |
810 | return &Token->UserAndGroups[Token->IntegrityLevelIndex];
811 | }
812 | //BOOLEAN SepTokenCapabilitySidSharingEnabled;
813 |
814 |
815 | NTSTATUS SepLengthSidAndAttributesArray(PSID_AND_ATTRIBUTES Caps, ULONG CapCount, PULONG pCapturedSize)
816 | {
817 | PVOID CaptureBuffer;
818 | NTSTATUS Status;
819 | PSID_AND_ATTRIBUTES CapturedCaps;
820 | ULONG CapturedSize;
821 |
822 |
823 | CapturedSize = 0;
824 | CapturedCaps = NULL;
825 |
826 | CaptureBuffer = ExAllocatePool2(POOL_FLAG_PAGED, 8, 'aSeS');
827 |
828 | if (CaptureBuffer == NULL)
829 | {
830 | return STATUS_INSUFFICIENT_RESOURCES;
831 | }
832 |
833 | Status = SeCaptureSidAndAttributesArray(
834 | Caps,
835 | CapCount,
836 | KernelMode,
837 | CaptureBuffer,
838 | 8,
839 | PagedPool,
840 | FALSE,
841 | &CapturedCaps,
842 | &CapturedSize);
843 |
844 | *pCapturedSize = CapturedSize;
845 | if (Status == STATUS_BUFFER_TOO_SMALL)
846 | {
847 | Status = STATUS_SUCCESS;
848 | }
849 |
850 | ExFreePool(CaptureBuffer);
851 | return Status;
852 | }
853 | typedef struct SID_MAPPING
854 | {
855 | EX_PUSH_LOCK Lock;
856 | PRTL_DYNAMIC_HASH_TABLE HashTable;
857 | }SID_MAPPING, * PSID_MAPPING;
858 |
859 | //PSID_MAPPING g_SepSidMapping;
860 |
861 | typedef struct SHARED_SID_ENTRY {
862 | RTL_DYNAMIC_HASH_TABLE_ENTRY Entry;
863 | LONG64 ReferCount;
864 | PSID Sid;
865 | }SHARED_SID_ENTRY, * PSHARED_SID_ENTRY;
866 |
867 | PSHARED_SID_ENTRY SepFindSharedSidEntry(PISID Sid)
868 | {
869 | ULONG_PTR IDAuthValue;
870 | PRTL_DYNAMIC_HASH_TABLE_ENTRY i;
871 | RTL_DYNAMIC_HASH_TABLE_CONTEXT Context;
872 | PSID_MAPPING g_SepSidMapping = *(PSID_MAPPING*)(KernelSymbols.g_SepSidMapping);
873 |
874 | memset(&Context, 0, sizeof(Context));
875 |
876 | IDAuthValue = SID_HASH_ULONG(Sid);
877 |
878 | if (IDAuthValue == 0)
879 | {
880 | IDAuthValue = 1;
881 | }
882 |
883 | for (i = RtlLookupEntryHashTable(g_SepSidMapping->HashTable, IDAuthValue, &Context);
884 | ;
885 | i = RtlGetNextEntryHashTable(g_SepSidMapping->HashTable, &Context))
886 | {
887 | if (!i)
888 | break;
889 | if (RtlEqualSid(Sid, CONTAINING_RECORD(i, SHARED_SID_ENTRY, Entry)->Sid))
890 | return NULL;
891 | }
892 | return CONTAINING_RECORD(i, SHARED_SID_ENTRY, Entry);
893 | }
894 |
895 | VOID SepDeReferenceSharedSidEntries(PSID_AND_ATTRIBUTES Capabilities, ULONG CapabilityCount)
896 | {
897 | ULONG CapCount;
898 | PSHARED_SID_ENTRY HashEntry;
899 | PSID_MAPPING g_SepSidMapping = *(PSID_MAPPING*)(KernelSymbols.g_SepSidMapping);
900 |
901 | KeEnterCriticalRegion();
902 | ExAcquirePushLockExclusive(&g_SepSidMapping->Lock);
903 |
904 | for (CapCount = 0; CapCount < CapabilityCount; CapCount++)
905 | {
906 | HashEntry = SepFindSharedSidEntry(Capabilities[CapCount].Sid);
907 |
908 | PSHARED_SID_ENTRY SidEntry = CONTAINING_RECORD(HashEntry, SHARED_SID_ENTRY, Entry);
909 | LONG64 NewRef = InterlockedDecrement64(&SidEntry->ReferCount);
910 |
911 | if (NewRef <= 0)
912 | {
913 | if (NewRef)
914 | {
915 | RtlFailFast(FAST_FAIL_INVALID_REFERENCE_COUNT);
916 | //never return
917 | }
918 |
919 | if (RtlRemoveEntryHashTable(g_SepSidMapping->HashTable, &HashEntry->Entry, NULL))
920 | {
921 | ExFreePool(HashEntry);
922 | }
923 | }
924 | }
925 |
926 | ExReleasePushLockExclusive(&g_SepSidMapping->Lock);
927 |
928 | KeLeaveCriticalRegion();
929 |
930 | return;
931 | }
932 |
933 |
934 | VOID SepFreeTokenCapabilities(PTOKEN Token)
935 | {
936 | if (*(BOOLEAN*)(KernelSymbols.SepTokenCapabilitySidSharingEnabled))
937 | {
938 | SepDeReferenceSharedSidEntries(Token->Capabilities, Token->CapabilityCount);
939 | }
940 | ExFreePool(Token->Capabilities);
941 | }
942 |
943 | NTSTATUS SepInsertOrReferenceSharedSidEntries(SID_AND_ATTRIBUTES* Capabilities , SID_AND_ATTRIBUTES* OutputSaA , ULONG CapabilityCount)
944 | {
945 | NTSTATUS Status = STATUS_SUCCESS;
946 | ULONG i;
947 | PSHARED_SID_ENTRY SidEntry;
948 | PISID Sid;
949 | ULONG Signature;
950 | ULONG SidEntrySize;
951 | LONGLONG RefCount;
952 | PSID_MAPPING g_SepSidMapping = *(PSID_MAPPING*)(KernelSymbols.g_SepSidMapping);
953 |
954 | KeEnterCriticalRegion();
955 |
956 | ExAcquirePushLockExclusive(&g_SepSidMapping->Lock);
957 |
958 | for (i = 0; i < CapabilityCount; i++)
959 | {
960 | OutputSaA[i].Attributes = Capabilities[i].Attributes;
961 |
962 | SidEntry = SepFindSharedSidEntry(Capabilities->Sid);
963 |
964 | if (SidEntry)
965 | {
966 | if (InterlockedIncrement64(&SidEntry->ReferCount) <= 1)
967 | {
968 | RtlFailFast(FAST_FAIL_INVALID_REFERENCE_COUNT);
969 | //never return
970 | }
971 |
972 | Sid = SidEntry->Sid;
973 | }
974 | else
975 | {
976 | SidEntrySize = (((PISID)(Capabilities[i].Sid))->SubAuthorityCount * sizeof(ULONG) + FIELD_OFFSET(SID, SubAuthority) + sizeof(SHARED_SID_ENTRY)) * 2; //why mul by 2?
977 |
978 | SidEntry = (PSHARED_SID_ENTRY)ExAllocatePool2(POOL_FLAG_PAGED, SidEntrySize, SEP_SID_SHARING_TAG);
979 |
980 | if (SidEntry == NULL)
981 | {
982 | Status = STATUS_NO_MEMORY;
983 | break;
984 | }
985 |
986 | SidEntry->Sid = (PSID)((ULONG_PTR)SidEntry + sizeof(SHARED_SID_ENTRY));
987 | SidEntry->ReferCount = 1;
988 |
989 | //SidEntrySize was multiplied by 2 but here it's only subtracting a single structure size
990 |
991 | RtlCopySid(SidEntrySize - sizeof(SHARED_SID_ENTRY), (PSID)((ULONG_PTR)SidEntry + sizeof(SHARED_SID_ENTRY)), Capabilities[i].Sid);
992 |
993 | Signature = SID_HASH_ULONG(Capabilities[i].Sid);
994 |
995 | if (Signature == 0)
996 | {
997 | Signature = 1;
998 | }
999 |
1000 | if (RtlInsertEntryHashTable(g_SepSidMapping->HashTable, &SidEntry->Entry, Signature, NULL) == FALSE)
1001 | {
1002 | Status = STATUS_UNSUCCESSFUL;
1003 | ExFreePoolWithTag(SidEntry, SEP_SID_SHARING_TAG);
1004 | break;
1005 | }
1006 | }
1007 |
1008 | //output inserted or referenced sid entry
1009 |
1010 | OutputSaA[i].Sid = SidEntry->Sid;
1011 | }
1012 |
1013 | //capability list not fully processed
1014 | if (i != CapabilityCount)
1015 | {
1016 | for (; i; i--)
1017 | {
1018 | //it must be able to find in the shared sid table
1019 |
1020 | SidEntry = SepFindSharedSidEntry(OutputSaA->Sid);
1021 |
1022 |
1023 | RefCount = InterlockedDecrement64(&SidEntry->ReferCount);
1024 |
1025 | if (RefCount <= 0)
1026 | {
1027 | if (RefCount)
1028 | {
1029 | RtlFailFast(FAST_FAIL_INVALID_REFERENCE_COUNT);
1030 | //never return
1031 | }
1032 |
1033 | //reference count == 0
1034 |
1035 | if (RtlRemoveEntryHashTable(g_SepSidMapping->HashTable, &SidEntry->Entry, NULL))
1036 | {
1037 | ExFreePool(SidEntry);
1038 | }
1039 | }
1040 |
1041 | OutputSaA++;
1042 | }
1043 | }
1044 |
1045 | ExReleasePushLockExclusive(&g_SepSidMapping->Lock);
1046 |
1047 | KeLeaveCriticalRegion();
1048 |
1049 | return Status;
1050 | }
1051 |
1052 | NTSTATUS SepSetTokenCapabilities(
1053 | PTOKEN Token,
1054 | PISID Sid,
1055 | PSID_AND_ATTRIBUTES CapabilityArray,
1056 | ULONG CapabilityCount)
1057 | {
1058 | NTSTATUS Status;
1059 | unsigned int CapLength;
1060 | PVOID CaptureBuffer;
1061 | PSID Package;
1062 | PSID_AND_ATTRIBUTES CapturedCap;
1063 | ULONG CapturedSize;
1064 |
1065 | CapturedSize = 0;
1066 | CapturedCap = NULL;
1067 |
1068 | if (Token->Capabilities)
1069 | {
1070 | if (Sid == NULL)
1071 | {
1072 | return STATUS_ACCESS_DENIED;
1073 | }
1074 |
1075 | Package = Token->Package;
1076 |
1077 | if (Package)
1078 | {
1079 | if (!RtlIsParentOfChildAppContainer(Package, Sid))
1080 | {
1081 | return STATUS_ACCESS_DENIED;
1082 | }
1083 | }
1084 | }
1085 |
1086 | if (CapabilityCount)
1087 | {
1088 | if (CapabilityCount > SEP_MAX_GROUP_COUNT)
1089 | {
1090 | return STATUS_INVALID_PARAMETER;
1091 | }
1092 |
1093 | if (*(BOOLEAN*)(KernelSymbols.SepTokenCapabilitySidSharingEnabled))
1094 | {
1095 | CapLength = sizeof(SID_AND_ATTRIBUTES) * CapabilityCount * 2 ; //why mul by 2?
1096 | }
1097 | else
1098 | {
1099 | Status = SepLengthSidAndAttributesArray(CapabilityArray, CapabilityCount, &CapturedSize);
1100 |
1101 | if (!NT_SUCCESS(Status))
1102 | {
1103 | return Status;
1104 | }
1105 |
1106 | CapLength = CapturedSize;
1107 | }
1108 |
1109 | CaptureBuffer = ExAllocatePool2(POOL_FLAG_PAGED, CapLength, SEP_SID_SHARING_TAG);
1110 |
1111 | if (CaptureBuffer == NULL)
1112 | {
1113 | return STATUS_INSUFFICIENT_RESOURCES;
1114 | }
1115 |
1116 | if (*(BOOLEAN*)(KernelSymbols.SepTokenCapabilitySidSharingEnabled))
1117 | {
1118 | Status = SepInsertOrReferenceSharedSidEntries(CapabilityArray, (SID_AND_ATTRIBUTES*)CaptureBuffer, CapabilityCount);
1119 | }
1120 | else
1121 | {
1122 | Status = SeCaptureSidAndAttributesArray(
1123 | CapabilityArray,
1124 | CapabilityCount,
1125 | KernelMode,
1126 | CaptureBuffer,
1127 | CapLength,
1128 | PagedPool,
1129 | FALSE,
1130 | &CapturedCap,
1131 | &CapturedSize);
1132 | }
1133 |
1134 | if (!NT_SUCCESS(Status))
1135 | {
1136 | ExFreePool(CaptureBuffer);
1137 | }
1138 | else
1139 | {
1140 | if (Token->Capabilities)
1141 | SepFreeTokenCapabilities(Token);
1142 |
1143 | Token->Capabilities = CapturedCap;
1144 | Token->CapabilityCount = CapabilityCount;
1145 | RtlSidHashInitialize((PSID_AND_ATTRIBUTES)CaptureBuffer, CapabilityCount, &Token->CapabilitiesHash);
1146 | }
1147 | return Status;
1148 | }
1149 | else
1150 | {
1151 | if (Token->Capabilities)
1152 | {
1153 | SepFreeTokenCapabilities(Token);
1154 | }
1155 |
1156 | Token->Capabilities = NULL;
1157 | Token->CapabilityCount = 0;
1158 |
1159 | //added 24h2, cleanup hash
1160 | RtlZeroMemory(&Token->CapabilitiesHash, sizeof(SID_AND_ATTRIBUTES_HASH));
1161 | return STATUS_SUCCESS;
1162 | }
1163 |
1164 | }
1165 |
1166 | BOOLEAN SepSidInTokenSidHash(PSID_AND_ATTRIBUTES_HASH SidHash, PSID PrincipalSelfSid, PSID Sid, BOOLEAN DenyAce, BOOLEAN Restricted, BOOLEAN TokenIsOwner)
1167 | {
1168 | PSID CurrentSid = Sid;
1169 | ULONG SidLength;
1170 | UCHAR SidRevsion;
1171 | UCHAR Hash;
1172 | SID_HASH_ENTRY HashLookupEntry;
1173 | ULONG ByteIndex;
1174 | UCHAR ByteLocation;
1175 | ULONG Index;
1176 | PSID_AND_ATTRIBUTES pSAHash;
1177 | ULONG i;
1178 |
1179 | if (PrincipalSelfSid != NULL && RtlEqualSid(SePrincipalSelfSid, Sid))
1180 | {
1181 | CurrentSid = PrincipalSelfSid;
1182 | }
1183 |
1184 | if (TokenIsOwner && RtlEqualSid(SeOwnerRightsSid, CurrentSid))
1185 | {
1186 | return TRUE;
1187 | }
1188 |
1189 | if (SidHash == NULL || CurrentSid == NULL)
1190 | {
1191 | return FALSE;
1192 | }
1193 |
1194 | SidLength = SeLengthSid(CurrentSid);
1195 | SidRevsion = ((PISID)CurrentSid)->Revision;
1196 |
1197 | Hash = AUTHZ_SID_HASH_BYTE(CurrentSid);
1198 | HashLookupEntry = AUTHZ_SID_HASH_LOOKUP(SidHash->Hash, Hash);
1199 |
1200 | ByteIndex = 0;
1201 |
1202 | while (HashLookupEntry)
1203 | {
1204 | ByteLocation = (UCHAR)HashLookupEntry;
1205 |
1206 | while (ByteLocation)
1207 | {
1208 | Index = SidHashByteToIndexLookupTable[ByteLocation];
1209 |
1210 | pSAHash = &SidHash->SidAttr[ByteIndex + Index];
1211 |
1212 | if (((PISID)(pSAHash->Sid))->Revision == SidRevsion &&
1213 | ((PISID)(pSAHash->Sid))->SubAuthorityCount == ((PISID)CurrentSid)->SubAuthorityCount)
1214 | {
1215 | if (memcmp(CurrentSid, pSAHash->Sid, SidLength) == 0)
1216 | {
1217 | goto GetHashSA;
1218 | }
1219 | }
1220 |
1221 | ByteLocation = ByteLocation ^ (1 << Index);
1222 |
1223 | }
1224 |
1225 | ByteIndex += 8;
1226 | HashLookupEntry >>= 8;
1227 | }
1228 |
1229 | if (SidHash->SidCount > AUTHZI_SID_HASH_ENTRY_NUM_BITS)
1230 | {
1231 | for (i = AUTHZI_SID_HASH_ENTRY_NUM_BITS; i < SidHash->SidCount; i++)
1232 | {
1233 | pSAHash = &SidHash->SidAttr[i];
1234 |
1235 | if (((PISID)(pSAHash->Sid))->Revision == SidRevsion &&
1236 | ((PISID)(pSAHash->Sid))->SubAuthorityCount == ((PISID)CurrentSid)->SubAuthorityCount)
1237 | {
1238 | if (memcmp(CurrentSid, pSAHash->Sid, SidLength) == 0)
1239 | {
1240 | goto GetHashSA;
1241 | }
1242 | }
1243 |
1244 | }
1245 | }
1246 |
1247 | return FALSE;
1248 |
1249 | GetHashSA:
1250 |
1251 | if (Restricted == FALSE && pSAHash != SidHash->SidAttr)
1252 | {
1253 | if ((pSAHash->Attributes & SE_GROUP_USE_FOR_DENY_ONLY) == 0)
1254 | {
1255 | return TRUE;
1256 | }
1257 |
1258 | if (DenyAce)
1259 | {
1260 | return TRUE;
1261 | }
1262 | }
1263 |
1264 | if ((pSAHash->Attributes & SE_GROUP_ENABLED) || (DenyAce && (pSAHash->Attributes & SE_GROUP_USE_FOR_DENY_ONLY)))
1265 | {
1266 | return TRUE;
1267 |
1268 | }
1269 | else
1270 | {
1271 | return FALSE;
1272 | }
1273 | }
1274 |
1275 |
1276 | NTSTATUS SepGetTokenSessionMapEntry(ULONG SessionId, BOOLEAN bInsert, PSEP_LOWBOX_NUMBER_MAPPING* pLowboxNumberMapping)
1277 | {
1278 | PSESSION_LOWBOX_MAP MapEntry;
1279 | PLIST_ENTRY entry;
1280 |
1281 | *pLowboxNumberMapping = NULL;
1282 |
1283 | //create list entry of lowbox map if it's not yet initialized
1284 |
1285 | if (*(PLIST_ENTRY*)(KernelSymbols.g_SessionLowboxMap) == NULL)
1286 | {
1287 | if (bInsert == FALSE)
1288 | {
1289 | return STATUS_NOT_FOUND;
1290 | }
1291 |
1292 | *(PLIST_ENTRY*)(KernelSymbols.g_SessionLowboxMap) = (PLIST_ENTRY)ExAllocatePool2(POOL_FLAG_PAGED, sizeof(LIST_ENTRY), SEP_LOWBOX_SESSION_TAG);
1293 |
1294 | if (*(PLIST_ENTRY*)(KernelSymbols.g_SessionLowboxMap) == NULL)
1295 | {
1296 | return STATUS_INSUFFICIENT_RESOURCES;
1297 | }
1298 |
1299 | InitializeListHead(*(PLIST_ENTRY*)(KernelSymbols.g_SessionLowboxMap));
1300 | }
1301 |
1302 | //find map entry
1303 | for (entry = (*(PLIST_ENTRY*)(KernelSymbols.g_SessionLowboxMap))->Flink; entry != *(PLIST_ENTRY*)(KernelSymbols.g_SessionLowboxMap); entry = entry->Flink)
1304 | {
1305 | MapEntry = (PSESSION_LOWBOX_MAP)CONTAINING_RECORD(entry, SESSION_LOWBOX_MAP, ListEntry);
1306 |
1307 | if (MapEntry->SessionId == SessionId)
1308 | {
1309 | *pLowboxNumberMapping = &MapEntry->LowboxMap;
1310 | return STATUS_SUCCESS;
1311 | }
1312 | }
1313 |
1314 | if (bInsert == FALSE)
1315 | {
1316 | return STATUS_NOT_FOUND;
1317 | }
1318 |
1319 | //insert new entry
1320 |
1321 | MapEntry = (PSESSION_LOWBOX_MAP)ExAllocatePool2(POOL_FLAG_PAGED, sizeof(SESSION_LOWBOX_MAP), SEP_LOWBOX_SESSION_TAG);
1322 |
1323 | if (MapEntry == NULL)
1324 | {
1325 | return STATUS_INSUFFICIENT_RESOURCES;
1326 | }
1327 |
1328 | ExInitializePushLock(&MapEntry->LowboxMap.Lock);
1329 | MapEntry->LowboxMap.Active = 0;
1330 | MapEntry->SessionId = SessionId;
1331 |
1332 | //insert into map list
1333 | InsertHeadList(*(PLIST_ENTRY*)(KernelSymbols.g_SessionLowboxMap), &MapEntry->ListEntry);
1334 |
1335 | *pLowboxNumberMapping = &MapEntry->LowboxMap;
1336 |
1337 | return STATUS_SUCCESS;
1338 | }
1339 |
1340 | #define LOWBOX_BITMAP_BITS 1024
1341 | NTSTATUS SepInitializeLowBoxNumberTable(PSEP_LOWBOX_NUMBER_MAPPING LowboxNumberMapping)
1342 | {
1343 | PVOID BitmapPool;
1344 |
1345 | LowboxNumberMapping->HashTable = NULL;
1346 |
1347 | if (RtlCreateHashTable(&LowboxNumberMapping->HashTable, 0, 0) == FALSE)
1348 | {
1349 | return STATUS_INSUFFICIENT_RESOURCES;
1350 | }
1351 |
1352 | BitmapPool = ExAllocatePool2(POOL_FLAG_PAGED, LOWBOX_BITMAP_BITS / 8, SEP_LOWBOX_SESSION_TAG);
1353 |
1354 | if (BitmapPool == NULL)
1355 | {
1356 | RtlDeleteHashTable(LowboxNumberMapping->HashTable);
1357 | return STATUS_INSUFFICIENT_RESOURCES;
1358 | }
1359 | else
1360 | {
1361 | LowboxNumberMapping->Bitmap.SizeOfBitMap = LOWBOX_BITMAP_BITS;
1362 | LowboxNumberMapping->Bitmap.Buffer = BitmapPool;
1363 | RtlClearAllBits(&LowboxNumberMapping->Bitmap);
1364 | LowboxNumberMapping->Active = 1;
1365 | }
1366 |
1367 | return STATUS_SUCCESS;
1368 |
1369 | }
1370 | VOID SepFindMatchingLowBoxNumberEntry(PRTL_DYNAMIC_HASH_TABLE HashTable, PISID Sid, PSEP_LOWBOX_NUMBER_ENTRY* pLowboxNumberEntry)
1371 | {
1372 | RTL_DYNAMIC_HASH_TABLE_CONTEXT Context;
1373 | ULONG Signature;
1374 | PRTL_DYNAMIC_HASH_TABLE_ENTRY Curr;
1375 | BOOLEAN bFound = FALSE;
1376 |
1377 | RtlZeroMemory(&Context, sizeof(Context));
1378 |
1379 | Signature = SID_HASH_ULONG(Sid);
1380 |
1381 | if (Signature == 0)
1382 | {
1383 | Signature = 1;
1384 | }
1385 |
1386 | for (Curr = RtlLookupEntryHashTable(HashTable, Signature, &Context); Curr != NULL; Curr = RtlGetNextEntryHashTable(HashTable, &Context))
1387 | {
1388 | if (RtlEqualSid(Sid, CONTAINING_RECORD(Curr, SEP_LOWBOX_NUMBER_ENTRY, HashEntry)->PackageSid))
1389 | {
1390 | bFound = TRUE;
1391 | break;
1392 | }
1393 | }
1394 |
1395 | *pLowboxNumberEntry = bFound ? CONTAINING_RECORD(Curr, SEP_LOWBOX_NUMBER_ENTRY, HashEntry) : NULL;
1396 |
1397 | return;
1398 | }
1399 | #define MAX_LOWBOX_BITMAP_GROW_SIZE 0x10000
1400 | NTSTATUS SepGetLowBoxNumberEntry(PSEP_LOWBOX_NUMBER_MAPPING LowboxNumberMapping, PISID PackageSid, PSEP_LOWBOX_NUMBER_ENTRY* pLowboxNumberEntry)
1401 | {
1402 | PSEP_LOWBOX_NUMBER_ENTRY Entry = NULL;
1403 | ULONG NewEntryLength;
1404 | ULONG BitStartingIndex;
1405 | ULONG NewBitsCount;
1406 | PVOID NewBitmapBuffer;
1407 | ULONG HashTableSignature;
1408 |
1409 | //find for existing entry take package sid as key
1410 |
1411 | SepFindMatchingLowBoxNumberEntry(LowboxNumberMapping->HashTable, PackageSid, &Entry);
1412 |
1413 | //lowbox number with same sid exists
1414 |
1415 | if (Entry)
1416 | {
1417 | if (InterlockedIncrement64( & Entry->ReferenceCount) <= 1)
1418 | {
1419 | RtlFailFast(FAST_FAIL_INVALID_REFERENCE_COUNT);
1420 | //never return
1421 | }
1422 | *pLowboxNumberEntry = Entry;
1423 | return STATUS_SUCCESS;
1424 | }
1425 |
1426 | //create new lowbox number
1427 |
1428 | //calcaute entry size
1429 |
1430 | NewEntryLength = LongAlignSize(SeLengthSid(PackageSid) + sizeof(SEP_LOWBOX_NUMBER_ENTRY));
1431 |
1432 | Entry = ExAllocatePool2(POOL_FLAG_PAGED, NewEntryLength, SEP_LOWBOX_SESSION_TAG);
1433 |
1434 | if (Entry == NULL)
1435 | {
1436 | return STATUS_INSUFFICIENT_RESOURCES;
1437 | }
1438 |
1439 | //Copy package SID content
1440 |
1441 | Entry->PackageSid = (PISID)((ULONG_PTR)Entry + sizeof(SEP_LOWBOX_NUMBER_ENTRY));
1442 | RtlCopySid(NewEntryLength - sizeof(SEP_LOWBOX_NUMBER_ENTRY), (PISID)((ULONG_PTR)Entry + sizeof(SEP_LOWBOX_NUMBER_ENTRY)), PackageSid);
1443 |
1444 | BitStartingIndex = RtlFindClearBitsAndSet(&LowboxNumberMapping->Bitmap, 1, 0);
1445 |
1446 | //all bits are dirty, grow a new bitmap
1447 |
1448 | if (BitStartingIndex == 0xFFFFFFFF)
1449 | {
1450 | //Double the bitmap size
1451 |
1452 | NewBitsCount = 2 * RtlNumberOfSetBits(&LowboxNumberMapping->Bitmap);
1453 |
1454 | if (NewBitsCount > MAX_LOWBOX_BITMAP_GROW_SIZE)
1455 | {
1456 | ExFreePool(Entry);
1457 | return STATUS_INSUFFICIENT_RESOURCES;
1458 | }
1459 |
1460 | NewBitmapBuffer = ExAllocatePool2(POOL_FLAG_PAGED, NewBitsCount / 8, SEP_LOWBOX_SESSION_TAG);
1461 |
1462 | if (NewBitmapBuffer == NULL)
1463 | {
1464 | ExFreePool(Entry);
1465 | return STATUS_INSUFFICIENT_RESOURCES;
1466 | }
1467 |
1468 | //free the old buffer
1469 | ExFreePool(LowboxNumberMapping->Bitmap.Buffer);
1470 |
1471 | LowboxNumberMapping->Bitmap.SizeOfBitMap = NewBitsCount;
1472 | LowboxNumberMapping->Bitmap.Buffer = NewBitmapBuffer;
1473 |
1474 | RtlClearAllBits(&LowboxNumberMapping->Bitmap);
1475 |
1476 | //reset previous bits
1477 | RtlSetBits(&LowboxNumberMapping->Bitmap, 0, NewBitsCount / 2);
1478 |
1479 | BitStartingIndex = RtlFindClearBitsAndSet(&LowboxNumberMapping->Bitmap, 1, 0);
1480 |
1481 | //sorry what??
1482 |
1483 | if (BitStartingIndex == 0xFFFFFFFF)
1484 | {
1485 | ExFreePool(Entry);
1486 | return STATUS_INSUFFICIENT_RESOURCES;
1487 | }
1488 | }
1489 |
1490 | if (BitStartingIndex >= MAX_LOWBOX_BITMAP_GROW_SIZE - 1)
1491 | {
1492 | ExFreePool(Entry);
1493 | return STATUS_INSUFFICIENT_RESOURCES;
1494 | }
1495 |
1496 | //insert new entry
1497 |
1498 | Entry->AtomTable = NULL;
1499 | Entry->LowboxNumber = BitStartingIndex + 1;
1500 | Entry->ReferenceCount = 1;
1501 |
1502 | HashTableSignature = SID_HASH_ULONG(PackageSid);
1503 |
1504 | if (HashTableSignature == 0)
1505 | {
1506 | HashTableSignature = 1;
1507 | }
1508 |
1509 | if (RtlInsertEntryHashTable(LowboxNumberMapping->HashTable, &Entry->HashEntry, HashTableSignature, NULL) == FALSE)
1510 | {
1511 | ExFreePool(Entry);
1512 | RtlClearBits(&LowboxNumberMapping->Bitmap, 1, BitStartingIndex);
1513 | return STATUS_INSUFFICIENT_RESOURCES;
1514 | }
1515 |
1516 | //Added reference to lowbox entry in 24h2, as it will be dereferenced again during token deletion in SepTokenDeleteMethod
1517 |
1518 | if (InterlockedIncrement64(&Entry->ReferenceCount) <= 1)
1519 | {
1520 | RtlFailFast(FAST_FAIL_INVALID_REFERENCE_COUNT);
1521 | }
1522 | //end
1523 |
1524 | *pLowboxNumberEntry = Entry;
1525 | return STATUS_SUCCESS;
1526 | }
1527 | #define GLOBAL_SESSION_LOWBOX_ARRAY_COUNT 5
1528 |
1529 | //SEP_LOWBOX_NUMBER_MAPPING g_SessionLowboxArray[GLOBAL_SESSION_LOWBOX_ARRAY_COUNT];
1530 |
1531 | NTSTATUS SepSetTokenLowboxNumber(PTOKEN Token, PISID PackageSid)
1532 | {
1533 | ULONG SessionId = Token->SessionId;
1534 | BOOLEAN bLockedShared = FALSE;
1535 | BOOLEAN bLockedExclusive = FALSE;
1536 | NTSTATUS Status = STATUS_SUCCESS;
1537 | PSEP_LOWBOX_NUMBER_MAPPING LowboxNumberMapping = NULL;
1538 | PSEP_LOWBOX_NUMBER_ENTRY LowboxNumberEntry = NULL;
1539 |
1540 | if (SessionId < GLOBAL_SESSION_LOWBOX_ARRAY_COUNT)
1541 | {
1542 | LowboxNumberMapping = &((SEP_LOWBOX_NUMBER_MAPPING*)(KernelSymbols.g_SessionLowboxArray))[SessionId];
1543 | }
1544 | else
1545 | {
1546 | KeEnterCriticalRegion();
1547 |
1548 | ExAcquirePushLockShared((EX_PUSH_LOCK*)(KernelSymbols.LowboxSessionMapLock));
1549 |
1550 | bLockedShared = TRUE;
1551 |
1552 | Status = SepGetTokenSessionMapEntry(SessionId, FALSE, &LowboxNumberMapping);
1553 |
1554 | if (!NT_SUCCESS(Status))
1555 | {
1556 | if (Status != STATUS_NOT_FOUND)
1557 | {
1558 | ExReleasePushLockShared((EX_PUSH_LOCK*)(KernelSymbols.LowboxSessionMapLock));
1559 | KeLeaveCriticalRegion();
1560 | return Status;
1561 | }
1562 |
1563 | ExReleasePushLockShared((EX_PUSH_LOCK*)(KernelSymbols.LowboxSessionMapLock));
1564 | KeLeaveCriticalRegion();
1565 |
1566 | KeEnterCriticalRegion();
1567 |
1568 | ExAcquirePushLockExclusive((EX_PUSH_LOCK*)(KernelSymbols.LowboxSessionMapLock));
1569 |
1570 | Status = SepGetTokenSessionMapEntry(SessionId, TRUE, &LowboxNumberMapping);
1571 |
1572 | bLockedShared = FALSE;
1573 | bLockedExclusive = TRUE;
1574 |
1575 | if (!NT_SUCCESS(Status))
1576 | {
1577 | ExReleasePushLockExclusive((EX_PUSH_LOCK*)(KernelSymbols.LowboxSessionMapLock));
1578 | KeLeaveCriticalRegion();
1579 | return Status;
1580 | }
1581 | }
1582 | }
1583 |
1584 | if (LowboxNumberMapping->Active == 0)
1585 | {
1586 | KeEnterCriticalRegion();
1587 | ExAcquirePushLockExclusive(&LowboxNumberMapping->Lock);
1588 | if (LowboxNumberMapping->Active == 0)
1589 | {
1590 | Status = SepInitializeLowBoxNumberTable(LowboxNumberMapping);
1591 | }
1592 |
1593 | ExReleasePushLockExclusive(&LowboxNumberMapping->Lock);
1594 | KeLeaveCriticalRegion();
1595 | }
1596 |
1597 | if (Status == STATUS_SUCCESS)
1598 | {
1599 | KeEnterCriticalRegion();
1600 | ExAcquirePushLockExclusive(&LowboxNumberMapping->Lock);
1601 |
1602 | Status = SepGetLowBoxNumberEntry(LowboxNumberMapping, PackageSid, &LowboxNumberEntry);
1603 |
1604 | if (Status == STATUS_SUCCESS)
1605 | {
1606 | Token->LowboxNumberEntry = LowboxNumberEntry;
1607 | }
1608 |
1609 | ExReleasePushLockExclusive(&LowboxNumberMapping->Lock);
1610 | KeLeaveCriticalRegion();
1611 | }
1612 |
1613 | if (bLockedExclusive)
1614 | {
1615 | ExReleasePushLockExclusive((EX_PUSH_LOCK*)(KernelSymbols.LowboxSessionMapLock));
1616 | KeLeaveCriticalRegion();
1617 | }
1618 | else if (bLockedShared)
1619 | {
1620 | ExReleasePushLockShared((EX_PUSH_LOCK*)(KernelSymbols.LowboxSessionMapLock));
1621 | KeLeaveCriticalRegion();
1622 | }
1623 |
1624 | return Status;
1625 | }
1626 | NTSTATUS SepReferenceCachedTokenHandles(ULONG HandleCount , HANDLE* Handles , HANDLE* NewHandles)
1627 | {
1628 | NTSTATUS status;
1629 | ULONG i;
1630 |
1631 | status = STATUS_SUCCESS;
1632 |
1633 | for (i = 0 ; i < HandleCount ; i++)
1634 | {
1635 | status = ZwDuplicateObject(NtCurrentProcess(), Handles[i], NtCurrentProcess(), &NewHandles[i], 0, OBJ_KERNEL_HANDLE, DUPLICATE_SAME_ACCESS);
1636 |
1637 | if (!NT_SUCCESS(status))
1638 | {
1639 | break;
1640 | }
1641 | }
1642 |
1643 | if (i == HandleCount)
1644 | {
1645 | return status;
1646 | }
1647 |
1648 | for (; i != 0; i--)
1649 | {
1650 | ZwClose(NewHandles[i]);
1651 | }
1652 |
1653 | return status;
1654 | }
1655 |
1656 | NTSTATUS SepQueryNameString(PVOID Object , POBJECT_NAME_INFORMATION* ObjectNameInfo)
1657 | {
1658 | NTSTATUS Status;
1659 | POBJECT_NAME_INFORMATION NameInfo;
1660 | ULONG ReturnLength = 0;
1661 |
1662 | *ObjectNameInfo = NULL;
1663 |
1664 | Status = ObQueryNameString(Object, NULL, 0, &ReturnLength);
1665 |
1666 | if (Status == STATUS_INFO_LENGTH_MISMATCH || Status == STATUS_BUFFER_TOO_SMALL)
1667 | {
1668 | NameInfo = (POBJECT_NAME_INFORMATION)ExAllocatePool2(POOL_FLAG_PAGED, ReturnLength, SEP_OBJECT_NAME_INFORMATION_TAG);
1669 |
1670 | *ObjectNameInfo = NameInfo;
1671 |
1672 | if (NameInfo)
1673 | {
1674 | Status = ObQueryNameString(Object, NameInfo, ReturnLength, &ReturnLength);
1675 |
1676 | if (!NT_SUCCESS(Status) || NameInfo->Name.Length == 0)
1677 | {
1678 | ExFreePool(NameInfo);
1679 |
1680 | *ObjectNameInfo = NULL;
1681 |
1682 | if (NT_SUCCESS(Status) && ObGetObjectType(Object) == *PsProcessType)
1683 | {
1684 | SeLocateProcessImageName((PEPROCESS)Object,(PUNICODE_STRING*)ObjectNameInfo);
1685 | }
1686 | return STATUS_SUCCESS;
1687 | }
1688 | }
1689 | else
1690 | {
1691 | return STATUS_INSUFFICIENT_RESOURCES;
1692 | }
1693 | }
1694 | return Status;
1695 | }
1696 |
1697 | NTSTATUS RtlGetAppContainerParent(PSID PackageSID , PISID* ParentSID)
1698 | {
1699 | PISID ParentSid;
1700 | NTSTATUS status;
1701 | ULONG i;
1702 | APPCONTAINER_SID_TYPE SidType;
1703 |
1704 | *ParentSID = NULL;
1705 | SidType = 0;
1706 |
1707 | if (!NT_SUCCESS(RtlGetAppContainerSidType(PackageSID, &SidType)) || SidType != ChildAppContainerSidType)
1708 | {
1709 | return STATUS_INVALID_PARAMETER;
1710 | }
1711 |
1712 | ParentSid = (PISID)ExAllocatePool2(POOL_FLAG_NON_PAGED | POOL_FLAG_USE_QUOTA, RtlLengthRequiredSid(SECURITY_PARENT_PACKAGE_RID_COUNT), RTL_PRIVATE_BUFFER_TAG);
1713 |
1714 | if (ParentSid == NULL)
1715 | {
1716 | return STATUS_INSUFFICIENT_RESOURCES;
1717 | }
1718 |
1719 | status = RtlInitializeSid(ParentSid, &RtlpAppPackageAuthority, SECURITY_PARENT_PACKAGE_RID_COUNT);
1720 |
1721 | if (!NT_SUCCESS(status))
1722 | {
1723 | ExFreePool(ParentSid);
1724 | return status ;
1725 | }
1726 |
1727 | for (i = 0; i < SECURITY_PARENT_PACKAGE_RID_COUNT; i++)
1728 | {
1729 | ParentSid->SubAuthority[i] = *RtlSubAuthoritySid(PackageSID, i);
1730 | }
1731 |
1732 | *ParentSID = ParentSid;
1733 |
1734 | return status;
1735 | }
1736 |
1737 |
1738 | UNICODE_STRING AllowedCachedObjectNames[] = {
1739 | RTL_CONSTANT_STRING(L"Local"),
1740 | RTL_CONSTANT_STRING(L"Global"),
1741 | RTL_CONSTANT_STRING(L"RPC Control"),
1742 | RTL_CONSTANT_STRING(L"Session"),
1743 | RTL_CONSTANT_STRING(L"AppContainerNamedObjects")
1744 | };
1745 |
1746 | NTSTATUS SepValidateReferencedCachedHandles(
1747 | PTOKEN Token,
1748 | SEP_CACHED_HANDLES_ENTRY_DESCRIPTOR* EntryDescriptor,
1749 | ULONG HandleCount,
1750 | HANDLE* NewHandles)
1751 | {
1752 | NTSTATUS status = STATUS_SUCCESS;
1753 | PVOID Object = NULL;
1754 | ULONG AllowedDirectoryCount = 0;
1755 | POBJECT_TYPE ObjectType;
1756 | ULONG j;
1757 | BOOLEAN bValid ;
1758 | BOOLEAN bSidNameAllocated = FALSE;
1759 | PSID ParentSID;
1760 | APPCONTAINER_SID_TYPE SidType = 0;
1761 | ULONG i;
1762 | POBJECT_NAME_INFORMATION NameInfo = NULL;
1763 | PCUNICODE_STRING pPrefixName = NULL;
1764 | UNICODE_STRING ObjectName;
1765 | UNICODE_STRING SidName = { 0, 0 , NULL };
1766 | UNICODE_STRING HeaderObjectName;
1767 | POBJECT_HEADER_NAME_INFO HeaderNameInfo;
1768 | ALLOWED_CACHED_DIRECTORY AllowedDirectories[2];
1769 | WCHAR AllowedPath1[256];
1770 | WCHAR ChildSidName[256];
1771 |
1772 | if (EntryDescriptor->DescriptorType == SepCachedHandlesEntryBnoIsolation)
1773 | {
1774 | pPrefixName = &EntryDescriptor->u1.IsolationPrefix;
1775 |
1776 | status = RtlStringCchPrintfW(AllowedPath1, MAX_OBJECT_PATH , L"\\Sessions\\%d", Token->SessionId);
1777 |
1778 | if (!NT_SUCCESS(status))
1779 | {
1780 | goto Exit;
1781 | }
1782 |
1783 | RtlInitUnicodeString(&AllowedDirectories[0].DirectoryName, AllowedPath1);
1784 |
1785 | AllowedDirectories[0].bCheckName = TRUE;
1786 | AllowedDirectoryCount = 1;
1787 |
1788 | if (Token->SessionId == RtlGetCurrentServiceSessionId())
1789 | {
1790 | RtlInitUnicodeString(&AllowedDirectories[1].DirectoryName, L"\\BaseNamedObjects");
1791 | AllowedDirectories[1].bCheckName = TRUE;
1792 | AllowedDirectoryCount = 2;
1793 | }
1794 | }
1795 | else if (EntryDescriptor->DescriptorType == SepCachedHandlesEntryLowbox)
1796 | {
1797 | status = RtlGetAppContainerSidType(EntryDescriptor->u1.PackageSid, &SidType);
1798 |
1799 | if (!NT_SUCCESS(status))
1800 | {
1801 | goto Exit;
1802 | }
1803 |
1804 | if (SidType == ParentAppContainerSidType)
1805 | {
1806 | status = RtlConvertSidToUnicodeString(&SidName, EntryDescriptor->u1.PackageSid, TRUE);
1807 |
1808 | if (!NT_SUCCESS(status))
1809 | {
1810 | goto Exit;
1811 | }
1812 |
1813 | bSidNameAllocated = TRUE;
1814 | }
1815 | else
1816 | {
1817 | status = RtlStringCchPrintfW(ChildSidName,
1818 | MAX_OBJECT_PATH,
1819 | L"%u-%u-%u-%u",
1820 | *RtlSubAuthoritySid(EntryDescriptor->u1.PackageSid, SECURITY_CHILD_PACKAGE_RID_COUNT - 4),
1821 | *RtlSubAuthoritySid(EntryDescriptor->u1.PackageSid, SECURITY_CHILD_PACKAGE_RID_COUNT - 3),
1822 | *RtlSubAuthoritySid(EntryDescriptor->u1.PackageSid, SECURITY_CHILD_PACKAGE_RID_COUNT - 2),
1823 | *RtlSubAuthoritySid(EntryDescriptor->u1.PackageSid, SECURITY_CHILD_PACKAGE_RID_COUNT - 1));
1824 |
1825 | if (!NT_SUCCESS(status))
1826 | {
1827 | goto Exit;
1828 | }
1829 |
1830 | RtlInitUnicodeString(&SidName, ChildSidName);
1831 | }
1832 |
1833 | pPrefixName = &SidName;
1834 |
1835 | status = RtlStringCchPrintfW(AllowedPath1, MAX_OBJECT_PATH, L"\\Sessions\\%d", Token->SessionId);
1836 |
1837 | if (!NT_SUCCESS(status))
1838 | {
1839 | goto Exit;
1840 | }
1841 |
1842 |
1843 | RtlInitUnicodeString(&AllowedDirectories[0].DirectoryName, AllowedPath1);
1844 |
1845 | AllowedDirectories[0].bCheckName = TRUE;
1846 |
1847 | RtlInitUnicodeString(&AllowedDirectories[1].DirectoryName, L"\\Device\\NamedPipe");
1848 |
1849 | AllowedDirectories[1].bCheckName = FALSE;
1850 |
1851 | AllowedDirectoryCount = 2;
1852 | }
1853 |
1854 | //For subsequent descriptor categorizations, execution continues without an explicit return.
1855 | //While not ideal, this is presently acceptable as the function has only two caller types in its invocation chain for now.
1856 |
1857 |
1858 | for (i = 0; i < HandleCount; i++)
1859 | {
1860 | if (Object)
1861 | {
1862 | ObDereferenceObject(Object);
1863 | }
1864 |
1865 | Object = NULL;
1866 |
1867 | status = ObReferenceObjectByHandle(NewHandles[i], 0, NULL, KernelMode, &Object, NULL);
1868 |
1869 | if (!NT_SUCCESS(status))
1870 | {
1871 | continue;
1872 | }
1873 |
1874 | ObjectType = ObGetObjectType(Object);
1875 |
1876 | if (ObjectType != ObpSymbolicLinkObjectType &&
1877 | ObjectType != ObpDirectoryObjectType &&
1878 | (ObjectType != *IoFileObjectType || ((PFILE_OBJECT)Object)->DeviceObject->DeviceType != FILE_DEVICE_NAMED_PIPE ))
1879 | {
1880 | status = STATUS_INVALID_PARAMETER;
1881 | break;
1882 | }
1883 |
1884 | if (NameInfo)
1885 | {
1886 | ExFreePool(NameInfo);
1887 | NameInfo = NULL;
1888 | }
1889 |
1890 | status = SepQueryNameString(Object, &NameInfo);
1891 |
1892 | if (!NT_SUCCESS(status))
1893 | {
1894 | break;
1895 | }
1896 |
1897 | if (NameInfo == NULL || NameInfo->Name.MaximumLength == 0)
1898 | {
1899 | status = STATUS_INVALID_PARAMETER;
1900 | break;
1901 | }
1902 |
1903 | ObjectName = NameInfo->Name;
1904 |
1905 | for (j = 0; j < AllowedDirectoryCount; j++)
1906 | {
1907 | if (RtlPrefixUnicodeString(&AllowedDirectories[j].DirectoryName, &ObjectName, TRUE))
1908 | {
1909 | break;
1910 | }
1911 | }
1912 |
1913 | if (j == AllowedDirectoryCount)
1914 | {
1915 | status = STATUS_INVALID_PARAMETER;
1916 | break;
1917 | }
1918 |
1919 | if (AllowedDirectories[j].bCheckName)
1920 | {
1921 | HeaderNameInfo = ObQueryNameInfo(Object);
1922 |
1923 | if (HeaderNameInfo == NULL || HeaderNameInfo->Name.MaximumLength == 0)
1924 | {
1925 | status = STATUS_INVALID_PARAMETER;
1926 | break;
1927 | }
1928 |
1929 | HeaderObjectName = HeaderNameInfo->Name;
1930 |
1931 | //Check object prefix name white list
1932 |
1933 | if (RtlEqualUnicodeString(&HeaderObjectName, pPrefixName, TRUE) == FALSE)
1934 | {
1935 | //Check object name white list
1936 |
1937 | for (j = 0; j < ARRAYSIZE(AllowedCachedObjectNames); j++)
1938 | {
1939 | if (RtlEqualUnicodeString(&HeaderObjectName, &AllowedCachedObjectNames[j], TRUE))
1940 | {
1941 | break;
1942 | }
1943 | }
1944 |
1945 | if (j != ARRAYSIZE(AllowedCachedObjectNames))
1946 | {
1947 | continue;
1948 | }
1949 |
1950 | //white list, object name = SID ?
1951 |
1952 | if (SidType != ChildAppContainerSidType)
1953 | {
1954 | status = STATUS_INVALID_PARAMETER;
1955 | break;
1956 | }
1957 |
1958 | ParentSID = NULL;
1959 |
1960 | if (!NT_SUCCESS(RtlGetAppContainerParent(EntryDescriptor->u1.PackageSid, (PISID*)&ParentSID)))
1961 | {
1962 | status = STATUS_INVALID_PARAMETER;
1963 | break;
1964 | }
1965 |
1966 | ObjectName.Buffer = NULL;
1967 | ObjectName.Length = 0;
1968 | ObjectName.MaximumLength = 0;
1969 |
1970 | if (!NT_SUCCESS(RtlConvertSidToUnicodeString(&ObjectName, ParentSID, TRUE)))
1971 | {
1972 | status = STATUS_INVALID_PARAMETER;
1973 | break;
1974 |
1975 | }
1976 |
1977 | bValid = (RtlEqualUnicodeString(&HeaderObjectName, &ObjectName, TRUE) == TRUE);
1978 |
1979 | RtlFreeUnicodeString(&ObjectName);
1980 |
1981 | ExFreePool(ParentSID);
1982 |
1983 | if (bValid == FALSE)
1984 | {
1985 | status = STATUS_INVALID_PARAMETER;
1986 | break;
1987 | }
1988 | }
1989 | }
1990 | }
1991 |
1992 | Exit:
1993 | if (NameInfo)
1994 | {
1995 | ExFreePool(NameInfo);
1996 | }
1997 |
1998 | if (Object)
1999 | {
2000 | ObDereferenceObject(Object);
2001 | }
2002 |
2003 | if (bSidNameAllocated)
2004 | {
2005 | RtlFreeUnicodeString(&SidName);
2006 | }
2007 |
2008 | return status;
2009 | }
2010 |
2011 | NTSTATUS SepCloseCachedTokenHandles(ULONG HandleCount, HANDLE* Handles)
2012 | {
2013 | NTSTATUS status = STATUS_SUCCESS;
2014 | ULONG i;
2015 |
2016 | for (i = 0; i < HandleCount; i++)
2017 | {
2018 | status = ZwClose(Handles[i]);
2019 | }
2020 | return status;
2021 | }
2022 |
2023 | NTSTATUS SepAllocateAndInitializeCachedHandleEntry( PSEP_CACHED_HANDLES_ENTRY_DESCRIPTOR EntryDescriptor, PSEP_CACHED_HANDLES_ENTRY* HandlesEntryReturn)
2024 | {
2025 | ULONG RequiredLength;
2026 | PSEP_CACHED_HANDLES_ENTRY Entry;
2027 |
2028 | *HandlesEntryReturn = NULL;
2029 | RequiredLength = sizeof(SEP_CACHED_HANDLES_ENTRY);
2030 |
2031 | if (EntryDescriptor->DescriptorType == SepCachedHandlesEntryLowbox)
2032 | {
2033 | RequiredLength = RtlLengthRequiredSid(((PISID)EntryDescriptor->u1.PackageSid)->SubAuthorityCount) + sizeof(SEP_CACHED_HANDLES_ENTRY);
2034 | }
2035 | else if (EntryDescriptor->DescriptorType == SepCachedHandlesEntryBnoIsolation)
2036 | {
2037 | RequiredLength = EntryDescriptor->u1.IsolationPrefix.MaximumLength + sizeof(SEP_CACHED_HANDLES_ENTRY);
2038 | }
2039 |
2040 | Entry = (PSEP_CACHED_HANDLES_ENTRY)ExAllocatePool2(POOL_FLAG_PAGED, LongAlignSize(RequiredLength), 'sLeS');
2041 |
2042 | if (Entry == NULL)
2043 | {
2044 | return STATUS_INSUFFICIENT_RESOURCES;
2045 | }
2046 |
2047 |
2048 | Entry->Handles = NULL;
2049 | Entry->HandleCount = 0;
2050 | Entry->ReferenceCount = 1;
2051 | Entry->EntryDescriptor.DescriptorType = EntryDescriptor->DescriptorType;
2052 |
2053 | if (EntryDescriptor->DescriptorType == SepCachedHandlesEntryLowbox)
2054 | {
2055 | Entry->EntryDescriptor.u1.PackageSid = (PSID)((ULONG_PTR)Entry + sizeof(SEP_CACHED_HANDLES_ENTRY));
2056 | RtlCopySid(RtlLengthRequiredSid(((PISID)EntryDescriptor->u1.PackageSid)->SubAuthorityCount),
2057 | (PSID)((ULONG_PTR)Entry + sizeof(SEP_CACHED_HANDLES_ENTRY)),
2058 | EntryDescriptor->u1.PackageSid);
2059 | }
2060 | else
2061 | {
2062 | if (EntryDescriptor->DescriptorType == SepCachedHandlesEntryBnoIsolation)
2063 | {
2064 | Entry->EntryDescriptor.u1.IsolationPrefix.Length = EntryDescriptor->u1.IsolationPrefix.Length;
2065 | Entry->EntryDescriptor.u1.IsolationPrefix.MaximumLength = EntryDescriptor->u1.IsolationPrefix.MaximumLength;
2066 | Entry->EntryDescriptor.u1.IsolationPrefix.Buffer = (WCHAR*)((ULONG_PTR)Entry + sizeof(SEP_CACHED_HANDLES_ENTRY));
2067 |
2068 | RtlCopyUnicodeString(&Entry->EntryDescriptor.u1.IsolationPrefix, &EntryDescriptor->u1.IsolationPrefix);
2069 |
2070 | }
2071 |
2072 | }
2073 |
2074 | *HandlesEntryReturn = Entry;
2075 | return STATUS_SUCCESS;
2076 | }
2077 | ULONG SepComputeCachedHandlesEntrySignature(PSEP_CACHED_HANDLES_ENTRY_DESCRIPTOR EntryDescriptor)
2078 | {
2079 | ULONG HashValue;
2080 |
2081 | if (EntryDescriptor->DescriptorType == SepCachedHandlesEntryBnoIsolation)
2082 | {
2083 | RtlHashUnicodeString(&EntryDescriptor->u1.IsolationPrefix, TRUE, HASH_STRING_ALGORITHM_DEFAULT, &HashValue);
2084 | }
2085 | else if (EntryDescriptor->DescriptorType == SepCachedHandlesEntryLowbox)
2086 | {
2087 | HashValue = SID_HASH_ULONG(EntryDescriptor->u1.PackageSid);
2088 |
2089 | if (HashValue == 0)
2090 | {
2091 | HashValue = 1;
2092 | }
2093 |
2094 | return HashValue;
2095 | }
2096 |
2097 | return 0;
2098 | }
2099 | NTSTATUS SepFindMatchingCachedHandlesEntry(PRTL_DYNAMIC_HASH_TABLE HashTable, ULONG Signature, PSEP_CACHED_HANDLES_ENTRY_DESCRIPTOR EntryDescriptor, PSEP_CACHED_HANDLES_ENTRY* Entry)
2100 | {
2101 | struct _RTL_DYNAMIC_HASH_TABLE_CONTEXT Context = { 0 };
2102 | BOOLEAN bFound = FALSE;
2103 | PRTL_DYNAMIC_HASH_TABLE_ENTRY i;
2104 | PSEP_CACHED_HANDLES_ENTRY HandlesEntry = NULL ;
2105 |
2106 | for (i = RtlLookupEntryHashTable(HashTable, Signature, &Context); i; i = RtlGetNextEntryHashTable(HashTable, &Context))
2107 | {
2108 | HandlesEntry = CONTAINING_RECORD(i, SEP_CACHED_HANDLES_ENTRY, HashEntry);
2109 |
2110 | if (EntryDescriptor->DescriptorType == HandlesEntry->EntryDescriptor.DescriptorType)
2111 | {
2112 | if (EntryDescriptor->DescriptorType == SepCachedHandlesEntryLowbox)
2113 | {
2114 | if (RtlEqualSid(EntryDescriptor->u1.PackageSid, HandlesEntry->EntryDescriptor.u1.PackageSid))
2115 | {
2116 | bFound = TRUE;
2117 | break;
2118 | }
2119 | }
2120 | else if (EntryDescriptor->DescriptorType == SepCachedHandlesEntryBnoIsolation)
2121 | {
2122 | if (RtlEqualUnicodeString(&EntryDescriptor->u1.IsolationPrefix, &HandlesEntry->EntryDescriptor.u1.IsolationPrefix, TRUE) == TRUE)
2123 | {
2124 | bFound = TRUE;
2125 | break;
2126 | }
2127 | }
2128 | }
2129 | }
2130 |
2131 | if (bFound)
2132 | {
2133 | *Entry = HandlesEntry;
2134 | }
2135 | else
2136 | {
2137 | *Entry = NULL;
2138 | }
2139 |
2140 | return STATUS_SUCCESS;
2141 |
2142 | }
2143 | NTSTATUS SepGetCachedHandlesEntry(PSEP_CACHED_HANDLES_TABLE HandleTable,
2144 | PSEP_CACHED_HANDLES_ENTRY_DESCRIPTOR EntryDescriptor,
2145 | BOOLEAN* bReferenced,
2146 | PSEP_CACHED_HANDLES_ENTRY* EntryReturned)
2147 | {
2148 | struct _RTL_DYNAMIC_HASH_TABLE* HashTable = HandleTable->HashTable;
2149 | NTSTATUS Status;
2150 | ULONG HashValue = 0 ;
2151 | PSEP_CACHED_HANDLES_ENTRY HandlesEntry = NULL;
2152 |
2153 | HashValue = SepComputeCachedHandlesEntrySignature(EntryDescriptor);
2154 |
2155 | *bReferenced = FALSE;
2156 |
2157 | HandlesEntry = NULL;
2158 |
2159 | SepFindMatchingCachedHandlesEntry(HashTable, HashValue, EntryDescriptor, &HandlesEntry);
2160 |
2161 |
2162 | if (HandlesEntry)
2163 | {
2164 | if (InterlockedIncrement64(&HandlesEntry->ReferenceCount) <= 1)
2165 | {
2166 | RtlFailFast(FAST_FAIL_INVALID_REFERENCE_COUNT);
2167 | //never return
2168 | }
2169 | *EntryReturned = HandlesEntry;
2170 | *bReferenced = TRUE;
2171 | return STATUS_SUCCESS;
2172 | }
2173 |
2174 | Status = SepAllocateAndInitializeCachedHandleEntry(EntryDescriptor, &HandlesEntry);
2175 |
2176 | if (!NT_SUCCESS(Status))
2177 | {
2178 | return Status;
2179 | }
2180 |
2181 | if (RtlInsertEntryHashTable(HashTable, &HandlesEntry->HashEntry, HashValue, NULL) == FALSE)
2182 | {
2183 | ExFreePool(HandlesEntry);
2184 | return STATUS_INSUFFICIENT_RESOURCES;
2185 | }
2186 |
2187 | *EntryReturned = HandlesEntry;
2188 |
2189 | return STATUS_SUCCESS;
2190 |
2191 | }
2192 |
2193 |
2194 | NTSTATUS SepSetTokenCachedHandles(PTOKEN Token, SEP_CACHED_HANDLES_ENTRY_DESCRIPTOR* EntryDescriptor, ULONG HandleCount, HANDLE* Handles)
2195 | {
2196 | HANDLE* NewHandles = NULL;
2197 | BOOLEAN bHandleDuplicated = FALSE;
2198 | NTSTATUS Status;
2199 | SEP_CACHED_HANDLES_TABLE* SessionCachedHandlesTable;
2200 | BOOLEAN bAddHandleTable;
2201 | PSEP_CACHED_HANDLES_ENTRY Entry = NULL;
2202 | BOOLEAN bReferenced = FALSE;
2203 |
2204 | if (HandleCount)
2205 | {
2206 | NewHandles = (HANDLE*)ExAllocatePool2(POOL_FLAG_PAGED, sizeof(HANDLE) * HandleCount, 'cHeS');
2207 |
2208 | if (NewHandles == NULL)
2209 | {
2210 | return STATUS_NO_MEMORY;
2211 | }
2212 |
2213 | Status = SepReferenceCachedTokenHandles(HandleCount, Handles, NewHandles);
2214 |
2215 | if (!NT_SUCCESS(Status))
2216 | {
2217 | ExFreePool(NewHandles);
2218 | return Status;
2219 | }
2220 |
2221 | bHandleDuplicated = TRUE;
2222 |
2223 | Status = SepValidateReferencedCachedHandles(Token, EntryDescriptor, HandleCount, NewHandles);
2224 |
2225 | if (!NT_SUCCESS(Status))
2226 | {
2227 | SepCloseCachedTokenHandles(HandleCount, NewHandles);
2228 | ExFreePool(NewHandles);
2229 | return Status;
2230 | }
2231 | }
2232 |
2233 | KeEnterCriticalRegion();
2234 | SessionCachedHandlesTable = &Token->LogonSession->CachedHandlesTable;
2235 |
2236 | ExAcquirePushLockExclusive(&SessionCachedHandlesTable->Lock);
2237 |
2238 |
2239 | if (SessionCachedHandlesTable->HashTable == NULL)
2240 | {
2241 | if (RtlCreateHashTable(&SessionCachedHandlesTable->HashTable, 0, 0) == FALSE)
2242 | {
2243 | Status = STATUS_INSUFFICIENT_RESOURCES;
2244 | goto Exit;
2245 | }
2246 | }
2247 |
2248 | Status = SepGetCachedHandlesEntry(SessionCachedHandlesTable, EntryDescriptor, &bReferenced, &Entry);
2249 |
2250 | if (Status != STATUS_SUCCESS)
2251 | {
2252 | goto Exit;
2253 | }
2254 |
2255 |
2256 | bAddHandleTable = FALSE;
2257 |
2258 | if (EntryDescriptor->DescriptorType == SepCachedHandlesEntryLowbox)
2259 | {
2260 | Token->LowboxHandlesEntry = Entry;
2261 | if (HandleCount && Entry->HandleCount == 0)
2262 | {
2263 | bAddHandleTable = TRUE;
2264 | }
2265 | }
2266 | else if (EntryDescriptor->DescriptorType == SepCachedHandlesEntryBnoIsolation)
2267 | {
2268 | Token->BnoIsolationHandlesEntry = Entry;
2269 |
2270 | if (bReferenced == FALSE)
2271 | {
2272 | bAddHandleTable = TRUE;
2273 | }
2274 | }
2275 |
2276 | if (bAddHandleTable)
2277 | {
2278 | Entry->HandleCount = HandleCount;
2279 | Entry->Handles = (PVOID)NewHandles;
2280 | }
2281 |
2282 | bHandleDuplicated = FALSE;
2283 |
2284 | NewHandles = NULL;
2285 |
2286 | Exit:
2287 | ExReleasePushLockExclusive(&SessionCachedHandlesTable->Lock);
2288 | KeLeaveCriticalRegion();
2289 |
2290 | if (NewHandles)
2291 | {
2292 | if (bHandleDuplicated)
2293 | {
2294 | SepCloseCachedTokenHandles(HandleCount, NewHandles);
2295 | }
2296 |
2297 | ExFreePool(NewHandles);
2298 | }
2299 |
2300 | return Status;
2301 | }
2302 |
2303 | NTSTATUS SepSetTokenPackage(PTOKEN Token , PISID PackageSid)
2304 | {
2305 | ULONG SidLength;
2306 | PSID NewSid;
2307 |
2308 | if (Token->Package && RtlIsParentOfChildAppContainer(Token->Package, PackageSid) == FALSE)
2309 | {
2310 | return STATUS_ACCESS_DENIED;
2311 | }
2312 |
2313 | SidLength = LongAlignSize(SeLengthSid(PackageSid));
2314 |
2315 | NewSid = (PSID)ExAllocatePool2(POOL_FLAG_PAGED, SidLength, SEP_SID_TAG);
2316 |
2317 |
2318 | if (NewSid == NULL)
2319 | {
2320 | return STATUS_INSUFFICIENT_RESOURCES;
2321 | }
2322 |
2323 | RtlCopySid(SidLength , NewSid , PackageSid);
2324 |
2325 | if (Token->Package)
2326 | {
2327 | ExFreePool(Token->Package);
2328 | }
2329 |
2330 | Token->Package = NewSid;
2331 |
2332 | return STATUS_SUCCESS;
2333 | }
2334 |
2335 | PACE_HEADER RtlFindAceBySid(PACL pAcl, PSID pSid, PULONG pIndex)
2336 | {
2337 | ULONG i;
2338 | PACE_HEADER pAce;
2339 | PSID AceSid;
2340 |
2341 | if (pAcl == NULL)
2342 | {
2343 | return NULL;
2344 | }
2345 |
2346 | for (i = 0, pAce = FirstAce(pAcl); i < pAcl->AceCount; i++, pAce = NextAce(pAce))
2347 | {
2348 | if (IsAllowedAceType(pAce))
2349 | {
2350 | AceSid = (PSID) & (((PACCESS_ALLOWED_ACE)pAce)->SidStart);
2351 | }
2352 | else if (IsCompoundAceType(pAce))
2353 | {
2354 | AceSid = (PSID) & (((PKNOWN_COMPOUND_ACE)pAce)->SidStart);
2355 | }
2356 | else if (IsObjectAceType(pAce) || IsCallbackObjectAceType(pAce) || IsSytstemCallbackObjectAceType(pAce))
2357 | {
2358 | AceSid = RtlObjectAceSid(pAce);
2359 | }
2360 | else
2361 | {
2362 | AceSid = NULL;
2363 | }
2364 |
2365 | if (AceSid)
2366 | {
2367 | if (pIndex == NULL)
2368 | {
2369 | if (RtlEqualSid(AceSid, pSid))
2370 | {
2371 | return pAce;
2372 | }
2373 | }
2374 | else
2375 | {
2376 | if (i >= *pIndex && RtlEqualSid(AceSid, pSid))
2377 | {
2378 | *pIndex = i;
2379 | return pAce;
2380 | }
2381 | }
2382 | }
2383 | }
2384 |
2385 | return NULL;
2386 | }
2387 |
2388 | NTSTATUS SepExpandDynamic(PTOKEN Token, ULONG NewLength)
2389 | {
2390 | ULONG CurrentSize;
2391 | PVOID NewDynamic;
2392 | PVOID DynamicPart;
2393 |
2394 | CurrentSize = Token->DynamicAvailable + SeLengthSid(Token->PrimaryGroup);
2395 |
2396 | if (Token->DefaultDacl)
2397 | {
2398 | CurrentSize += Token->DefaultDacl->AclSize;
2399 | }
2400 |
2401 | if (NewLength <= CurrentSize)
2402 | {
2403 | STATUS_SUCCESS;
2404 | }
2405 |
2406 | NewDynamic = ExAllocatePool2(POOL_FLAG_PAGED, NewLength, SEP_TOKEN_DYNAMIC_PART_TAG);
2407 |
2408 | if (NewDynamic == NULL)
2409 | {
2410 | return STATUS_INSUFFICIENT_RESOURCES;
2411 | }
2412 |
2413 | DynamicPart = Token->DynamicPart;
2414 |
2415 | RtlCopyMemory(NewDynamic, DynamicPart, CurrentSize);
2416 |
2417 | Token->DynamicAvailable += NewLength - CurrentSize;
2418 | Token->DynamicPart = NewDynamic;
2419 |
2420 | if (Token->DefaultDacl)
2421 | {
2422 | Token->DefaultDacl = (PACL)((PUCHAR)NewDynamic + ((PUCHAR)Token->DefaultDacl - (PUCHAR)DynamicPart));
2423 | }
2424 |
2425 | Token->PrimaryGroup = (PSID)((PUCHAR)NewDynamic + ((PUCHAR)Token->PrimaryGroup - (PUCHAR)DynamicPart));
2426 |
2427 | ExFreePool(DynamicPart);
2428 |
2429 | return STATUS_SUCCESS;
2430 |
2431 | }
2432 |
2433 | VOID SepFreeDefaultDacl(PTOKEN Token)
2434 | {
2435 | if (Token->DefaultDacl)
2436 | {
2437 | Token->DynamicAvailable += Token->DefaultDacl->AclSize;
2438 | Token->DefaultDacl = NULL;
2439 | }
2440 |
2441 | if (Token->DynamicPart != (PULONG)Token->PrimaryGroup)
2442 | {
2443 | RtlMoveMemory((PVOID)(Token->DynamicPart), (PVOID)(Token->PrimaryGroup), SeLengthSid(Token->PrimaryGroup));
2444 |
2445 | Token->PrimaryGroup = (PSID)Token->DynamicPart;
2446 | }
2447 |
2448 | return;
2449 | }
2450 |
2451 | VOID SepAppendDefaultDacl(PTOKEN Token, PACL NewAcl)
2452 | {
2453 | RtlCopyMemory((PVOID)((ULONG_PTR)(Token->DynamicPart) + SeLengthSid(Token->PrimaryGroup)), (PVOID)NewAcl, NewAcl->AclSize);
2454 |
2455 | Token->DynamicAvailable -= NewAcl->AclSize;
2456 | Token->DefaultDacl = (PACL)(PVOID)((ULONG_PTR)(Token->DynamicPart) + SeLengthSid(Token->PrimaryGroup));
2457 | return;
2458 | }
2459 |
2460 | NTSTATUS SepAppendAceToTokenDefaultDacl(PTOKEN Token, PISID PackageSid)
2461 | {
2462 | PACL DefaultAcl;
2463 | NTSTATUS Status;
2464 | ULONG LengthRequired;
2465 | PACL NewAcl = NULL;
2466 | ACL_REVISION_INFORMATION AclRevision = { 0 };
2467 | PVOID Ace = NULL;
2468 | ACL_SIZE_INFORMATION AclSize = { 0 , 0 , 0 };
2469 |
2470 | DefaultAcl = Token->DefaultDacl;
2471 |
2472 | if (DefaultAcl == NULL || RtlFindAceBySid(DefaultAcl, PackageSid, NULL))
2473 | {
2474 | return STATUS_SUCCESS;
2475 | }
2476 | else
2477 | {
2478 | Status = RtlQueryInformationAcl(DefaultAcl, &AclRevision, sizeof(ACL_REVISION_INFORMATION), AclRevisionInformation);
2479 |
2480 | if (!NT_SUCCESS(Status))
2481 | {
2482 | return Status;
2483 | }
2484 |
2485 | Status = RtlQueryInformationAcl(DefaultAcl, &AclSize, sizeof(ACL_SIZE_INFORMATION), AclSizeInformation);
2486 |
2487 | if (!NT_SUCCESS(Status))
2488 | {
2489 | return Status;
2490 | }
2491 |
2492 |
2493 | LengthRequired = LongAlignSize(DefaultAcl->AclSize + SeLengthSid(PackageSid) + sizeof(ACL));
2494 |
2495 |
2496 | NewAcl = (PACL)ExAllocatePool2(POOL_FLAG_PAGED , LengthRequired , SEP_ACL_TAG);
2497 |
2498 | if (NewAcl == NULL)
2499 | {
2500 | return STATUS_INSUFFICIENT_RESOURCES;
2501 | }
2502 |
2503 | Status = RtlCreateAcl(NewAcl, LengthRequired, AclRevision.AclRevision);
2504 |
2505 | if (!NT_SUCCESS(Status))
2506 | {
2507 | ExFreePool(NewAcl);
2508 | return Status;
2509 | }
2510 |
2511 | Status = RtlGetAce(DefaultAcl, 0, &Ace);
2512 |
2513 | if (!NT_SUCCESS(Status))
2514 | {
2515 | ExFreePool(NewAcl);
2516 | return Status;
2517 | }
2518 |
2519 | Status = RtlAddAce(NewAcl, AclRevision.AclRevision, 0, Ace, AclSize.AclBytesInUse - sizeof(ACL));
2520 |
2521 | if (!NT_SUCCESS(Status))
2522 | {
2523 | ExFreePool(NewAcl);
2524 | return Status;
2525 | }
2526 |
2527 | Status = RtlAddAccessAllowedAce(NewAcl, AclRevision.AclRevision, GENERIC_ALL, PackageSid);
2528 |
2529 |
2530 | if (!NT_SUCCESS(Status))
2531 | {
2532 | ExFreePool(NewAcl);
2533 | return Status;
2534 | }
2535 |
2536 | Status = SepExpandDynamic(Token, LongAlignSize(LengthRequired + SeLengthSid(Token->PrimaryGroup)));
2537 |
2538 | if (!NT_SUCCESS(Status))
2539 | {
2540 | ExFreePool(NewAcl);
2541 | return Status;
2542 | }
2543 |
2544 | SepFreeDefaultDacl(Token);
2545 | SepAppendDefaultDacl(Token , NewAcl);
2546 |
2547 |
2548 | ExFreePool(NewAcl);
2549 | }
2550 |
2551 | return Status;
2552 | }
2553 |
2554 | BOOLEAN SepCapabilitiesHasAppSiloBaseSID(ULONG CapabilityCount , SID_AND_ATTRIBUTES* Capabilities)
2555 | {
2556 | ULONG Index;
2557 |
2558 | for (Index = 0; Index < CapabilityCount; Index++)
2559 | {
2560 | if (RtlEqualSid(SeAppSiloSid, Capabilities[Index].Sid))
2561 | {
2562 | return TRUE;
2563 | }
2564 | }
2565 |
2566 | return FALSE;
2567 | }
2568 |
2569 | PSID_IDENTIFIER_AUTHORITY
2570 | _RtlIdentifierAuthoritySid(
2571 | IN PSID Sid
2572 | )
2573 | /*++
2574 |
2575 | Routine Description:
2576 |
2577 | This function returns the address of an SID's IdentifierAuthority field.
2578 |
2579 | Arguments:
2580 |
2581 | Sid - Pointer to the SID data structure.
2582 |
2583 | Return Value:
2584 |
2585 |
2586 | --*/
2587 | {
2588 | PISID ISid;
2589 |
2590 | //
2591 | // Typecast to the opaque SID
2592 | //
2593 |
2594 | ISid = (PISID)Sid;
2595 |
2596 | return &(ISid->IdentifierAuthority);
2597 |
2598 | }
2599 |
2600 | BOOLEAN SepIsAppSiloCapability(PSID CapSID)
2601 | {
2602 | PSID_IDENTIFIER_AUTHORITY CapIDAUTH, AppSiloCapIDAUTH;
2603 | ULONG Index ;
2604 |
2605 | if (((PISID)CapSID)->Revision != ((PISID)SeAppSiloSid)->Revision ||
2606 | ((PISID)CapSID)->SubAuthorityCount <= ((PISID)SeAppSiloSid)->SubAuthorityCount)
2607 | {
2608 | return FALSE;
2609 | }
2610 | AppSiloCapIDAUTH = _RtlIdentifierAuthoritySid(SeAppSiloSid);
2611 | CapIDAUTH = _RtlIdentifierAuthoritySid(CapSID);
2612 |
2613 | if (memcmp(&CapIDAUTH, &AppSiloCapIDAUTH, sizeof(SID_IDENTIFIER_AUTHORITY)) == 0)
2614 | {
2615 | Index = 0;
2616 |
2617 | while (Index < ((PISID)SeAppSiloSid)->SubAuthorityCount)
2618 | {
2619 | if (((PISID)CapSID)->SubAuthority[Index] != ((PISID)SeAppSiloSid)->SubAuthority[Index])
2620 | {
2621 | return FALSE;
2622 | }
2623 | Index++;
2624 | }
2625 | }
2626 | return TRUE;
2627 | }
2628 |
2629 | //we just import this function cause ObsSecurityDescriotCahce involved
2630 | VOID NTSYSAPI
2631 | ObDereferenceSecurityDescriptor(
2632 | __in PSECURITY_DESCRIPTOR SecurityDescriptor,
2633 | __in ULONG Count
2634 | );
2635 |
2636 | BOOLEAN NTSYSAPI RtlValidAcl(IN PACL Acl);
2637 | BOOLEAN NTSYSAPI RtlFirstFreeAce(IN PACL Acl, OUT PVOID* FirstFree);
2638 |
2639 | NTSTATUS
2640 | RtlpAddKnownAce(
2641 | IN OUT PACL Acl,
2642 | IN ULONG AceRevision,
2643 | IN ULONG AceFlags,
2644 | IN ACCESS_MASK AccessMask,
2645 | IN PSID Sid,
2646 | IN UCHAR NewType
2647 | )
2648 |
2649 | /*
2650 |
2651 | Routine Description:
2652 |
2653 | This routine adds KNOWN_ACE to an ACL. This is
2654 | expected to be a common form of ACL modification.
2655 |
2656 | A very bland ACE header is placed in the ACE. It provides no
2657 | inheritance and no ACE flags. The type is specified by the caller.
2658 |
2659 | Arguments:
2660 |
2661 | Acl - Supplies the Acl being modified
2662 |
2663 | AceRevision - Supplies the Acl/Ace revision of the ACE being added
2664 |
2665 | AceFlags - Supplies the inherit flags for the ACE.
2666 |
2667 | AccessMask - The mask of accesses to be denied to the specified SID.
2668 |
2669 | Sid - Pointer to the SID being denied access.
2670 |
2671 | NewType - Type of ACE to be added.
2672 |
2673 | Return Value:
2674 |
2675 | STATUS_SUCCESS - The ACE was successfully added.
2676 |
2677 | STATUS_INVALID_ACL - The specified ACL is not properly formed.
2678 |
2679 | STATUS_REVISION_MISMATCH - The specified revision is not known
2680 | or is incompatible with that of the ACL.
2681 |
2682 | STATUS_ALLOTTED_SPACE_EXCEEDED - The new ACE does not fit into the
2683 | ACL. A larger ACL buffer is required.
2684 |
2685 | STATUS_INVALID_SID - The provided SID is not a structurally valid
2686 | SID.
2687 |
2688 | STATUS_INVALID_PARAMETER - The AceFlags parameter was invalid.
2689 |
2690 | */
2691 |
2692 | {
2693 | PVOID FirstFree;
2694 | USHORT AceSize;
2695 | PKNOWN_ACE GrantAce;
2696 | UCHAR NewRevision;
2697 | ULONG TestedAceFlags;
2698 |
2699 |
2700 | // Validate the structure of the SID
2701 |
2702 |
2703 | if (!RtlValidSid(Sid))
2704 | {
2705 | return STATUS_INVALID_SID;
2706 | }
2707 |
2708 |
2709 | // Check the ACL & ACE revision levels
2710 |
2711 |
2712 | if (Acl->AclRevision > ACL_REVISION4 || AceRevision > ACL_REVISION4)
2713 | {
2714 |
2715 | return STATUS_REVISION_MISMATCH;
2716 | }
2717 |
2718 |
2719 | // Calculate the new revision of the ACL. The new revision is the maximum
2720 | // of the old revision and and new ACE's revision. This is possible because
2721 | // the format of previously defined ACEs did not change across revisions.
2722 |
2723 |
2724 | NewRevision = Acl->AclRevision > (UCHAR)AceRevision ? Acl->AclRevision : (UCHAR)AceRevision;
2725 |
2726 |
2727 | // Validate the AceFlags.
2728 |
2729 |
2730 | TestedAceFlags = AceFlags & ~VALID_INHERIT_FLAGS;
2731 |
2732 | if (TestedAceFlags != 0)
2733 | {
2734 |
2735 | if (NewType == SYSTEM_AUDIT_ACE_TYPE)
2736 | {
2737 | TestedAceFlags &= ~(SUCCESSFUL_ACCESS_ACE_FLAG | FAILED_ACCESS_ACE_FLAG);
2738 | }
2739 | else if (NewType == ACCESS_ALLOWED_ACE_TYPE)
2740 | {
2741 | TestedAceFlags &= ~(CRITICAL_ACE_FLAG);
2742 | }
2743 |
2744 | if (TestedAceFlags != 0)
2745 | {
2746 | return STATUS_INVALID_PARAMETER;
2747 | }
2748 | }
2749 |
2750 |
2751 | // Locate the first free ace and check to see that the Acl is
2752 | // well formed.
2753 |
2754 |
2755 | if (!RtlValidAcl(Acl))
2756 | {
2757 | return STATUS_INVALID_ACL;
2758 | }
2759 |
2760 | if (!RtlFirstFreeAce(Acl, &FirstFree))
2761 | {
2762 |
2763 | return STATUS_INVALID_ACL;
2764 | }
2765 |
2766 |
2767 | // Check to see if there is enough room in the Acl to store the new
2768 | // ACE
2769 |
2770 |
2771 | AceSize = (USHORT)(sizeof(ACE_HEADER) + sizeof(ACCESS_MASK) + SeLengthSid(Sid));
2772 |
2773 | if (FirstFree == NULL || ((PUCHAR)FirstFree + AceSize > ((PUCHAR)Acl + Acl->AclSize)))
2774 | {
2775 | return STATUS_ALLOTTED_SPACE_EXCEEDED;
2776 | }
2777 |
2778 |
2779 | // Add the ACE to the end of the ACL
2780 |
2781 |
2782 | GrantAce = (PKNOWN_ACE)FirstFree;
2783 | GrantAce->Header.AceFlags = (UCHAR)AceFlags;
2784 | GrantAce->Header.AceType = NewType;
2785 | GrantAce->Header.AceSize = AceSize;
2786 | GrantAce->Mask = AccessMask;
2787 |
2788 | RtlCopySid(SeLengthSid(Sid), (PSID)(&GrantAce->SidStart), Sid);
2789 |
2790 |
2791 | // Increment the number of ACEs by 1.
2792 |
2793 |
2794 | Acl->AceCount += 1;
2795 |
2796 |
2797 | // Adjust the Acl revision, if necessary
2798 |
2799 |
2800 | Acl->AclRevision = NewRevision;
2801 |
2802 |
2803 | // And return to our caller
2804 |
2805 |
2806 | return STATUS_SUCCESS;
2807 | }
2808 | NTSTATUS NTSYSAPI RtlAddAce(PACL Acl, ULONG AceRevision, ULONG StartingAceIndex, PVOID AceList, ULONG AceListLength);
2809 | NTSTATUS NTSYSAPI ObSetSecurityObjectByPointer(__in PVOID Object, __in SECURITY_INFORMATION SecurityInformation, __in PSECURITY_DESCRIPTOR SecurityDescriptor);
2810 |
2811 | NTSTATUS SepAppendAceToTokenObjectAcl(PTOKEN Token , ACCESS_MASK Access , PSID Sid)
2812 | {
2813 | PSECURITY_DESCRIPTOR SecurityDescriptor = NULL ;
2814 | BOOLEAN MemoryAllocated = FALSE;
2815 | NTSTATUS Status = STATUS_SUCCESS;
2816 | PACL TokenDacl;
2817 | ULONG AclSize;
2818 | SECURITY_DESCRIPTOR NewSecurityDescriptor = { 0 };
2819 | ACL_SIZE_INFORMATION AclSizeInfo;
2820 | ACL_REVISION_INFORMATION RevisionInfo;
2821 | PACL NewDacl = NULL;
2822 | PVOID Ace = NULL;
2823 |
2824 | Status = ObGetObjectSecurity(Token, &SecurityDescriptor, &MemoryAllocated);
2825 |
2826 | if (!NT_SUCCESS(Status))
2827 | {
2828 | goto Exit;
2829 | }
2830 |
2831 | if (SecurityDescriptor == NULL)
2832 | {
2833 | return Status;
2834 | }
2835 |
2836 | TokenDacl = RtlpDaclAddrSecurityDescriptor((PISECURITY_DESCRIPTOR)SecurityDescriptor);
2837 |
2838 | if (TokenDacl == NULL)
2839 | {
2840 | goto Exit;
2841 | }
2842 |
2843 | //Make sure no such ACE exists in the original token dacl
2844 |
2845 | if (RtlFindAceBySid(TokenDacl, Sid, NULL))
2846 | {
2847 | goto Exit;
2848 | }
2849 |
2850 | Status = RtlQueryInformationAcl(TokenDacl, &AclSizeInfo, sizeof(ACL_SIZE_INFORMATION), AclSizeInformation);
2851 |
2852 | if (!NT_SUCCESS(Status))
2853 | {
2854 | goto Exit;
2855 | }
2856 |
2857 | Status = RtlQueryInformationAcl(TokenDacl, &RevisionInfo, sizeof(ACL_REVISION_INFORMATION), AclRevisionInformation);
2858 |
2859 | if (!NT_SUCCESS(Status))
2860 | {
2861 | goto Exit;
2862 | }
2863 |
2864 | AclSize = LongAlignSize(AclSizeInfo.AclBytesInUse + RtlLengthSid(Sid) + FIELD_OFFSET(ACCESS_ALLOWED_ACE, SidStart));
2865 |
2866 | NewDacl = (PACL) ExAllocatePool2(POOL_FLAG_PAGED, AclSize, SEP_ACL_TAG);
2867 |
2868 | if (NewDacl == NULL)
2869 | {
2870 | Status = STATUS_INSUFFICIENT_RESOURCES;
2871 | goto Exit;
2872 | }
2873 |
2874 | Status = RtlCreateAcl(NewDacl, AclSize, RevisionInfo.AclRevision);
2875 |
2876 | if (!NT_SUCCESS(Status))
2877 | {
2878 | goto Exit;
2879 | }
2880 |
2881 | Status = RtlGetAce(TokenDacl, 0, &Ace);
2882 |
2883 | if (!NT_SUCCESS(Status))
2884 | {
2885 | goto Exit;
2886 | }
2887 |
2888 | Status = RtlAddAce(NewDacl, RevisionInfo.AclRevision, 0, Ace, AclSizeInfo.AclBytesInUse - sizeof(ACL));
2889 |
2890 | if (!NT_SUCCESS(Status))
2891 | {
2892 | goto Exit;
2893 | }
2894 |
2895 | Status = RtlpAddKnownAce(NewDacl, RevisionInfo.AclRevision, 0, Access, Sid, ACCESS_ALLOWED_ACE_TYPE);
2896 |
2897 | if (!NT_SUCCESS(Status))
2898 | {
2899 | goto Exit;
2900 | }
2901 |
2902 | Status = RtlCreateSecurityDescriptor(&NewSecurityDescriptor, SECURITY_DESCRIPTOR_REVISION);
2903 |
2904 | if (!NT_SUCCESS(Status))
2905 | {
2906 | goto Exit;
2907 | }
2908 |
2909 | Status = RtlSetDaclSecurityDescriptor(&NewSecurityDescriptor, TRUE, TokenDacl, FALSE);
2910 |
2911 | if (!NT_SUCCESS(Status))
2912 | {
2913 | goto Exit;
2914 | }
2915 |
2916 | Status = ObSetSecurityObjectByPointer(Token, DACL_SECURITY_INFORMATION, &NewSecurityDescriptor);
2917 |
2918 | Exit:
2919 | if (NewDacl)
2920 | {
2921 | ExFreePool(NewDacl);
2922 | }
2923 |
2924 | if (SecurityDescriptor)
2925 | {
2926 | ObReleaseObjectSecurity(SecurityDescriptor, MemoryAllocated);
2927 | }
2928 |
2929 | return Status;
2930 | }
2931 | PVOID
2932 | NTSYSAPI
2933 | RtlFindAceByType(
2934 | _In_ PACL Acl,
2935 | _In_ UCHAR AceType,
2936 | _Out_opt_ PULONG Index
2937 | );
2938 | NTSYSAPI
2939 | NTSTATUS
2940 |
2941 | RtlAddProcessTrustLabelAce(
2942 | _Inout_ PACL Acl,
2943 | _In_ ULONG AceRevision,
2944 | _In_ ULONG AceFlags,
2945 | _In_ PSID ProcessTrustLabelSid,
2946 | _In_ UCHAR AceType, // SYSTEM_PROCESS_TRUST_LABEL_ACE_TYPE
2947 | _In_ ACCESS_MASK AccessMask
2948 | );
2949 |
2950 |
2951 | NTSYSAPI
2952 | NTSTATUS
2953 |
2954 | RtlSetSaclSecurityDescriptor(
2955 | _Inout_ PSECURITY_DESCRIPTOR SecurityDescriptor,
2956 | _In_ BOOLEAN SaclPresent,
2957 | _In_opt_ PACL Sacl,
2958 | _In_ BOOLEAN SaclDefaulted
2959 | );
2960 |
2961 | NTSTATUS SepSetProcessTrustLabelAceForToken(PTOKEN Token)
2962 | {
2963 | SECURITY_DESCRIPTOR Sd = { 0 };
2964 | PSID TrustLevelSid;
2965 | NTSTATUS Status;
2966 | PISECURITY_DESCRIPTOR OldSd = NULL;
2967 | BOOLEAN MemoryAllocated = FALSE;
2968 | PACL TokenSacl;
2969 | PSYSTEM_PROCESS_TRUST_LABEL_ACE TrustLabelAce;
2970 | ULONG AceIndex;
2971 | ACL_REVISION_INFORMATION RevisionInfo;
2972 | ACL_SIZE_INFORMATION AclSizeInfo;
2973 | PVOID Ace = NULL ;
2974 | ULONG AclSize;
2975 | PACL NewSacl = NULL;
2976 |
2977 | if (Token == NULL)
2978 | {
2979 | return STATUS_INVALID_PARAMETER;
2980 | }
2981 |
2982 | RevisionInfo.AclRevision = ACL_REVISION2;
2983 | AclSizeInfo.AclBytesInUse = sizeof(ACL);
2984 |
2985 | TrustLevelSid = Token->TrustLevelSid;
2986 |
2987 | Status = ObGetObjectSecurity(Token, &OldSd, &MemoryAllocated);
2988 |
2989 | if (!NT_SUCCESS(Status))
2990 | {
2991 | goto Exit;
2992 | }
2993 |
2994 | if (OldSd == NULL)
2995 | {
2996 | return Status;
2997 | }
2998 |
2999 | TokenSacl = RtlpSaclAddrSecurityDescriptor(OldSd);
3000 |
3001 | if (TokenSacl)
3002 | {
3003 | TrustLabelAce = RtlFindAceByType(TokenSacl, SYSTEM_PROCESS_TRUST_LABEL_ACE_TYPE, &AceIndex);
3004 |
3005 | if (TrustLevelSid == NULL)
3006 | {
3007 | if (TrustLabelAce == NULL)
3008 | {
3009 | goto Exit;
3010 | }
3011 | }
3012 | else if (TrustLabelAce && RtlEqualSid(&(TrustLabelAce->SidStart), TrustLevelSid))
3013 | {
3014 | TrustLabelAce->Mask &= (READ_CONTROL | TOKEN_QUERY_SOURCE | TOKEN_QUERY | TOKEN_IMPERSONATE | TOKEN_DUPLICATE);
3015 | goto Exit;
3016 | }
3017 |
3018 | Status = RtlQueryInformationAcl(TokenSacl, &AclSizeInfo, sizeof(ACL_SIZE_INFORMATION), AclSizeInformation);
3019 |
3020 | if (!NT_SUCCESS(Status))
3021 | {
3022 | goto Exit;
3023 | }
3024 |
3025 | Status = RtlQueryInformationAcl(TokenSacl, &RevisionInfo, sizeof(ACL_REVISION_INFORMATION), AclRevisionInformation);
3026 |
3027 | if (!NT_SUCCESS(Status))
3028 | {
3029 | goto Exit;
3030 | }
3031 |
3032 | Status = RtlGetAce(TokenSacl, 0, &Ace);
3033 |
3034 | if (!NT_SUCCESS(Status))
3035 | {
3036 | goto Exit;
3037 | }
3038 | }
3039 |
3040 | AclSize = AclSizeInfo.AclBytesInUse + SeLengthSid(TrustLevelSid) + FIELD_OFFSET(SYSTEM_PROCESS_TRUST_LABEL_ACE, SidStart);
3041 |
3042 |
3043 | NewSacl = ExAllocatePool2(POOL_FLAG_PAGED, AclSize, SEP_ACL_TAG);
3044 |
3045 | if (NewSacl == NULL)
3046 | {
3047 | Status = STATUS_INSUFFICIENT_RESOURCES;
3048 | goto Exit;
3049 | }
3050 |
3051 | Status = RtlCreateAcl(NewSacl, AclSize, RevisionInfo.AclRevision);
3052 |
3053 | if (!NT_SUCCESS(Status))
3054 | {
3055 | goto Exit;
3056 | }
3057 |
3058 | if (Ace != NULL)
3059 | {
3060 | Status = RtlAddAce(NewSacl, RevisionInfo.AclRevision, 0, Ace, AclSizeInfo.AclBytesInUse - sizeof(ACL));
3061 |
3062 | if (!NT_SUCCESS(Status))
3063 | {
3064 | goto Exit;
3065 | }
3066 | }
3067 |
3068 | Status = RtlAddProcessTrustLabelAce(NewSacl,
3069 | ACL_REVISION2,
3070 | 0,
3071 | TrustLevelSid,
3072 | SYSTEM_PROCESS_TRUST_LABEL_ACE_TYPE,
3073 | (READ_CONTROL | TOKEN_QUERY_SOURCE | TOKEN_QUERY | TOKEN_IMPERSONATE | TOKEN_DUPLICATE));
3074 |
3075 | if (!NT_SUCCESS(Status))
3076 | {
3077 | goto Exit;
3078 | }
3079 |
3080 | Status = RtlCreateSecurityDescriptor(&Sd, SECURITY_DESCRIPTOR_REVISION);
3081 |
3082 | if (!NT_SUCCESS(Status))
3083 | {
3084 | goto Exit;
3085 | }
3086 |
3087 | Sd.Revision = SECURITY_DESCRIPTOR_REVISION;
3088 |
3089 | Status = RtlSetSaclSecurityDescriptor(&Sd, TRUE, NewSacl, FALSE);
3090 |
3091 | if (!NT_SUCCESS(Status))
3092 | {
3093 | goto Exit;
3094 | }
3095 |
3096 | RtlpPropagateControlBits(&Sd, OldSd, (SE_SACL_PROTECTED | SE_SACL_AUTO_INHERITED | SE_SACL_PRESENT | SE_SACL_DEFAULTED));
3097 |
3098 | Status = ObSetSecurityObjectByPointer(Token,
3099 | (ACCESS_FILTER_SECURITY_INFORMATION | PROCESS_TRUST_LABEL_SECURITY_INFORMATION | SCOPE_SECURITY_INFORMATION | ATTRIBUTE_SECURITY_INFORMATION | LABEL_SECURITY_INFORMATION | SACL_SECURITY_INFORMATION),
3100 | &Sd);
3101 |
3102 |
3103 | Exit:
3104 | if (NewSacl)
3105 | {
3106 | ExFreePool(NewSacl);
3107 | }
3108 |
3109 | if (OldSd)
3110 | {
3111 | ObReleaseObjectSecurity(OldSd, MemoryAllocated);
3112 | }
3113 |
3114 | return Status;
3115 | }
3116 |
3117 | NTSTATUS SepFinalizeTokenAcls(PTOKEN Token)
3118 | {
3119 | NTSTATUS Status;
3120 |
3121 | Status = SepAppendAceToTokenObjectAcl(Token, TOKEN_QUERY, SeAliasAdminsSid);
3122 |
3123 | if (NT_SUCCESS(Status))
3124 | {
3125 | return SepSetProcessTrustLabelAceForToken(Token);
3126 | }
3127 | return Status;
3128 | }
3129 |
3130 | NTSTATUS NTAPI NtCreateLowBoxToken(
3131 | _Out_ PHANDLE TokenHandle,
3132 | _In_ HANDLE ExistingTokenHandle,
3133 | _In_ ACCESS_MASK DesiredAccess,
3134 | _In_ POBJECT_ATTRIBUTES ObjectAttributes,
3135 | _In_ PSID PackageSid,
3136 | _In_ ULONG CapabilityCount,
3137 | _In_ PSID_AND_ATTRIBUTES Capabilities,
3138 | _In_ ULONG HandleCount,
3139 | _In_ HANDLE* Handles)
3140 | {
3141 | KPROCESSOR_MODE Mode;
3142 | PTOKEN ExistingToken;
3143 | OBJECT_HANDLE_INFORMATION ohi = { 0 , 0 };
3144 | NTSTATUS Status;
3145 | PISID CapturedPackageSid = NULL;
3146 | PSID_AND_ATTRIBUTES CapturedCapabilities = NULL;
3147 | ULONG CapturedCapabilitiesSize = 0;
3148 | BOOLEAN bDuplicatedToken = FALSE;
3149 | BOOLEAN bTokenLocked = FALSE;
3150 | PTOKEN DuplicatedToken = NULL;
3151 | HANDLE NewTokenHandle = 0;
3152 | HANDLE* CapturedHandles = NULL;
3153 | ULONG Index;
3154 | ULONG SidIndex;
3155 | BOOLEAN bLegit = FALSE;
3156 | TOKEN_MANDATORY_POLICY MandtoryPolicy = { TOKEN_MANDATORY_POLICY_NO_WRITE_UP };
3157 | PSID_AND_ATTRIBUTES TokenIntegrity;
3158 | PISID IntegritySid;
3159 | SEP_CACHED_HANDLES_ENTRY_DESCRIPTOR chEntryDescriptor = { 0 , 0 };
3160 |
3161 | APPCONTAINER_SID_TYPE AppContainerSidType;
3162 | ACCESS_MASK GrantedAccess;
3163 |
3164 | Mode = ExGetPreviousMode();
3165 |
3166 |
3167 | if (Mode)
3168 | {
3169 | __try
3170 | {
3171 | ProbeForWriteHandle(TokenHandle);
3172 |
3173 | ProbeForRead(Handles, sizeof(HANDLE) * HandleCount, sizeof(HANDLE));
3174 | }
3175 | __except (EXCEPTION_EXECUTE_HANDLER)
3176 | {
3177 | return GetExceptionCode();
3178 | }
3179 | }
3180 |
3181 | if (PackageSid == NULL)
3182 | {
3183 | return STATUS_INVALID_PARAMETER;
3184 | }
3185 |
3186 | //ensure HandleCount and Handles pointer are consistent
3187 | //*(zero count requires NULL pointer and vice versa)
3188 |
3189 | if (HandleCount == 0)
3190 | {
3191 | if (Handles != NULL)
3192 | {
3193 | return STATUS_INVALID_PARAMETER_MIX;
3194 | }
3195 | }
3196 | else
3197 | {
3198 | if (Handles == NULL)
3199 | {
3200 | return STATUS_INVALID_PARAMETER_MIX;
3201 | }
3202 | }
3203 |
3204 | ExistingToken = NULL;
3205 |
3206 | Status = ObReferenceObjectByHandle(ExistingTokenHandle, TOKEN_DUPLICATE, *SeTokenObjectType, Mode, &ExistingToken, &ohi);
3207 |
3208 | if (!NT_SUCCESS(Status))
3209 | {
3210 | return Status;
3211 | }
3212 |
3213 | Status = SeCaptureSid(PackageSid, Mode, NULL, 0, POOL_ZERO_ALLOCATION | PagedPool, TRUE, &CapturedPackageSid);
3214 |
3215 | if (!NT_SUCCESS(Status))
3216 | {
3217 | return Status;
3218 | }
3219 |
3220 |
3221 | // Verify caller's privilege for creating LowBox token - must be non-LowBox process or parent AppContainer
3222 |
3223 | Status = SepCheckCreateLowBox(CapturedPackageSid);
3224 |
3225 | if (!NT_SUCCESS(Status))
3226 | {
3227 | return Status;
3228 | }
3229 |
3230 | // Impersonation token must be at SecurityImpersonation level or higher
3231 |
3232 | if (ExistingToken->TokenType != TokenPrimary && ExistingToken->ImpersonationLevel < SecurityImpersonation)
3233 | {
3234 | ObDereferenceObject(ExistingToken);
3235 | return STATUS_BAD_IMPERSONATION_LEVEL;
3236 | }
3237 |
3238 | GrantedAccess = ohi.GrantedAccess;
3239 |
3240 | if (DesiredAccess)
3241 | {
3242 | GrantedAccess = DesiredAccess;
3243 | }
3244 |
3245 |
3246 | // Capture capabilities and handles
3247 |
3248 | if (Capabilities)
3249 | {
3250 | Status = SeCaptureSidAndAttributesArray(Capabilities, CapabilityCount, Mode, NULL, 0, POOL_ZERO_ALLOCATION | PagedPool, TRUE, &CapturedCapabilities, &CapturedCapabilitiesSize);
3251 | }
3252 |
3253 | if (!NT_SUCCESS(Status))
3254 | {
3255 | goto Exit;
3256 | }
3257 |
3258 |
3259 | Status = SepCaptureHandles(HandleCount, Handles, &CapturedHandles);
3260 |
3261 | if (!NT_SUCCESS(Status))
3262 | {
3263 | goto Exit;
3264 | }
3265 |
3266 | //check captured packaged sid
3267 |
3268 | if (RtlIsPackageSid(CapturedPackageSid) == FALSE)
3269 | {
3270 | Status = STATUS_INVALID_PARAMETER;
3271 | goto Exit;
3272 | }
3273 |
3274 | if (CapturedPackageSid->SubAuthorityCount != SECURITY_APP_PACKAGE_RID_COUNT && CapturedPackageSid->SubAuthorityCount != SECURITY_CHILD_PACKAGE_RID_COUNT)
3275 | {
3276 | Status = STATUS_INVALID_PACKAGE_SID_LENGTH;
3277 | goto Exit;
3278 | }
3279 |
3280 |
3281 | //Check for duplicated SID
3282 |
3283 | for (Index = 0; Index < CapabilityCount; Index++)
3284 | {
3285 | if (RtlIsCapabilitySid(CapturedCapabilities[Index].Sid) == FALSE)
3286 | {
3287 | Status = STATUS_INVALID_PARAMETER;
3288 | goto Exit;
3289 | }
3290 |
3291 |
3292 | for (SidIndex = 0; SidIndex < Index; SidIndex++)
3293 | {
3294 | if (RtlEqualSid(CapturedCapabilities[Index].Sid, CapturedCapabilities[SidIndex].Sid) == TRUE)
3295 | {
3296 | Status = STATUS_INVALID_PARAMETER;
3297 | goto Exit;
3298 | }
3299 | }
3300 | }
3301 |
3302 | //AppSilo checking added Win11 24H2
3303 | if (!SepCapabilitiesHasAppSiloBaseSID(CapabilityCount, CapturedCapabilities))
3304 | {
3305 | for (Index = 0; Index < CapabilityCount; Index++)
3306 | {
3307 | if (SepIsAppSiloCapability(CapturedCapabilities[Index].Sid))
3308 | {
3309 | Status = STATUS_INVALID_PARAMETER;
3310 | goto Exit;
3311 | }
3312 | }
3313 | }
3314 | //end
3315 |
3316 |
3317 | Status = RtlGetAppContainerSidType(CapturedPackageSid, &AppContainerSidType);
3318 |
3319 | if (!NT_SUCCESS(Status))
3320 | {
3321 | goto Exit;
3322 | }
3323 |
3324 | //Check for child app container sid creation
3325 |
3326 |
3327 | if (AppContainerSidType == ChildAppContainerSidType)
3328 | {
3329 | Status = SepCheckCapabilities(ExistingToken, CapabilityCount, CapturedCapabilities, 0, &bLegit);
3330 |
3331 | if (bLegit == FALSE)
3332 | {
3333 | Status = STATUS_ACCESS_DENIED;
3334 | goto Exit;
3335 | }
3336 | }
3337 |
3338 | if (!NT_SUCCESS(Status))
3339 | {
3340 | goto Exit;
3341 | }
3342 |
3343 | Status = SepDuplicateToken(ExistingToken,
3344 | ObjectAttributes,
3345 | FALSE,
3346 | TokenPrimary,
3347 | SecurityAnonymous,
3348 | Mode,
3349 | FALSE,
3350 | &DuplicatedToken);
3351 |
3352 | if (!NT_SUCCESS(Status))
3353 | {
3354 | goto Exit;
3355 | }
3356 |
3357 | bDuplicatedToken = TRUE;
3358 |
3359 | Status = SeSetMandatoryPolicyToken(DuplicatedToken, &MandtoryPolicy);
3360 |
3361 | if (!NT_SUCCESS(Status))
3362 | {
3363 | goto Exit;
3364 | }
3365 |
3366 | SepAcquireTokenWriteLock(DuplicatedToken);
3367 |
3368 | bTokenLocked = TRUE;
3369 |
3370 | TokenIntegrity = SepLocateTokenIntegrity(DuplicatedToken);
3371 |
3372 | if (TokenIntegrity == NULL)
3373 | {
3374 | Status = STATUS_INVALID_LABEL;
3375 | goto Exit;
3376 | }
3377 |
3378 | IntegritySid = TokenIntegrity->Sid;
3379 |
3380 | if (*RtlSubAuthorityCountSid(IntegritySid))
3381 | {
3382 | *RtlSubAuthoritySid(IntegritySid, *RtlSubAuthorityCountSid(IntegritySid) - 1) = MANDATORY_LEVEL_TO_MANDATORY_RID(MandatoryLevelLow);
3383 | }
3384 |
3385 | DuplicatedToken->Privileges.Enabled &= ((1 << SE_CHANGE_NOTIFY_PRIVILEGE) | (1 << SE_UNDOCK_PRIVILEGE));
3386 | DuplicatedToken->Privileges.EnabledByDefault &= ((1 << SE_CHANGE_NOTIFY_PRIVILEGE) | (1 <Privileges.Present &= ((1 << SE_CHANGE_NOTIFY_PRIVILEGE) | (1 << SE_UNDOCK_PRIVILEGE));
3388 | DuplicatedToken->TokenFlags &= ~TOKEN_NOT_LOW;
3389 | DuplicatedToken->TokenFlags |= TOKEN_LOWBOX;
3390 |
3391 | Status = SepSetTokenCapabilities(DuplicatedToken, CapturedPackageSid, CapturedCapabilities, CapabilityCount);
3392 |
3393 | if (!NT_SUCCESS(Status))
3394 | {
3395 | goto Exit;
3396 | }
3397 |
3398 | Status = SepSetTokenLowboxNumber(DuplicatedToken, CapturedPackageSid);
3399 |
3400 | if (!NT_SUCCESS(Status))
3401 | {
3402 | goto Exit;
3403 | }
3404 |
3405 | chEntryDescriptor.u1.PackageSid = CapturedPackageSid;
3406 |
3407 | Status = SepSetTokenCachedHandles(DuplicatedToken, &chEntryDescriptor, HandleCount, CapturedHandles);
3408 |
3409 | if (!NT_SUCCESS(Status))
3410 | {
3411 | goto Exit;
3412 | }
3413 |
3414 | Status = SepSetTokenPackage(DuplicatedToken, CapturedPackageSid);
3415 |
3416 | if (!NT_SUCCESS(Status))
3417 | {
3418 | goto Exit;
3419 | }
3420 |
3421 | Status = SepAppendAceToTokenDefaultDacl(DuplicatedToken, CapturedPackageSid);
3422 |
3423 | if (!NT_SUCCESS(Status))
3424 | {
3425 | goto Exit;
3426 | }
3427 |
3428 | //Added 23H2
3429 |
3430 | if (SepSidInTokenSidHash(&DuplicatedToken->CapabilitiesHash, NULL, SePermissiveLearningModeCapabilitySid, FALSE, FALSE, TRUE))
3431 | {
3432 | // It's impossible to have learning mode capability in the duplicated token
3433 | // without having SepLearningModeTokenCount (in 22H2 and below),
3434 | // but we perform the check anyway
3435 |
3436 | if (KernelSymbols.SepLearningModeTokenCount)
3437 | InterlockedAdd((LONG*)KernelSymbols.SepLearningModeTokenCount , 1);
3438 | DuplicatedToken->TokenFlags |= TOKEN_PERMISSIVE_LEARNING_MODE;
3439 | }
3440 | else
3441 | {
3442 | DuplicatedToken->TokenFlags &= ~TOKEN_PERMISSIVE_LEARNING_MODE;
3443 |
3444 | if (SepSidInTokenSidHash(&DuplicatedToken->CapabilitiesHash, NULL, SeLearningModeLoggingCapabilitySid, FALSE , FALSE , TRUE))
3445 | {
3446 | // It's impossible to have learning mode capability in the duplicated token
3447 | // without having SepLearningModeTokenCount (in 22H2 and below),
3448 | // but we perform the check anyway
3449 |
3450 | if (KernelSymbols.SepLearningModeTokenCount)
3451 | InterlockedAdd((LONG*)KernelSymbols.SepLearningModeTokenCount , 1);
3452 | DuplicatedToken->TokenFlags |= TOKEN_LEARNING_MODE_LOGGING;
3453 | }
3454 | }
3455 | //end
3456 |
3457 | SepReleaseTokenWriteLock(DuplicatedToken, TRUE);
3458 |
3459 | bTokenLocked = FALSE;
3460 |
3461 | //create token handle
3462 |
3463 | Status = ObInsertObject(DuplicatedToken, 0, GrantedAccess, 1, NULL, &NewTokenHandle);
3464 |
3465 | if (!NT_SUCCESS(Status))
3466 | {
3467 | bDuplicatedToken = FALSE;
3468 | goto Exit;
3469 | }
3470 |
3471 | //Added 24H2
3472 |
3473 | Status = SepAppendAceToTokenObjectAcl(DuplicatedToken, TOKEN_ALL_ACCESS, CapturedPackageSid);
3474 |
3475 | if (!NT_SUCCESS(Status))
3476 | {
3477 | goto Exit;
3478 | }
3479 |
3480 | //end
3481 |
3482 | SepFinalizeTokenAcls(DuplicatedToken);
3483 | ObDereferenceObject(DuplicatedToken);
3484 | bDuplicatedToken = FALSE;
3485 |
3486 |
3487 | Exit:
3488 | if (bTokenLocked)
3489 | {
3490 | SepReleaseTokenWriteLock(DuplicatedToken, NT_SUCCESS(Status));
3491 | }
3492 |
3493 | if (!NT_SUCCESS(Status))
3494 | {
3495 | if (bDuplicatedToken)
3496 | {
3497 | ObDereferenceObject(DuplicatedToken);
3498 | }
3499 |
3500 | if (NewTokenHandle)
3501 | {
3502 | ObCloseHandle(NewTokenHandle, Mode);
3503 | }
3504 | }
3505 |
3506 | if (CapturedCapabilities)
3507 | {
3508 | SeReleaseLuidAndAttributesArray(CapturedCapabilities, Mode , TRUE );
3509 | }
3510 |
3511 | if (CapturedPackageSid)
3512 | {
3513 | SeReleaseSid(CapturedPackageSid, Mode, TRUE);
3514 | }
3515 |
3516 | if (ExistingToken)
3517 | {
3518 | ObDereferenceObject(ExistingToken);
3519 | }
3520 |
3521 | if (CapturedHandles)
3522 | {
3523 | ExFreePool(CapturedHandles);
3524 | }
3525 |
3526 | if (NT_SUCCESS(Status))
3527 | {
3528 | __try
3529 | {
3530 | *TokenHandle = NewTokenHandle;
3531 | }
3532 | __except (EXCEPTION_EXECUTE_HANDLER)
3533 | {
3534 | return GetExceptionCode();
3535 | }
3536 |
3537 | }
3538 |
3539 | return Status;
3540 | }
3541 |
3542 |
3543 |
3544 | static SID_IDENTIFIER_AUTHORITY SepPackagesAuthority = { 0 , 0 , 0 , 0 , 0 , 16 };
3545 | static SID_IDENTIFIER_AUTHORITY SepNtAuthority = { 0,0,0,0,0,5 };
3546 | static SID_IDENTIFIER_AUTHORITY SepCreatorSidAuthority = { 0,0,0,0,0,3 };
3547 | PSID SeConstrainedImpersonationCapabilityGroupSid = NULL;
3548 |
3549 | //learning mode names
3550 |
3551 | UNICODE_STRING LeanringModeLoggingCapabilitySidName = RTL_CONSTANT_STRING(L"learningModeLogging");
3552 | UNICODE_STRING PermissiveLearningModeCapabilitySidName = RTL_CONSTANT_STRING(L"permissiveLearningMode");
3553 |
3554 | UNICODE_STRING LpacCapabilitySidNames[] = {
3555 | RTL_CONSTANT_STRING(L"lpacAppExperience"),
3556 | RTL_CONSTANT_STRING(L"lpacCom"),
3557 | RTL_CONSTANT_STRING(L"lpacCryptoServices"),
3558 | RTL_CONSTANT_STRING(L"lpacIdentityServices"),
3559 | RTL_CONSTANT_STRING(L"lpacInstrumentation"),
3560 | RTL_CONSTANT_STRING(L"lpacEnterprisePolicyChangeNotifications"),
3561 | RTL_CONSTANT_STRING(L"lpacMedia"),
3562 | RTL_CONSTANT_STRING(L"lpacPnpNotifications"),
3563 | RTL_CONSTANT_STRING(L"registryRead"),
3564 | RTL_CONSTANT_STRING(L"lpacServicesManagement"),
3565 | RTL_CONSTANT_STRING(L"lpacSessionManagement"),
3566 | RTL_CONSTANT_STRING(L"lpacPrinting"),
3567 | RTL_CONSTANT_STRING(L"lpacWebPlatform"),
3568 | RTL_CONSTANT_STRING(L"lpacPayments"),
3569 | RTL_CONSTANT_STRING(L"lpacClipboard"),
3570 | RTL_CONSTANT_STRING(L"lpacIME"),
3571 | RTL_CONSTANT_STRING(L"lpacPackageManagerOperation"),
3572 | RTL_CONSTANT_STRING(L"lpacDeviceAccess")
3573 | };
3574 |
3575 | NTSTATUS
3576 | NTSYSAPI
3577 | RtlDeriveCapabilitySidsFromName(
3578 | _Inout_ PUNICODE_STRING UnicodeString,
3579 | _Out_ PSID CapabilityGroupSid,
3580 | _Out_ PSID CapabilitySid
3581 | );
3582 |
3583 |
3584 |
3585 | VOID UninitKnownSIDs()
3586 | {
3587 | ULONG i;
3588 |
3589 | if (SeAppSiloSid)
3590 | {
3591 | ExFreePool(SeAppSiloSid);
3592 | SeAppSiloSid = NULL;
3593 | }
3594 | if (SeAliasAdminsSid)
3595 | {
3596 | ExFreePool(SeAliasAdminsSid);
3597 | SeAliasAdminsSid = NULL;
3598 | }
3599 | if (SePrincipalSelfSid)
3600 | {
3601 | ExFreePool(SePrincipalSelfSid);
3602 | SePrincipalSelfSid = NULL;
3603 | }
3604 | if (SeOwnerRightsSid)
3605 | {
3606 | ExFreePool(SeOwnerRightsSid);
3607 | SeOwnerRightsSid = NULL;
3608 | }
3609 | if (SeLearningModeLoggingCapabilitySid)
3610 | {
3611 | ExFreePool(SeLearningModeLoggingCapabilitySid);
3612 | SeLearningModeLoggingCapabilitySid = NULL;
3613 | }
3614 | if (SePermissiveLearningModeCapabilitySid)
3615 | {
3616 | ExFreePool(SePermissiveLearningModeCapabilitySid);
3617 | SePermissiveLearningModeCapabilitySid = NULL;
3618 | }
3619 |
3620 | if (SeConstrainedImpersonationCapabilityGroupSid)
3621 | {
3622 | ExFreePool(SeConstrainedImpersonationCapabilityGroupSid);
3623 | SeConstrainedImpersonationCapabilityGroupSid = NULL;
3624 | }
3625 |
3626 | for (i = 0; i < SE_LPAC_CAPABILITY_COUNT; i++)
3627 | {
3628 | if (*SeLpacCapabilitySids[i])
3629 | {
3630 | ExFreePool(*SeLpacCapabilitySids[i]);
3631 | *(PSID*)SeLpacCapabilitySids[i] = NULL;
3632 | }
3633 | }
3634 |
3635 | return;
3636 |
3637 | }
3638 | NTSTATUS InitKnownSIDs()
3639 | {
3640 | NTSTATUS Status;
3641 | ULONG i;
3642 |
3643 | //SeAppSiloSid
3644 | SeAppSiloSid = ExAllocatePool2(POOL_FLAG_NON_PAGED/* | POOL_FLAG_RAISE_ON_FAILURE*/, RtlLengthRequiredSid(SECURITY_BUILTIN_APP_PACKAGE_RID_COUNT), SEP_SID_TAG);
3645 |
3646 | if (SeAppSiloSid == NULL)
3647 | {
3648 | UninitKnownSIDs();
3649 | return STATUS_NO_MEMORY;
3650 | }
3651 |
3652 | RtlInitializeSid(SeAppSiloSid, &SepPackagesAuthority, SECURITY_BUILTIN_APP_PACKAGE_RID_COUNT);
3653 |
3654 | *RtlSubAuthoritySid(SeAppSiloSid, 0) = SECURITY_CAPABILITY_BASE_RID;
3655 | *RtlSubAuthoritySid(SeAppSiloSid, 1) = SECURITY_CAPABILITY_APP_SILO_RID;
3656 |
3657 | //SeAliasAdminsSid
3658 | SeAliasAdminsSid = ExAllocatePool2(POOL_FLAG_PAGED/* | POOL_FLAG_RAISE_ON_FAILURE*/, RtlLengthRequiredSid(2), SEP_SID_TAG);
3659 |
3660 | if (SeAliasAdminsSid == NULL)
3661 | {
3662 | UninitKnownSIDs();
3663 | return STATUS_NO_MEMORY;
3664 | }
3665 |
3666 | RtlInitializeSid(SeAliasAdminsSid, &SepNtAuthority, 2);
3667 |
3668 | *RtlSubAuthoritySid(SeAliasAdminsSid, 0) = SECURITY_BUILTIN_DOMAIN_RID;
3669 | *RtlSubAuthoritySid(SeAliasAdminsSid, 1) = DOMAIN_ALIAS_RID_ADMINS;
3670 |
3671 | //SePrincipalSelfSid
3672 | SePrincipalSelfSid = ExAllocatePool2(POOL_FLAG_NON_PAGED /* | POOL_FLAG_RAISE_ON_FAILURE*/, RtlLengthRequiredSid(1), SEP_SID_TAG);
3673 |
3674 | if (SePrincipalSelfSid == NULL)
3675 | {
3676 | UninitKnownSIDs();
3677 | return STATUS_NO_MEMORY;
3678 | }
3679 |
3680 | RtlInitializeSid(SePrincipalSelfSid, &SepNtAuthority, 1);
3681 |
3682 | *RtlSubAuthoritySid(SePrincipalSelfSid, 0) = SECURITY_PRINCIPAL_SELF_RID;
3683 |
3684 |
3685 | //SeOwnerRightsSid
3686 | SeOwnerRightsSid = ExAllocatePool2(POOL_FLAG_NON_PAGED/* | POOL_FLAG_RAISE_ON_FAILURE*/, RtlLengthRequiredSid(1), SEP_SID_TAG);
3687 |
3688 | if (SeOwnerRightsSid == NULL)
3689 | {
3690 | UninitKnownSIDs();
3691 | return STATUS_NO_MEMORY;
3692 | }
3693 |
3694 | RtlInitializeSid(SeOwnerRightsSid, &SepCreatorSidAuthority, 1);
3695 |
3696 | *RtlSubAuthoritySid(SeOwnerRightsSid, 0) = SECURITY_CREATOR_OWNER_RIGHTS_RID;
3697 |
3698 | //Initialize the SeConstrainedImpersonationCapabilityGroupSid first
3699 |
3700 | SeConstrainedImpersonationCapabilityGroupSid = ExAllocatePool2(POOL_FLAG_PAGED, RtlLengthRequiredSid(SECURITY_INSTALLER_GROUP_CAPABILITY_RID_COUNT), SEP_SID_TAG);
3701 |
3702 | if (SeConstrainedImpersonationCapabilityGroupSid == NULL)
3703 | {
3704 | UninitKnownSIDs();
3705 | return STATUS_NO_MEMORY;
3706 | }
3707 |
3708 | //we don't need to initialze the group SID
3709 |
3710 | //SeLearningModeLoggingCapabilitySid
3711 | SeLearningModeLoggingCapabilitySid = ExAllocatePool2(POOL_FLAG_PAGED/* | POOL_FLAG_RAISE_ON_FAILURE*/, RtlLengthRequiredSid(10), SEP_SID_TAG);
3712 |
3713 | if (SeLearningModeLoggingCapabilitySid == NULL)
3714 | {
3715 | UninitKnownSIDs();
3716 | return STATUS_NO_MEMORY;
3717 | }
3718 |
3719 | Status = RtlDeriveCapabilitySidsFromName(&LeanringModeLoggingCapabilitySidName, SeConstrainedImpersonationCapabilityGroupSid, SeLearningModeLoggingCapabilitySid);
3720 |
3721 | if (!NT_SUCCESS(Status))
3722 | {
3723 | UninitKnownSIDs();
3724 | return STATUS_NO_MEMORY;
3725 | }
3726 |
3727 | //SePermissiveLearningModeCapabilitySid
3728 | SePermissiveLearningModeCapabilitySid = ExAllocatePool2(POOL_FLAG_PAGED/* | POOL_FLAG_RAISE_ON_FAILURE*/, RtlLengthRequiredSid(10), SEP_SID_TAG);
3729 |
3730 | if (SePermissiveLearningModeCapabilitySid == NULL)
3731 | {
3732 | UninitKnownSIDs();
3733 | return STATUS_NO_MEMORY;
3734 | }
3735 |
3736 | Status = RtlDeriveCapabilitySidsFromName(&PermissiveLearningModeCapabilitySidName, SeConstrainedImpersonationCapabilityGroupSid, SePermissiveLearningModeCapabilitySid);
3737 |
3738 | if (!NT_SUCCESS(Status))
3739 | {
3740 | UninitKnownSIDs();
3741 | return STATUS_NO_MEMORY;
3742 | }
3743 |
3744 | for (i = 0; i < SE_LPAC_CAPABILITY_COUNT; i++)
3745 | {
3746 | *(PSID*)SeLpacCapabilitySids[i] = ExAllocatePool2(POOL_FLAG_PAGED, RtlLengthRequiredSid(10), SEP_SID_TAG);
3747 |
3748 | if (*SeLpacCapabilitySids[i] == NULL)
3749 | {
3750 | UninitKnownSIDs();
3751 | return STATUS_NO_MEMORY;
3752 | }
3753 |
3754 | Status = RtlDeriveCapabilitySidsFromName(&LpacCapabilitySidNames[i], SeConstrainedImpersonationCapabilityGroupSid, *SeLpacCapabilitySids[i]);
3755 |
3756 | if (!NT_SUCCESS(Status))
3757 | {
3758 | UninitKnownSIDs();
3759 | return STATUS_NO_MEMORY;
3760 | }
3761 | }
3762 |
3763 |
3764 | return STATUS_SUCCESS;
3765 | }
3766 | UNICODE_STRING DirectoryName = RTL_CONSTANT_STRING(L"\\");
3767 | UNICODE_STRING SymLinkName = RTL_CONSTANT_STRING(L"\\DosDevices");
3768 | OBJECT_ATTRIBUTES DirectoryOBA = RTL_CONSTANT_OBJECT_ATTRIBUTES(&DirectoryName, OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE);
3769 | OBJECT_ATTRIBUTES SymlinkOBA = RTL_CONSTANT_OBJECT_ATTRIBUTES(&SymLinkName, OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE);
3770 |
3771 | NTSTATUS InitKernelSymbols(PVOID Buffer , ULONG Length)
3772 | {
3773 | NTSTATUS Status;
3774 | HANDLE DirectoryHandle, SymbolicLinkHandle;
3775 | PVOID Object;
3776 |
3777 | if (bSystemSymbolInitialized)
3778 | {
3779 | return STATUS_SUCCESS;
3780 | }
3781 |
3782 | if (Length < sizeof(SYSTEM_SYMBOLS_PARAMS))
3783 | {
3784 | return STATUS_INVALID_PARAMETER;
3785 | }
3786 |
3787 | RtlCopyMemory(&KernelSymbols, Buffer, sizeof(SYSTEM_SYMBOLS_PARAMS));
3788 |
3789 | Status = ZwOpenDirectoryObject(&DirectoryHandle, DIRECTORY_QUERY, &DirectoryOBA);
3790 |
3791 | if (!NT_SUCCESS(Status))
3792 | {
3793 | return Status;
3794 | }
3795 |
3796 | Status = ObReferenceObjectByHandle(DirectoryHandle, 0, NULL, KernelMode, &Object, NULL);
3797 |
3798 | if (!NT_SUCCESS(Status))
3799 | {
3800 | ZwClose(DirectoryHandle);
3801 | return Status;
3802 | }
3803 |
3804 | ObpDirectoryObjectType = ObGetObjectType(Object);
3805 |
3806 | ObDereferenceObject(Object);
3807 |
3808 | ZwClose(DirectoryHandle);
3809 |
3810 | Status = ZwOpenSymbolicLinkObject(&SymbolicLinkHandle, SYMBOLIC_LINK_QUERY, &SymlinkOBA);
3811 |
3812 | if (!NT_SUCCESS(Status))
3813 | {
3814 | return Status;
3815 | }
3816 |
3817 | Status = ObReferenceObjectByHandle(SymbolicLinkHandle, 0, NULL, KernelMode, &Object, NULL);
3818 |
3819 | if (!NT_SUCCESS(Status))
3820 | {
3821 | ZwClose(SymbolicLinkHandle);
3822 | return Status;
3823 | }
3824 |
3825 | ObpSymbolicLinkObjectType = ObGetObjectType(Object);
3826 |
3827 | ObDereferenceObject(Object);
3828 |
3829 | ZwClose(SymbolicLinkHandle);
3830 |
3831 | Status = InitKnownSIDs();
3832 |
3833 | if (!NT_SUCCESS(Status))
3834 | {
3835 | return Status;
3836 | }
3837 |
3838 | bSystemSymbolInitialized = TRUE;
3839 |
3840 | return STATUS_SUCCESS;
3841 | }
3842 |
3843 | NTSTATUS IrpDispatch(PDEVICE_OBJECT DeviceObject, PIRP pIrp)
3844 | {
3845 | PIO_STACK_LOCATION IrpStack;
3846 | NTSTATUS Status = STATUS_SUCCESS;
3847 | ULONG_PTR Information = 0;
3848 | PLOWBOXTOKEN_PARAMS LowboxTokenParam;
3849 |
3850 |
3851 | UNREFERENCED_PARAMETER(DeviceObject);
3852 |
3853 | IrpStack = IoGetCurrentIrpStackLocation(pIrp);
3854 |
3855 |
3856 | if (IrpStack->MajorFunction == IRP_MJ_DEVICE_CONTROL)
3857 | {
3858 | if (IrpStack->Parameters.DeviceIoControl.IoControlCode == IOCTL_NTCREATELOWBOXTOKEN)
3859 | {
3860 | if (IrpStack->Parameters.DeviceIoControl.InputBufferLength != sizeof(LOWBOXTOKEN_PARAMS))
3861 | {
3862 | Status = STATUS_INVALID_PARAMETER;
3863 | goto cleanup;
3864 | }
3865 |
3866 | LowboxTokenParam = (PLOWBOXTOKEN_PARAMS)pIrp->AssociatedIrp.SystemBuffer;
3867 |
3868 | if (bSystemSymbolInitialized == FALSE)
3869 | {
3870 | Status = STATUS_NOT_IMPLEMENTED;
3871 | goto cleanup;
3872 | }
3873 |
3874 | Status = NtCreateLowBoxToken(LowboxTokenParam->TokenHandle,
3875 | LowboxTokenParam->ExistingTokenHandle,
3876 | LowboxTokenParam->DesiredAccess,
3877 | LowboxTokenParam->ObjectAttributes,
3878 | LowboxTokenParam->PackageSid,
3879 | LowboxTokenParam->CapabilityCount,
3880 | LowboxTokenParam->Capabilities,
3881 | LowboxTokenParam->HandleCount,
3882 | LowboxTokenParam->Handles);
3883 | }
3884 | else if (IrpStack->Parameters.DeviceIoControl.IoControlCode == IOCTL_GET_SYSTEM_SYMBOLS)
3885 | {
3886 | Status = InitKernelSymbols(pIrp->AssociatedIrp.SystemBuffer, IrpStack->Parameters.DeviceIoControl.InputBufferLength);
3887 | }
3888 | else
3889 | {
3890 | Status = STATUS_NOT_IMPLEMENTED;
3891 | }
3892 | }
3893 |
3894 | cleanup:
3895 |
3896 | pIrp->IoStatus.Status = Status;
3897 | pIrp->IoStatus.Information = Information;
3898 | IoCompleteRequest(pIrp, IO_NO_INCREMENT);
3899 | return Status;
3900 | }
3901 |
3902 | VOID DriverUnload(PDRIVER_OBJECT DriverObject)
3903 | {
3904 | if (DriverObject->DeviceObject)
3905 | IoDeleteDevice(DriverObject->DeviceObject);
3906 |
3907 | IoDeleteSymbolicLink(&DosDeviceName);
3908 |
3909 | UninitKnownSIDs();
3910 |
3911 | return;
3912 | }
3913 | NTSTATUS DriverEntry(PDRIVER_OBJECT DriverObject, PUNICODE_STRING Registry)
3914 | {
3915 | NTSTATUS Status;
3916 | PDEVICE_OBJECT DeviceObject;
3917 | int i;
3918 |
3919 | UNREFERENCED_PARAMETER(Registry);
3920 |
3921 | Status = IoCreateDevice(DriverObject, 0, &DeviceName, FILE_DEVICE_UNKNOWN, FILE_DEVICE_SECURE_OPEN, TRUE, &DeviceObject);
3922 |
3923 | if (NT_SUCCESS(Status) == FALSE)
3924 | {
3925 | return Status;
3926 | }
3927 |
3928 |
3929 | Status = IoCreateSymbolicLink(&DosDeviceName, &DeviceName);
3930 |
3931 | if (NT_SUCCESS(Status) == FALSE)
3932 | {
3933 | IoDeleteDevice(DeviceObject);
3934 | return Status;
3935 | }
3936 |
3937 | for (i = 0; i <= IRP_MJ_MAXIMUM_FUNCTION; i++)
3938 | {
3939 | DriverObject->MajorFunction[i] = IrpDispatch;
3940 | }
3941 |
3942 | DriverObject->DriverUnload = DriverUnload;
3943 |
3944 |
3945 | return STATUS_SUCCESS;
3946 |
3947 | }
3948 |
--------------------------------------------------------------------------------