-
Notifications
You must be signed in to change notification settings - Fork 35
/
NtUtils.AntiHooking.pas
429 lines (349 loc) · 11.3 KB
/
NtUtils.AntiHooking.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
unit NtUtils.AntiHooking;
{
This module introduces user-mode unhooking of ntdll functions via IAT
modification. It works for native 32 and 64 bits, as well as under WoW64.
Note that not all functions support unhooking, but syscall stubs always do.
}
interface
uses
NtUtils, NtUtils.Ldr;
type
TUnhookableImport = record
FunctionName: AnsiString;
IATEntry: PPointer;
TargetRVA: Cardinal; // inside ntdll
end;
// Find all imports of a module that can be unhooked via IAT modification
function RtlxFindUnhookableImport(
const Module: TLdrxModuleInfo;
out Entries: TArray<TUnhookableImport>
): TNtxStatus;
// Unhook the specified functions
function RtlxEnforceAntiHooking(
const Imports: TArray<TUnhookableImport>;
Enable: Boolean = True
): TNtxStatus;
// Unhook functions imported using Delphi's "external" keyword
// Example usage: RtlxEnforceExternalImportAntiHooking([@NtCreateUserProcess]);
function RtlxEnforceExternalImportAntiHooking(
const ExternalImports: TArray<Pointer>;
Enable: Boolean = True
): TNtxStatus;
// Unhook specific functions for a single module
function RtlxEnforceModuleAntiHooking(
const Module: TLdrxModuleInfo;
const Functions: TArray<AnsiString>;
Enable: Boolean = True
): TNtxStatus;
// Unhook specific functions for all currently loaded modules
function RtlxEnforceGlobalAntiHooking(
const Functions: TArray<AnsiString>;
Enable: Boolean = True
): TNtxStatus;
// Apply a custom IAT hook to a specific module
function RtlxInstallIATHook(
out Reverter: IAutoReleasable;
const ModuleName: String;
const ImportModuleName: AnsiString;
const ImportFunction: AnsiString;
[in] Hook: Pointer;
[out, opt] OriginalTarget: PPointer = nil
): TNtxStatus;
implementation
uses
Ntapi.ntdef, Ntapi.ntldr, Ntapi.ntmmapi, Ntapi.ntpebteb, Ntapi.ntstatus,
DelphiUtils.ExternalImport, NtUtils.Sections, NtUtils.ImageHlp,
NtUtils.SysUtils, NtUtils.Memory, NtUtils.Processes, NtUtils.Synchronization,
DelphiUtils.Arrays, DelphiApi.Reflection;
{$BOOLEVAL OFF}
{$IFOPT R+}{$DEFINE R+}{$ENDIF}
{$IFOPT Q+}{$DEFINE Q+}{$ENDIF}
var
AlternateNtdllInitialized: TRtlRunOnce;
AlternateNtdll: IMemory;
AlternateTargets: TArray<TExportEntry>;
// Note: we suppress range checking in these functions because hooked modules
// might have atypical layout (such as an import table outside of the image)
[ThreadSafe]
function RtlxInitializeAlternateNtdll: TNtxStatus;
var
InitState: IAcquiredRunOnce;
begin
if not RtlxRunOnceBegin(@AlternateNtdllInitialized, InitState) then
Exit(NtxSuccess);
// Map a second instance of ntdll from KnownDlls
Result := RtlxMapKnownDll(AlternateNtdll, ntdll, RtlIsWoW64);
if not Result.IsSuccess then
Exit;
// Parse its export and save all functions as available for redirection
Result := RtlxEnumerateExportImage(AlternateTargets, AlternateNtdll.Region,
True, False);
if not Result.IsSuccess then
begin
AlternateNtdll := nil;
Exit;
end;
AlternateNtdll.AutoRelease := False;
InitState.Complete;
end;
function UnhookableImportCapturer(
[in] IAT: Pointer
): TConvertRoutineEx<TImportEntry, TUnhookableImport>;
begin
Result := function (
const Index: Integer;
const Import: TImportEntry;
out UnhookableImport: TUnhookableImport
): Boolean
var
i: Integer;
begin
// Find the export that corresponds to the function. Use fast binary search
// when importing by name (which are sorted by default) or slow linear
// search when importing by ordinal.
if Import.ImportByName then
i := TArray.BinarySearchEx<TExportEntry>(AlternateTargets,
function (const Target: TExportEntry): Integer
begin
Result := RtlxCompareAnsiStrings(Target.Name, Import.Name, True)
end
)
else
i := TArray.IndexOfMatch<TExportEntry>(AlternateTargets,
function (const Target: TExportEntry): Boolean
begin
Result := (Target.Ordinal = Import.Ordinal);
end
);
if i < 0 then
Exit(False);
// Save the name, IAT entry address, and ntdll function RVA
UnhookableImport.FunctionName := Import.Name;
UnhookableImport.IATEntry := PPointer(PByte(IAT) +
Cardinal(Index) * SizeOf(Pointer));
UnhookableImport.TargetRVA := AlternateTargets[i].VirtualAddress;
Result := True;
end;
end;
function UnhookableImportFinder(
[in] Base: Pointer
): TMapRoutine<TImportDllEntry, TArray<TUnhookableImport>>;
begin
// Find and capture all functions that are imported from ntdll
Result := function (const Dll: TImportDllEntry): TArray<TUnhookableImport>
begin
if RtlxEqualAnsiStrings(Dll.DllName, ntdll) then
Result := TArray.ConvertEx<TImportEntry, TUnhookableImport>(Dll.Functions,
UnhookableImportCapturer(PByte(Base) + Dll.IAT))
else
Result := nil;
end
end;
function RtlxFindUnhookableImport;
var
AllImport: TArray<TImportDllEntry>;
begin
Result := RtlxInitializeAlternateNtdll;
if not Result.IsSuccess then
Exit;
// Determine which functions a module imports
Result := RtlxEnumerateImportImage(AllImport, Module.Region, True,
[itNormal, itDelayed], False);
if not Result.IsSuccess then
Exit;
// Intersect them with what we can unhook
Entries := TArray.FlattenEx<TImportDllEntry, TUnhookableImport>(AllImport,
UnhookableImportFinder(Module.DllBase));
end;
function RtlxEnforceAntiHooking;
var
ImportGroups: TArray<TArrayGroup<Pointer, TUnhookableImport>>;
ProtectionReverter: IAutoReleasable;
TargetModule: Pointer;
i, j: Integer;
begin
Result := LdrxCheckDelayedModule(delayed_ntdll);
if not Result.IsSuccess then
Exit;
Result := RtlxInitializeAlternateNtdll;
if not Result.IsSuccess then
Exit;
// Choose where to redirect the functions
if Enable then
TargetModule := AlternateNtdll.Data
else
TargetModule := delayed_ntdll.DllAddress;
// Combine entries that reside on the same page so we can change memory
// protection more efficiently
ImportGroups := TArray.GroupBy<TUnhookableImport, Pointer>(Imports,
function (const Element: TUnhookableImport): Pointer
begin
Result := Pointer(UIntPtr(Element.IATEntry) and not (PAGE_SIZE - 1));
end
);
for i := 0 to High(ImportGroups) do
begin
// Make sure the pages with IAT entries are writable
Result := NtxProtectMemoryAuto(NtxCurrentProcess, ImportGroups[i].Key,
PAGE_SIZE, PAGE_READWRITE, ProtectionReverter);
if not Result.IsSuccess then
Exit;
// Redirect the import
for j := 0 to High(ImportGroups[i].Values) do
ImportGroups[i].Values[j].IATEntry^ := PByte(TargetModule) +
ImportGroups[i].Values[j].TargetRVA;
end;
end;
function RtlxEnforceExternalImportAntiHooking;
var
CurrentModule: TLdrxModuleInfo;
UnhookableImport: TArray<TUnhookableImport>;
IATEntries: TArray<PPointer>;
i: Integer;
begin
Result := LdrxFindModuleInfo(CurrentModule, LdrxModuleStartsAt(@ImageBase));
if not Result.IsSuccess then
Exit;
// Find all imports from the current module that we can unhook
Result := RtlxFindUnhookableImport(CurrentModule, UnhookableImport);
if not Result.IsSuccess then
Exit;
// Determine IAT entry locations of the specified imports
SetLength(IATEntries, Length(ExternalImports));
for i := 0 to High(IATEntries) do
IATEntries[i] := ExternalImportTarget(ExternalImports[i]);
// Leave only the function we were asked to unhook
TArray.FilterInline<TUnhookableImport>(UnhookableImport,
function (const Import: TUnhookableImport): Boolean
begin
Result := TArray.Contains<PPointer>(IATEntries, Import.IATEntry);
end
);
if Length(UnhookableImport) <> Length(ExternalImports) then
begin
// Should not happen as long as the specified functions are imported via the
// "extern" keyword.
Result.Location := 'RtlxEnforceExternalImportAntiHooking';
Result.Status := STATUS_ENTRYPOINT_NOT_FOUND;
Exit;
end;
// Adjust IAT targets
Result := RtlxEnforceAntiHooking(UnhookableImport, Enable);
end;
function RtlxEnforceModuleAntiHooking;
var
UnhookableImport: TArray<TUnhookableImport>;
begin
// Find what we can unhook
Result := RtlxFindUnhookableImport(Module, UnhookableImport);
if not Result.IsSuccess then
Exit;
// Include only the specified names
TArray.FilterInline<TUnhookableImport>(UnhookableImport,
function (const Import: TUnhookableImport): Boolean
begin
Result := TArray.Contains<AnsiString>(Functions, Import.FunctionName);
end
);
// Adjust IAT targets
if Length(UnhookableImport) > 0 then
Result := RtlxEnforceAntiHooking(UnhookableImport, Enable)
else
begin
Result.Location := 'RtlxEnforceModuleAntiHookingByName';
Result.Status := STATUS_ALREADY_COMPLETE;
end;
end;
function RtlxEnforceGlobalAntiHooking;
var
Lock: IAutoReleasable;
Modules: TArray<TLdrxModuleInfo>;
i: Integer;
begin
Result := LdrxAcquireLoaderLock(Lock);
if not Result.IsSuccess then
Exit;
Result := LdrxEnumerateModuleInfo(Modules);
if not Result.IsSuccess then
Exit;
for i := 0 to High(Modules) do
begin
Result := RtlxEnforceModuleAntiHooking(Modules[i], Functions, Enable);
if not Result.IsSuccess then
Exit;
end;
end;
function RtlxApplyPatch(
[in, out, WritesTo] Address: PPointer;
[in] Value: Pointer;
[out, opt] OldValue: PPointer = nil
): TNtxStatus;
var
ProtectionReverter: IAutoReleasable;
Old: Pointer;
begin
// Make address writable
Result := NtxProtectMemoryAuto(NtxCurrentProcess, Address,
SizeOf(Pointer), PAGE_READWRITE, ProtectionReverter);
if not Result.IsSuccess then
Exit;
try
Old := AtomicExchange(Address^, Value);
if Assigned(OldValue) then
OldValue^ := Old;
except
Result.Location := 'RtlxApplyIATPatch';
Result.Status := STATUS_ACCESS_VIOLATION;
end;
end;
function RtlxInstallIATHook;
var
Module: TLdrxModuleInfo;
ModuleRef: IAutoPointer;
Imports: TArray<TImportDllEntry>;
Address: PPointer;
OldTarget: Pointer;
i, j: Integer;
begin
Result := LdrxLoadDllAuto(ModuleName, ModuleRef);
if not Result.IsSuccess then
Exit;
Result := LdrxFindModuleInfo(Module, LdrxModuleStartsAt(ModuleRef.Data));
if not Result.IsSuccess then
Exit;
Result := RtlxEnumerateImportImage(Imports, Module.Region, True,
[itNormal, itDelayed], False);
if not Result.IsSuccess then
Exit;
for i := 0 to High(Imports) do
if RtlxEqualAnsiStrings(Imports[i].DllName, ImportModuleName) then
begin
for j := 0 to High(Imports[i].Functions) do
if Imports[i].Functions[j].ImportByName and
(Imports[i].Functions[j].Name = ImportFunction) then
begin
Pointer(Address) := PByte(Module.DllBase) + Imports[i].IAT +
SizeOf(Pointer) * j;
// Patch the IAT entry
Result := RtlxApplyPatch(Address, Hook, @OldTarget);
if not Result.IsSuccess then
Exit;
Reverter := Auto.Delay(
procedure
begin
// Restore the original target
RtlxApplyPatch(Address, OldTarget);
// Capture the module lifetime and release after unpatching
ModuleRef := nil;
end
);
if Assigned(OriginalTarget) then
OriginalTarget^ := OldTarget;
Exit;
end;
Break;
end;
Result.Location := 'RtlxSetHook';
Result.Status := STATUS_ENTRYPOINT_NOT_FOUND;
end;
end.