-
Notifications
You must be signed in to change notification settings - Fork 35
/
NtUtils.Tokens.Impersonate.pas
530 lines (430 loc) · 16.9 KB
/
NtUtils.Tokens.Impersonate.pas
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
unit NtUtils.Tokens.Impersonate;
{
The module provides support for token impersonation and assignment.
}
interface
{ Note: All functions here support pseudo-handles on input on all OS versions }
uses
Ntapi.WinNt, Ntapi.ntdef, Ntapi.ntpsapi, Ntapi.ntseapi, NtUtils,
NtUtils.Objects;
const
THREAD_BACKUP_TOKEN = THREAD_QUERY_LIMITED_INFORMATION or
THREAD_SET_THREAD_TOKEN;
THREAD_SAFE_SET_THREAD_TOKEN = THREAD_SET_THREAD_TOKEN or
THREAD_QUERY_LIMITED_INFORMATION;
TOKEN_SAFE_IMPERSONATE = TOKEN_IMPERSONATE or TOKEN_QUERY;
// For server thread during direct impersonation
THREAD_SAFE_IMPERSONATE = THREAD_IMPERSONATE or THREAD_DIRECT_IMPERSONATION;
type
// Custom flags for safe impersonation
TSafeImpersonateFlags = set of (
siSkipLevelCheck,
siConvertPrimary // Requires TOKEN_DUPLICATE in addition
);
// Capture the current impersonation token before performing operations that can
// alter it. IAutoReleasable will set the token back when released.
function NtxBackupThreadToken(
[Access(THREAD_BACKUP_TOKEN)] const hxThread: IHandle
): IAutoReleasable;
// Set or clear thread token
[RequiredPrivilege(SE_IMPERSONATE_PRIVILEGE, rpSometimes)]
function NtxSetThreadToken(
[Access(THREAD_SET_THREAD_TOKEN)] const hxThread: IHandle;
[opt, Access(TOKEN_IMPERSONATE)] hxToken: IHandle
): TNtxStatus;
// Set or clear thread token by Thread ID
[RequiredPrivilege(SE_IMPERSONATE_PRIVILEGE, rpSometimes)]
[RequiredPrivilege(SE_DEBUG_PRIVILEGE, rpForBypassingChecks)]
function NtxSetThreadTokenById(
[Access(THREAD_SET_THREAD_TOKEN)] TID: TThreadId;
[opt, Access(TOKEN_IMPERSONATE)] const hxToken: IHandle
): TNtxStatus;
// Set thread token and make sure it was not duplicated to Identification level
[RequiredPrivilege(SE_IMPERSONATE_PRIVILEGE, rpSometimes)]
function NtxSafeSetThreadToken(
[Access(THREAD_SAFE_SET_THREAD_TOKEN)] const hxThread: IHandle;
[opt, Access(TOKEN_SAFE_IMPERSONATE)] hxToken: IHandle;
Flags: TSafeImpersonateFlags = []
): TNtxStatus;
// Set thread token and make sure it was not duplicated to Identification level
[RequiredPrivilege(SE_IMPERSONATE_PRIVILEGE, rpSometimes)]
[RequiredPrivilege(SE_DEBUG_PRIVILEGE, rpForBypassingChecks)]
function NtxSafeSetThreadTokenById(
TID: TThreadId;
[Access(TOKEN_SAFE_IMPERSONATE)] const hxToken: IHandle;
Flags: TSafeImpersonateFlags = []
): TNtxStatus;
// Impersonate the token of any type on the current thread
function NtxImpersonateAnyToken(
[Access(TOKEN_IMPERSONATE or TOKEN_DUPLICATE)] hxToken: IHandle
): TNtxStatus;
// Makes a server thread impersonate a client thread
function NtxImpersonateThread(
[Access(THREAD_IMPERSONATE)] const hxServerThread: IHandle;
[Access(THREAD_DIRECT_IMPERSONATION)] const hxClientThread: IHandle;
ImpersonationLevel: TSecurityImpersonationLevel = SecurityImpersonation;
EffectiveOnly: Boolean = False
): TNtxStatus;
// Impersonate a client thread on the current and revert impersonation later
function NtxImpersonateThreadAuto(
out Reverter: IAutoReleasable;
[Access(THREAD_DIRECT_IMPERSONATION)] const hxClientThread: IHandle;
ImpersonationLevel: TSecurityImpersonationLevel = SecurityImpersonation;
EffectiveOnly: Boolean = False
): TNtxStatus;
// Makes a server thread impersonate a client thread. Also determines which
// impersonation level was actually used.
function NtxSafeImpersonateThread(
[Access(THREAD_SAFE_IMPERSONATE)] const hxServerThread: IHandle;
[Access(THREAD_DIRECT_IMPERSONATION)] const hxClientThread: IHandle;
var ImpersonationLevel: TSecurityImpersonationLevel;
EffectiveOnly: Boolean = False
): TNtxStatus;
// Make a thread impersonate an anonymous token
function NtxImpersonateAnonymousToken(
[Access(THREAD_IMPERSONATE)] const hxThread: IHandle
): TNtxStatus;
// Open an anonymous token
function NtxOpenAnonymousToken(
out hxToken: IHandle;
DesiredAccess: TAccessMask;
HandleAttributes: TObjectAttributesFlags = 0
): TNtxStatus;
// Copy an effective security context of a thread via direct impersonation
function NtxCopyEffectiveToken(
out hxToken: IHandle;
[Access(THREAD_DIRECT_IMPERSONATION)] const hxThread: IHandle;
ImpersonationLevel: TSecurityImpersonationLevel;
DesiredAccess: TTokenAccessMask;
HandleAttributes: TObjectAttributesFlags = 0;
EffectiveOnly: Boolean = False
): TNtxStatus;
// Copy an effective security context of a thread by ID
[RequiredPrivilege(SE_DEBUG_PRIVILEGE, rpForBypassingChecks)]
function NtxCopyEffectiveTokenById(
out hxToken: IHandle;
[Access(THREAD_DIRECT_IMPERSONATION)] TID: TThreadId;
ImpersonationLevel: TSecurityImpersonationLevel;
DesiredAccess: TTokenAccessMask;
HandleAttributes: TObjectAttributesFlags = 0;
EffectiveOnly: Boolean = False
): TNtxStatus;
// Assign primary token to a process
[RequiredPrivilege(SE_ASSIGN_PRIMARY_TOKEN_PRIVILEGE, rpSometimes)]
function NtxAssignPrimaryToken(
[Access(PROCESS_SET_INFORMATION)] const hxProcess: IHandle;
[Access(TOKEN_ASSIGN_PRIMARY)] hxToken: IHandle
): TNtxStatus;
// Assign primary token to a process by a process ID
[RequiredPrivilege(SE_ASSIGN_PRIMARY_TOKEN_PRIVILEGE, rpSometimes)]
[RequiredPrivilege(SE_DEBUG_PRIVILEGE, rpForBypassingChecks)]
function NtxAssignPrimaryTokenById(
PID: TProcessId;
[Access(TOKEN_ASSIGN_PRIMARY)] const hxToken: IHandle
): TNtxStatus;
implementation
uses
Ntapi.ntstatus, NtUtils.Threads, NtUtils.Processes, NtUtils.Processes.Info,
NtUtils.Tokens, NtUtils.Tokens.Info;
{$BOOLEVAL OFF}
{$IFOPT R+}{$DEFINE R+}{$ENDIF}
{$IFOPT Q+}{$DEFINE Q+}{$ENDIF}
function NtxBackupThreadToken;
var
Status: TNtxStatus;
hxToken: IHandle;
begin
// Open the thread's token
Status := NtxOpenThreadToken(hxToken, hxThread, TOKEN_IMPERSONATE);
// Ideally, we should clear impersonation only on STATUS_NO_TOKEN.
// However, it might happen that we get STATUS_ACCESS_DENIED or other errors
// that indicate that the thread has a token we cannot read. We could
// use direct impersonation to obtain a copy in this case, but for now just
// clear it the same way most Winapi functions do.
if not Status.IsSuccess then
hxToken := nil;
Result := Auto.Delay(
procedure
begin
// Try to establish the captured token. If we can't, at least clear
// current impersonation as most Winapi functions would do. Also, we
// can potentially introduce a setting for using safe impersonation
// here. Not sure whether we should, though.
if not NtxSetThreadToken(hxThread, hxToken).IsSuccess and
Assigned(hxToken) then
NtxSetThreadToken(hxThread, nil);
end
);
end;
function NtxSetThreadToken;
var
hToken: THandle;
begin
if Assigned(hxToken) then
begin
// Handle pseudo-handles as well
Result := NtxExpandToken(hxToken, TOKEN_IMPERSONATE);
if not Result.IsSuccess then
Exit;
hToken := hxToken.Handle;
end
else
hToken := 0;
Result := NtxThread.Set(hxThread, ThreadImpersonationToken, hToken);
// TODO: what about inconsistency with NtCurrentTeb.IsImpersonating ?
end;
function NtxSetThreadTokenById;
var
hxThread: IHandle;
begin
Result := NtxOpenThread(hxThread, TID, THREAD_SET_THREAD_TOKEN);
if Result.IsSuccess then
Result := NtxSetThreadToken(hxThread, hxToken);
end;
{ Some notes about safe impersonation...
Usually, the system establishes the exact token we passed to the system call
as an impersonation token for the target thread. However, in some cases it
duplicates the token or adjusts it a bit.
* Anonymous up to identification-level tokens do not require any special
treatment - you can impersonate any of them without limitations.
As for impersonation- and delegation-level tokens:
* If the target process does not have SeImpersonatePrivilege, some security
contexts can't be impersonated by its threads. The system duplicates such
tokens to identification level which fails all further access checks for
the target thread. Unfortunately, the result of NtSetInformationThread does
not provide any information whether it happened. The goal is to detect and
avoid such situations since we should consider such impersonations as failed.
* Also, if the trust level of the target process is lower than the trust level
specified in the token, the system duplicates the token removing the trust
label; as for the rest, the impersonations succeeds. This scenario does not
allow us to determine whether the impersonation was successful by simply
comparing the source and the actually set tokens. Duplication does not
necessarily means failed impersonation.
NtxSafeSetThreadToken sets the token, queries what was actually set, and
checks the impersonation level. Anything but success causes the routine to
undo its work.
Note:
The security context of the target thread is not guaranteed to return to its
previous state. It might happen if the target thread is impersonating a token
that the caller can't open. In this case after the failed call the target
thread will have no token.
To address this issue the caller can make a copy of the target thread's
token by using NtImpersonateThread. See implementation of
NtxCopyEffectiveToken for more details.
Other possible implementations:
* Since NtImpersonateThread fails with BAD_IMPERSONATION_LEVEL when we request
Impersonation-level token while the thread's token is Identification or less.
We can use this behaviour to determine which level the target token is.
}
function NtxSafeSetThreadToken;
var
hxActuallySetToken: IHandle;
StateBackup: IAutoReleasable;
Stats: TTokenStatistics;
begin
// No need to use safe impersonation to revoke tokens
if not Assigned(hxToken) then
Exit(NtxSetThreadToken(hxThread, nil));
if not (siSkipLevelCheck in Flags) then
begin
// Determine the type and impersonation level of the token
Result := NtxToken.Query(hxToken, TokenStatistics, Stats);
if not Result.IsSuccess then
Exit;
// Convert primary tokens if required
if (Stats.TokenType = TokenPrimary) and (siConvertPrimary in Flags) then
begin
Result := NtxDuplicateTokenLocal(hxToken, TokenImpersonation,
SecurityImpersonation);
if not Result.IsSuccess then
Exit;
end
// Anonymous up to Identification do not require any special treatment
else if (Stats.TokenType <> TokenImpersonation) or
(Stats.ImpersonationLevel < SecurityImpersonation) then
Exit(NtxSetThreadToken(hxThread, hxToken));
end;
// Backup the current impersonation state of the target thread.
// IAutoReleasable will revert it in case of failure.
StateBackup := NtxBackupThreadToken(hxThread);
// Set the token
Result := NtxSetThreadToken(hxThread, hxToken);
if not Result.IsSuccess then
begin
// No need to revert impersonation if we didn't change it.
StateBackup.AutoRelease := False;
Exit;
end;
// Read the token back for inspection
Result := NtxOpenThreadToken(hxActuallySetToken, hxThread, TOKEN_QUERY);
if not Result.IsSuccess then
Exit;
// Determine the used impersonation level
Result := NtxToken.Query(hxActuallySetToken, TokenStatistics, Stats);
if not Result.IsSuccess then
Exit;
if Stats.ImpersonationLevel < SecurityImpersonation then
begin
// Safe impersonation failed. SeImpersonatePrivilege
// on the target process can help.
Result.Location := 'NtxSafeSetThreadToken';
Result.LastCall.ExpectedPrivilege := SE_IMPERSONATE_PRIVILEGE;
Result.Status := STATUS_PRIVILEGE_NOT_HELD;
Exit;
end;
// Success. No need to revert anything.
StateBackup.AutoRelease := False;
end;
function NtxSafeSetThreadTokenById;
var
hxThread: IHandle;
begin
Result := NtxOpenThread(hxThread, TID, THREAD_SAFE_SET_THREAD_TOKEN);
if Result.IsSuccess then
Result := NtxSafeSetThreadToken(hxThread, hxToken, Flags);
end;
function NtxImpersonateAnyToken;
begin
// Try to impersonate (in case it is an impersonation-type token)
Result := NtxSetThreadToken(NtxCurrentThread, hxToken);
if Result.Matches(STATUS_BAD_TOKEN_TYPE, 'NtSetInformationThread') then
begin
// Nope, it is a primary token, duplicate it
Result := NtxDuplicateTokenLocal(hxToken, TokenImpersonation,
SecurityImpersonation);
// Retry
if Result.IsSuccess then
Result := NtxSetThreadToken(NtxCurrentThread, hxToken);
end;
end;
function NtxImpersonateThread;
var
QoS: TSecurityQualityOfService;
begin
InitializeQoS(QoS, ImpersonationLevel, EffectiveOnly);
// Direct impersonation makes the server thread to impersonate an effective
// security context of the client thread. No access checks are performed on
// the client's token, the server obtains a copy. Note, that the actual
// impersonation level might turn to be less then the one requested.
Result.Location := 'NtImpersonateThread';
Result.LastCall.Expects<TThreadAccessMask>(THREAD_IMPERSONATE); // Server
Result.LastCall.Expects<TThreadAccessMask>(THREAD_DIRECT_IMPERSONATION); // Client
Result.Status := NtImpersonateThread(HandleOrDefault(hxServerThread),
HandleOrDefault(hxClientThread), QoS);
end;
function NtxImpersonateThreadAuto;
begin
Result := NtxImpersonateThread(NtxCurrentThread, hxClientThread,
ImpersonationLevel, EffectiveOnly);
if not Result.IsSuccess then
Exit;
Reverter := Auto.Delay(
procedure
begin
NtxSetThreadToken(NtxCurrentThread, nil);
end
);
end;
function NtxSafeImpersonateThread;
begin
// No need to use safe impersonation for identification and less
if ImpersonationLevel <= SecurityIdentification then
Exit(NtxImpersonateThread(hxServerThread, hxClientThread,
ImpersonationLevel, EffectiveOnly));
// Make the server impersonate the client. This might result in setting an
// identification-level token on the server (which might or might not be us).
Result := NtxImpersonateThread(hxServerThread, hxClientThread,
ImpersonationLevel, EffectiveOnly);
if not Result.IsSuccess then
Exit;
// Now try to perform seemingly meaningless operation by using the server
// thread both as a client and as a server. If the previous operation
// succeeded, it will merely duplicate the impersonation token. However, if
// the server previously failed the impersonation and got identification-
// level token, the system won't allow us to duplicate the token to
// the requested impersonation level, failing the request.
Result := NtxImpersonateThread(hxServerThread, hxServerThread,
ImpersonationLevel, EffectiveOnly);
if Result.Matches(STATUS_BAD_IMPERSONATION_LEVEL, 'NtImpersonateThread') then
begin
// The server got identification-level token.
// SeImpersonatePrivilege on the server process can help
ImpersonationLevel := SecurityIdentification;
Result := NtxSuccess;
end;
end;
function NtxImpersonateAnonymousToken;
begin
Result.Location := 'NtImpersonateAnonymousToken';
Result.LastCall.Expects<TThreadAccessMask>(THREAD_IMPERSONATE);
Result.Status := NtImpersonateAnonymousToken(HandleOrDefault(hxThread));
end;
function NtxOpenAnonymousToken;
var
StateBackup: IAutoReleasable;
begin
// Revert our impersonation when we exit this function.
StateBackup := NtxBackupThreadToken(NtxCurrentThread);
Result := NtxImpersonateAnonymousToken(NtxCurrentThread);
if not Result.IsSuccess then
begin
// No need to revert impersonation if we did not alter it.
StateBackup.AutoRelease := False;
Exit;
end;
Result := NtxOpenThreadToken(hxToken, NtxCurrentThread, DesiredAccess,
HandleAttributes);
end;
function NtxCopyEffectiveToken;
var
StateBackup: IAutoReleasable;
begin
// Backup our impersonation. IAutoReleasable will revert it
// when we exit this function.
StateBackup := NtxBackupThreadToken(NtxCurrentThread);
// Use direct impersonation to make us impersonate a copy of an effective
// security context of the target thread.
Result := NtxImpersonateThread(NtxCurrentThread, hxThread, ImpersonationLevel,
EffectiveOnly);
if not Result.IsSuccess then
begin
// No need to revert impersonation if we did not alter it.
StateBackup.AutoRelease := False;
Exit;
end;
// Read the token from our thread
Result := NtxOpenThreadToken(hxToken, NtxCurrentThread, DesiredAccess,
HandleAttributes);
end;
function NtxCopyEffectiveTokenById;
var
hxThread: IHandle;
begin
Result := NtxOpenThread(hxThread, TID, THREAD_DIRECT_IMPERSONATION);
if Result.IsSuccess then
Result := NtxCopyEffectiveToken(hxToken, hxThread,
ImpersonationLevel, DesiredAccess, HandleAttributes, EffectiveOnly);
end;
function NtxAssignPrimaryToken;
var
AccessToken: TProcessAccessToken;
begin
// Manage pseudo-tokens
Result := NtxExpandToken(hxToken, TOKEN_ASSIGN_PRIMARY);
if Result.IsSuccess then
begin
AccessToken.Token := hxToken.Handle;
AccessToken.Thread := 0;
Result := NtxProcess.Set(hxProcess, ProcessAccessToken, AccessToken);
end;
end;
function NtxAssignPrimaryTokenById;
var
hxProcess: IHandle;
begin
Result := NtxOpenProcess(hxProcess, PID, PROCESS_SET_INFORMATION);
if not Result.IsSuccess then
Exit;
Result := NtxAssignPrimaryToken(hxProcess, hxToken);
end;
end.