-
Notifications
You must be signed in to change notification settings - Fork 59
/
impersonate.cpp
439 lines (351 loc) · 10.5 KB
/
impersonate.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
#include "pch.hpp"
#include "impersonate.hpp"
BOOL c_impersonate::token_is_not_restricted(HANDLE hToken, PBOOL pbIsNotRestricted)
{
BOOL bReturnValue = FALSE;
DWORD dwSize = 0;
PTOKEN_GROUPS pTokenGroups = NULL;
if (!GetTokenInformation(hToken, TokenRestrictedSids, NULL, dwSize, &dwSize))
{
if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
{
log_err("GetTokenInformation");
goto end;
}
}
pTokenGroups = (PTOKEN_GROUPS)LocalAlloc(LPTR, dwSize);
if (!pTokenGroups)
goto end;
if (!GetTokenInformation(hToken, TokenRestrictedSids, pTokenGroups, dwSize, &dwSize))
{
log_err("GetTokenInformation");
goto end;
}
*pbIsNotRestricted = pTokenGroups->GroupCount == 0;
bReturnValue = TRUE;
end:
if (pTokenGroups)
LocalFree(pTokenGroups);
return bReturnValue;
}
BOOL c_impersonate::token_get_sid(HANDLE hToken, PSID* ppSid)
{
BOOL bReturnValue = TRUE;
DWORD dwSize = 0;
PTOKEN_USER pTokenUser = NULL;
if (!GetTokenInformation(hToken, TokenUser, NULL, 0, &dwSize))
{
if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
log_err("GetTokenInformation");
goto end;
}
}
pTokenUser = (PTOKEN_USER)LocalAlloc(LPTR, dwSize);
if (!pTokenUser)
goto end;
if (!GetTokenInformation(hToken, TokenUser, pTokenUser, dwSize, &dwSize))
{
log_err("GetTokenInformation");
goto end;
}
*ppSid = (PSID)LocalAlloc(LPTR, SECURITY_MAX_SID_SIZE);
if (!*ppSid)
goto end;
if (!CopySid(SECURITY_MAX_SID_SIZE, *ppSid, pTokenUser->User.Sid))
{
log_err("CopySid");
LocalFree(*ppSid);
goto end;
}
bReturnValue = TRUE;
end:
if (pTokenUser)
LocalFree(pTokenUser);
return bReturnValue;
}
BOOL c_impersonate::token_get_username(HANDLE hToken, LPWSTR* ppwszUsername)
{
BOOL bReturnValue = FALSE;
PSID pSid = NULL;
const DWORD dwMaxSize = 256;
WCHAR wszUsername[dwMaxSize] = { 0 };
WCHAR wszDomain[dwMaxSize] = { 0 };
DWORD dwMaxUsername = dwMaxSize;
DWORD dwMaxDomain = dwMaxSize;
SID_NAME_USE type;
if (!this->token_get_sid(hToken, &pSid))
goto end;
if (!LookupAccountSid(NULL, pSid, wszUsername, &dwMaxUsername, wszDomain, &dwMaxDomain, &type))
{
log_err("LookupAccountSid");
goto end;
}
*ppwszUsername = (LPWSTR)LocalAlloc(LPTR, (dwMaxSize * 2 + 1) * sizeof(WCHAR));
if (!*ppwszUsername)
goto end;
StringCchPrintf(*ppwszUsername, dwMaxSize * 2 + 1, L"%ws\\%ws", wszDomain, wszUsername);
bReturnValue = TRUE;
end:
if (pSid)
LocalFree(pSid);
return bReturnValue;
}
BOOL c_impersonate::token_compare_sids(PSID pSidA, PSID pSidB)
{
BOOL bReturnValue = FALSE;
LPWSTR pwszSidA = NULL;
LPWSTR pwszSidB = NULL;
if (ConvertSidToStringSid(pSidA, &pwszSidA) && ConvertSidToStringSid(pSidB, &pwszSidB))
{
bReturnValue = _wcsicmp(pwszSidA, pwszSidB) == 0;
LocalFree(pwszSidA);
LocalFree(pwszSidB);
}
else
log_err("ConvertSidToStringSid");
return bReturnValue;
}
BOOL c_impersonate::find_process_token_and_duplicate(_In_ LPCWSTR pwszTargetSid, _Out_ PHANDLE phToken, _In_opt_ LPCWSTR pwszPrivileges[], _In_ DWORD dwPrivilegeCount)
{
BOOL bReturnValue = FALSE;
PSID pTargetSid = NULL;
PVOID pBuffer = NULL;
PSYSTEM_PROCESS_INFORMATION pProcInfo = NULL;
HANDLE hProcess = NULL, hToken = NULL, hTokenDup = NULL;
DWORD dwReturnedLen = 0, dwBufSize = 0x1000, dwSessionId = 0;
PSID pSidTmp = NULL;
NTSTATUS status = STATUS_INFO_LENGTH_MISMATCH;
LPWSTR pwszUsername = NULL;
if (!ConvertStringSidToSid(pwszTargetSid, &pTargetSid))
goto end;
while (TRUE)
{
pBuffer = LocalAlloc(LPTR, dwBufSize);
if (!pBuffer || status != STATUS_INFO_LENGTH_MISMATCH)
break;
status = NtQuerySystemInformation((SYSTEM_INFORMATION_CLASS)SystemProcessInformation, pBuffer, dwBufSize, &dwReturnedLen);
if (NT_SUCCESS(status))
{
pProcInfo = (PSYSTEM_PROCESS_INFORMATION)pBuffer;
while (TRUE) {
if (hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, PtrToUlong(pProcInfo->UniqueProcessId)))
{
if (OpenProcessToken(hProcess, TOKEN_QUERY | TOKEN_DUPLICATE, &hToken))
{
if (DuplicateTokenEx(hToken, MAXIMUM_ALLOWED, NULL, SecurityImpersonation, TokenImpersonation, &hTokenDup))
{
if (this->token_get_sid(hTokenDup, &pSidTmp) && this->token_get_username(hTokenDup, &pwszUsername))
{
if (this->token_compare_sids(pSidTmp, pTargetSid))
{
log_debug("Found a potential Process candidate: PID=%d - Image='%ws' - User='%ws'", PtrToUlong(pProcInfo->UniqueProcessId), pProcInfo->ImageName.Buffer, pwszUsername);
BOOL bTokenIsNotRestricted = FALSE;
this->token_is_not_restricted(hTokenDup, &bTokenIsNotRestricted);
if (bTokenIsNotRestricted)
log_debug("This token is not restricted.");
else
log_debug("This token is restricted.");
if (bTokenIsNotRestricted)
{
if (pwszPrivileges && dwPrivilegeCount != 0)
{
DWORD dwPrivilegeFound = 0;
for (DWORD i = 0; i < dwPrivilegeCount; i++)
{
if (this->token_check_privilege(hTokenDup, pwszPrivileges[i], FALSE))
dwPrivilegeFound++;
}
log_debug("Found %d/%d required privileges in token.", dwPrivilegeFound, dwPrivilegeCount);
if (dwPrivilegeFound == dwPrivilegeCount)
{
log_debug("Found a valid Token candidate.");
*phToken = hTokenDup;
bReturnValue = TRUE;
}
}
else
{
log_debug("Found a valid Token.");
*phToken = hTokenDup;
bReturnValue = TRUE;
}
}
}
LocalFree(pSidTmp);
LocalFree(pwszUsername);
}
if (!bReturnValue)
CloseHandle(hTokenDup);
}
CloseHandle(hToken);
}
CloseHandle(hProcess);
}
// If we found a valid token, stop
if (bReturnValue)
break;
// If next entry is null, stop
if (!pProcInfo->NextEntryOffset)
break;
// Increment SYSTEM_PROCESS_INFORMATION pointer
pProcInfo = (PSYSTEM_PROCESS_INFORMATION)((PBYTE)pProcInfo + pProcInfo->NextEntryOffset);
}
}
LocalFree(pBuffer);
dwBufSize <<= 1;
}
end:
if (pTargetSid)
LocalFree(pTargetSid);
return bReturnValue;
}
BOOL c_impersonate::token_check_privilege(HANDLE hToken, LPCWSTR pwszPrivilege, BOOL bEnablePrivilege)
{
BOOL bReturnValue = FALSE;
DWORD dwTokenPrivilegesSize = 0, i = 0, dwPrivilegeNameLength = 0;
PTOKEN_PRIVILEGES pTokenPrivileges = NULL;
LUID_AND_ATTRIBUTES laa = { 0 };
TOKEN_PRIVILEGES tp = { 0 };
LPWSTR pwszPrivilegeNameTemp = NULL;
if (!GetTokenInformation(hToken, TokenPrivileges, NULL, dwTokenPrivilegesSize, &dwTokenPrivilegesSize))
{
if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
{
log_err("GetTokenInformation");
goto end;
}
}
pTokenPrivileges = (PTOKEN_PRIVILEGES)LocalAlloc(LPTR, dwTokenPrivilegesSize);
if (!pTokenPrivileges)
goto end;
if (!GetTokenInformation(hToken, TokenPrivileges, pTokenPrivileges, dwTokenPrivilegesSize, &dwTokenPrivilegesSize))
{
log_err("GetTokenInformation");
goto end;
}
for (i = 0; i < pTokenPrivileges->PrivilegeCount; i++)
{
laa = pTokenPrivileges->Privileges[i];
dwPrivilegeNameLength = 0;
if (!LookupPrivilegeName(NULL, &(laa.Luid), NULL, &dwPrivilegeNameLength))
{
if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
{
log_err("LookupPrivilegeName");
goto end;
}
}
dwPrivilegeNameLength++;
if (pwszPrivilegeNameTemp = (LPWSTR)LocalAlloc(LPTR, dwPrivilegeNameLength * sizeof(WCHAR)))
{
if (LookupPrivilegeName(NULL, &(laa.Luid), pwszPrivilegeNameTemp, &dwPrivilegeNameLength))
{
if (!_wcsicmp(pwszPrivilegeNameTemp, pwszPrivilege))
{
if (bEnablePrivilege)
{
ZeroMemory(&tp, sizeof(TOKEN_PRIVILEGES));
tp.PrivilegeCount = 1;
tp.Privileges[0].Luid = laa.Luid;
tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
if (AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), (PTOKEN_PRIVILEGES)NULL, (PDWORD)NULL))
bReturnValue = TRUE;
else
log_err("AdjustTokenPrivileges");
}
else
{
bReturnValue = TRUE;
}
break;
}
}
else
log_err("LookupPrivilegeName");
LocalFree(pwszPrivilegeNameTemp);
}
}
end:
if (pTokenPrivileges)
LocalFree(pTokenPrivileges);
return bReturnValue;
}
BOOL c_impersonate::impersonate(_In_ HANDLE hToken)
{
HANDLE hThread = GetCurrentThread(); // Pseudo handle, does not need to be closed
if (!SetThreadToken(&hThread, hToken))
{
log_err("SetThreadToken");
return FALSE;
}
return TRUE;
}
HANDLE c_impersonate::impersonate_as_local_service() {
BOOL bReturnValue = FALSE;
HANDLE hCurrentProcessToken = NULL;
HANDLE hToken = NULL;
HANDLE hCurrentThread = NULL;
if (!OpenProcessToken(GetCurrentProcess(), MAXIMUM_ALLOWED, &hCurrentProcessToken))
{
log_err("OpenProcessToken");
goto end;
}
if (!this->token_check_privilege(hCurrentProcessToken, SE_DEBUG_NAME, TRUE))
goto end;
if (!this->token_check_privilege(hCurrentProcessToken, SE_IMPERSONATE_NAME, TRUE))
goto end;
if (!this->find_process_token_and_duplicate(L"S-1-5-19", &hToken, NULL, 0))
goto end;
log_debug("Impersonating as LOCAL SERVICE.");
if (!this->impersonate(hToken))
goto end;
bReturnValue = TRUE;
end:
if (hCurrentProcessToken)
CloseHandle(hCurrentProcessToken);
return hToken;
}
HANDLE c_impersonate::impersonate_as_system() {
BOOL bReturnValue = FALSE;
HANDLE hCurrentProcessToken = NULL;
HANDLE hToken = NULL;
HANDLE hCurrentThread = NULL;
LPCWSTR pwszPrivileges[2] = {
L"SeDebugPrivilege",
L"SeAssignPrimaryTokenPrivilege"
};
if (!OpenProcessToken(GetCurrentProcess(), MAXIMUM_ALLOWED, &hCurrentProcessToken))
{
log_err("OpenProcessToken");
goto end;
}
if (!this->token_check_privilege(hCurrentProcessToken, SE_DEBUG_NAME, TRUE))
goto end;
if (!this->token_check_privilege(hCurrentProcessToken, SE_ASSIGNPRIMARYTOKEN_NAME, TRUE))
goto end;
if (!this->find_process_token_and_duplicate(L"S-1-5-18", &hToken, pwszPrivileges, ARRAYSIZE(pwszPrivileges)))
goto end;
log_debug("Impersonating as SYSTEM.");
if (!this->impersonate(hToken))
goto end;
bReturnValue = TRUE;
end:
if (hCurrentProcessToken)
CloseHandle(hCurrentProcessToken);
return hToken;
}
BOOL c_impersonate::is_elevated() {
BOOL fRet = FALSE;
HANDLE hToken = NULL;
if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken)) {
TOKEN_ELEVATION Elevation;
DWORD cbSize = sizeof(TOKEN_ELEVATION);
if (GetTokenInformation(hToken, TokenElevation, &Elevation, sizeof(Elevation), &cbSize)) {
fRet = Elevation.TokenIsElevated;
}
}
if (hToken) {
CloseHandle(hToken);
}
return fRet;
}