1 #include <windows.h>
2 #include <stdio.h>
3 #include "app-helpers.h"
4 #include "nt-stuff.h"
5 #include "util/base.h"
6 
7 WINADVAPI BOOL WINAPI ConvertSidToStringSidW(PSID sid, LPWSTR *str);
8 
is_app(HANDLE process)9 bool is_app(HANDLE process)
10 {
11 	DWORD size_ret;
12 	DWORD ret = 0;
13 	HANDLE token;
14 
15 	if (OpenProcessToken(process, TOKEN_QUERY, &token)) {
16 		BOOL success = GetTokenInformation(token, TokenIsAppContainer,
17 						   &ret, sizeof(ret),
18 						   &size_ret);
19 		if (!success) {
20 			const DWORD error = GetLastError();
21 			blog(LOG_ERROR,
22 			     "is_app GetTokenInformation failed: 0x%08lX",
23 			     error);
24 		}
25 
26 		CloseHandle(token);
27 	}
28 	return !!ret;
29 }
30 
get_app_sid(HANDLE process)31 wchar_t *get_app_sid(HANDLE process)
32 {
33 	wchar_t *ret = NULL;
34 	DWORD size_ret;
35 	BOOL success;
36 	HANDLE token;
37 
38 	if (OpenProcessToken(process, TOKEN_QUERY, &token)) {
39 		DWORD info_len = GetSidLengthRequired(12) +
40 				 sizeof(TOKEN_APPCONTAINER_INFORMATION);
41 
42 		PTOKEN_APPCONTAINER_INFORMATION info = malloc(info_len);
43 
44 		success = GetTokenInformation(token, TokenAppContainerSid, info,
45 					      info_len, &size_ret);
46 		if (success)
47 			ConvertSidToStringSidW(info->TokenAppContainer, &ret);
48 
49 		free(info);
50 		CloseHandle(token);
51 	}
52 
53 	return ret;
54 }
55 
56 static const wchar_t *path_format =
57 	L"\\Sessions\\%lu\\AppContainerNamedObjects\\%s\\%s";
58 
create_app_mutex(const wchar_t * sid,const wchar_t * name)59 HANDLE create_app_mutex(const wchar_t *sid, const wchar_t *name)
60 {
61 	wchar_t path[MAX_PATH];
62 	DWORD session_id = WTSGetActiveConsoleSessionId();
63 	_snwprintf(path, MAX_PATH, path_format, session_id, sid, name);
64 	return nt_create_mutex(path);
65 }
66 
open_app_mutex(const wchar_t * sid,const wchar_t * name)67 HANDLE open_app_mutex(const wchar_t *sid, const wchar_t *name)
68 {
69 	wchar_t path[MAX_PATH];
70 	DWORD session_id = WTSGetActiveConsoleSessionId();
71 	_snwprintf(path, MAX_PATH, path_format, session_id, sid, name);
72 	return nt_open_mutex(path);
73 }
74 
open_app_event(const wchar_t * sid,const wchar_t * name)75 HANDLE open_app_event(const wchar_t *sid, const wchar_t *name)
76 {
77 	wchar_t path[MAX_PATH];
78 	DWORD session_id = WTSGetActiveConsoleSessionId();
79 	_snwprintf(path, MAX_PATH, path_format, session_id, sid, name);
80 	return nt_open_event(path);
81 }
82 
open_app_map(const wchar_t * sid,const wchar_t * name)83 HANDLE open_app_map(const wchar_t *sid, const wchar_t *name)
84 {
85 	wchar_t path[MAX_PATH];
86 	DWORD session_id = WTSGetActiveConsoleSessionId();
87 	_snwprintf(path, MAX_PATH, path_format, session_id, sid, name);
88 	return nt_open_map(path);
89 }
90