-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathDriver.c
602 lines (479 loc) · 15.3 KB
/
Driver.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
#include <ntifs.h>
#include <ntddk.h>
typedef struct _SYSTEM_THREAD_INFORMATION
{
LARGE_INTEGER KernelTime;
LARGE_INTEGER UserTime;
LARGE_INTEGER CreateTime;
ULONG WaitTime;
PVOID StartAddress;
CLIENT_ID ClientId;
KPRIORITY Priority;
LONG BasePriority;
ULONG ContextSwitches;
ULONG ThreadState;
KWAIT_REASON WaitReason;
}SYSTEM_THREAD_INFORMATION,*PSYSTEM_THREAD_INFORMATION;
typedef struct _SYSTEM_PROCESS_INFO
{
ULONG NextEntryOffset;
ULONG NumberOfThreads;
LARGE_INTEGER WorkingSetPrivateSize;
ULONG HardFaultCount;
ULONG NumberOfThreadsHighWatermark;
ULONGLONG CycleTime;
LARGE_INTEGER CreateTime;
LARGE_INTEGER UserTime;
LARGE_INTEGER KernelTime;
UNICODE_STRING ImageName;
KPRIORITY BasePriority;
HANDLE UniqueProcessId;
HANDLE InheritedFromUniqueProcessId;
ULONG HandleCount;
ULONG SessionId;
ULONG_PTR UniqueProcessKey;
SIZE_T PeakVirtualSize;
SIZE_T VirtualSize;
ULONG PageFaultCount;
SIZE_T PeakWorkingSetSize;
SIZE_T WorkingSetSize;
SIZE_T QuotaPeakPagedPoolUsage;
SIZE_T QuotaPagedPoolUsage;
SIZE_T QuotaPeakNonPagedPoolUsage;
SIZE_T QuotaNonPagedPoolUsage;
SIZE_T PagefileUsage;
SIZE_T PeakPagefileUsage;
SIZE_T PrivatePageCount;
LARGE_INTEGER ReadOperationCount;
LARGE_INTEGER WriteOperationCount;
LARGE_INTEGER OtherOperationCount;
LARGE_INTEGER ReadTransferCount;
LARGE_INTEGER WriteTransferCount;
LARGE_INTEGER OtherTransferCount;
SYSTEM_THREAD_INFORMATION Threads[1];
}SYSTEM_PROCESS_INFO,*PSYSTEM_PROCESS_INFO;
typedef struct _LDR_DATA_TABLE_ENTRY
{
LIST_ENTRY InLoadOrderLinks;
LIST_ENTRY InMemoryOrderLinks;
LIST_ENTRY InInitializationOrderLinks;
PVOID DllBase;
PVOID EntryPoint;
ULONG SizeOfImage;
UNICODE_STRING FullDllName;
UNICODE_STRING BaseDllName;
ULONG Flags;
USHORT LoadCount;
USHORT TlsIndex;
union
{
LIST_ENTRY HashLinks;
struct
{
PVOID SectionPointer;
ULONG CheckSum;
};
};
union
{
ULONG TimeDateStamp;
PVOID LoadedImports;
};
struct _ACTIVATION_CONTEXT * EntryPointActivationContext;
PVOID PatchInformation;
LIST_ENTRY ForwarderLinks;
LIST_ENTRY ServiceTagLinks;
LIST_ENTRY StaticLinks;
}LDR_DATA_TABLE_ENTRY,*PLDR_DATA_TABLE_ENTRY;
typedef struct _IMAGE_DOS_HEADER
{
USHORT e_magic;
USHORT e_cblp;
USHORT e_cp;
USHORT e_crlc;
USHORT e_cparhdr;
USHORT e_minalloc;
USHORT e_maxalloc;
USHORT e_ss;
USHORT e_sp;
USHORT e_csum;
USHORT e_ip;
USHORT e_cs;
USHORT e_lfarlc;
USHORT e_ovno;
USHORT e_res[4];
USHORT e_oemid;
USHORT e_oeminfo;
USHORT e_res2[10];
LONG e_lfanew;
}IMAGE_DOS_HEADER,*PIMAGE_DOS_HEADER;
typedef struct _IMAGE_DATA_DIRECTORY
{
ULONG VirtualAddress;
ULONG Size;
}IMAGE_DATA_DIRECTORY,*PIMAGE_DATA_DIRECTORY;
typedef struct _IMAGE_FILE_HEADER
{
USHORT Machine;
USHORT NumberOfSections;
ULONG TimeDateStamp;
ULONG PointerToSymbolTable;
ULONG NumberOfSymbols;
USHORT SizeOfOptionalHeader;
USHORT Characteristics;
}IMAGE_FILE_HEADER,*PIMAGE_FILE_HEADER;
typedef struct _IMAGE_OPTIONAL_HEADER
{
USHORT Magic;
UCHAR MajorLinkerVersion;
UCHAR MinorLinkerVersion;
ULONG SizeOfCode;
ULONG SizeOfInitializedData;
ULONG SizeOfUninitializedData;
ULONG AddressOfEntryPoint;
ULONG BaseOfCode;
ULONG BaseOfData;
ULONG ImageBase;
ULONG SectionAlignment;
ULONG FileAlignment;
USHORT MajorOperatingSystemVersion;
USHORT MinorOperatingSystemVersion;
USHORT MajorImageVersion;
USHORT MinorImageVersion;
USHORT MajorSubsystemVersion;
USHORT MinorSubsystemVersion;
ULONG Win32VersionValue;
ULONG SizeOfImage;
ULONG SizeOfHeaders;
ULONG CheckSum;
USHORT Subsystem;
USHORT DllCharacteristics;
ULONG SizeOfStackReserve;
ULONG SizeOfStackCommit;
ULONG SizeOfHeapReserve;
ULONG SizeOfHeapCommit;
ULONG LoaderFlags;
ULONG NumberOfRvaAndSizes;
IMAGE_DATA_DIRECTORY DataDirectory[16];
}IMAGE_OPTIONAL_HEADER,*PIMAGE_OPTIONAL_HEADER;
typedef struct _IMAGE_NT_HEADERS
{
ULONG Signature;
IMAGE_FILE_HEADER FileHeader;
IMAGE_OPTIONAL_HEADER OptionalHeader;
}IMAGE_NT_HEADERS,*PIMAGE_NT_HEADERS;
typedef struct _IMAGE_EXPORT_DIRECTORY
{
ULONG Characteristics;
ULONG TimeDateStamp;
USHORT MajorVersion;
USHORT MinorVersion;
ULONG Name;
ULONG Base;
ULONG NumberOfFunctions;
ULONG NumberOfNames;
ULONG AddressOfFunctions;
ULONG AddressOfNames;
ULONG AddressOfNameOrdinals;
}IMAGE_EXPORT_DIRECTORY,*PIMAGE_EXPORT_DIRECTORY;
#define IMAGE_DIRECTORY_ENTRY_EXPORT 0
extern "C" NTSTATUS ZwQuerySystemInformation(ULONG InfoClass,PVOID Buffer,ULONG Length,PULONG ReturnLength);
extern "C" LPSTR PsGetProcessImageFileName(PEPROCESS Process);
typedef NTSTATUS (*PLDR_LOAD_DLL)(PWSTR,PULONG,PUNICODE_STRING,PVOID*);
typedef struct _INJECT_INFO
{
HANDLE ProcessId;
wchar_t DllName[1024];
}INJECT_INFO,*PINJECT_INFO;
typedef struct _KINJECT
{
UNICODE_STRING DllName;
wchar_t Buffer[1024];
PLDR_LOAD_DLL LdrLoadDll;
PVOID DllBase;
ULONG Executed;
}KINJECT,*PKINJECT;
typedef enum _KAPC_ENVIRONMENT
{
OriginalApcEnvironment,
AttachedApcEnvironment,
CurrentApcEnvironment,
InsertApcEnvironment
}KAPC_ENVIRONMENT,*PKAPC_ENVIRONMENT;
typedef VOID (NTAPI *PKNORMAL_ROUTINE)(
PVOID NormalContext,
PVOID SystemArgument1,
PVOID SystemArgument2
);
typedef VOID KKERNEL_ROUTINE(
PRKAPC Apc,
PKNORMAL_ROUTINE *NormalRoutine,
PVOID *NormalContext,
PVOID *SystemArgument1,
PVOID *SystemArgument2
);
typedef KKERNEL_ROUTINE (NTAPI *PKKERNEL_ROUTINE);
typedef VOID (NTAPI *PKRUNDOWN_ROUTINE)(
PRKAPC Apc
);
extern "C" void KeInitializeApc(
PRKAPC Apc,
PRKTHREAD Thread,
KAPC_ENVIRONMENT Environment,
PKKERNEL_ROUTINE KernelRoutine,
PKRUNDOWN_ROUTINE RundownRoutine,
PKNORMAL_ROUTINE NormalRoutine,
KPROCESSOR_MODE ProcessorMode,
PVOID NormalContext
);
extern "C" BOOLEAN KeInsertQueueApc(
PRKAPC Apc,
PVOID SystemArgument1,
PVOID SystemArgument2,
KPRIORITY Increment
);
UNICODE_STRING DeviceName=RTL_CONSTANT_STRING(L"\\Device\\KeInject"),SymbolicLink=RTL_CONSTANT_STRING(L"\\DosDevices\\KeInject");
ULONG ApcStateOffset; // Offset to the ApcState structure
PLDR_LOAD_DLL LdrLoadDll; // LdrLoadDll address
void Unload(PDRIVER_OBJECT pDriverObject)
{
DbgPrint("DLL injection driver unloaded.");
IoDeleteSymbolicLink(&SymbolicLink);
IoDeleteDevice(pDriverObject->DeviceObject);
}
void NTAPI KernelRoutine(PKAPC apc,PKNORMAL_ROUTINE* NormalRoutine,PVOID* NormalContext,PVOID* SystemArgument1,PVOID* SystemArgument2)
{
ExFreePool(apc);
}
void NTAPI InjectDllApc(PVOID NormalContext,PVOID SystemArgument1,PVOID SystemArgument2)
{
PKINJECT inject=(PKINJECT)NormalContext;
inject->LdrLoadDll(NULL,NULL,&inject->DllName,&inject->DllBase);
inject->Executed=TRUE;
}
BOOLEAN InjectDll(PINJECT_INFO InjectInfo)
{
PEPROCESS Process;
PETHREAD Thread;
PKINJECT mem;
ULONG size;
PKAPC_STATE ApcState;
PKAPC apc;
PVOID buffer;
PSYSTEM_PROCESS_INFO pSpi;
LARGE_INTEGER delay;
buffer=ExAllocatePool(NonPagedPool,1024*1024); // Allocate memory for the system information
if(!buffer)
{
DbgPrint("Error: Unable to allocate memory for the process thread list.");
return FALSE;
}
// Get the process thread list
if(!NT_SUCCESS(ZwQuerySystemInformation(5,buffer,1024*1024,NULL)))
{
DbgPrint("Error: Unable to query process thread list.");
ExFreePool(buffer);
return FALSE;
}
pSpi=(PSYSTEM_PROCESS_INFO)buffer;
// Find a target thread
while(pSpi->NextEntryOffset)
{
if(pSpi->UniqueProcessId==InjectInfo->ProcessId)
{
DbgPrint("Target thread found. TID: %d",pSpi->Threads[0].ClientId.UniqueThread);
break;
}
pSpi=(PSYSTEM_PROCESS_INFO)((PUCHAR)pSpi+pSpi->NextEntryOffset);
}
// Reference the target process
if(!NT_SUCCESS(PsLookupProcessByProcessId(InjectInfo->ProcessId,&Process)))
{
DbgPrint("Error: Unable to reference the target process.");
ExFreePool(buffer);
return FALSE;
}
DbgPrint("Process name: %s",PsGetProcessImageFileName(Process));
DbgPrint("EPROCESS address: %#x",Process);
// Reference the target thread
if(!NT_SUCCESS(PsLookupThreadByThreadId(pSpi->Threads[0].ClientId.UniqueThread,&Thread)))
{
DbgPrint("Error: Unable to reference the target thread.");
ObDereferenceObject(Process); // Dereference the target process
ExFreePool(buffer); // Free the allocated memory
return FALSE;
}
DbgPrint("ETHREAD address: %#x",Thread);
ExFreePool(buffer); // Free the allocated memory
KeAttachProcess(Process); // Attach to target process's address space
mem=NULL;
size=4096;
// Allocate memory in the target process
if(!NT_SUCCESS(ZwAllocateVirtualMemory(NtCurrentProcess(),(PVOID*)&mem,0,&size,MEM_COMMIT|MEM_RESERVE,PAGE_EXECUTE_READWRITE)))
{
DbgPrint("Error: Unable to allocate memory in the target process.");
KeDetachProcess(); // Detach from target process's address space
ObDereferenceObject(Process); // Dereference the target process
ObDereferenceObject(Thread); // Dereference the target thread
return FALSE;
}
DbgPrint("Memory allocated at %#x",mem);
mem->LdrLoadDll=LdrLoadDll; // Write the address of LdrLoadDll to target process
wcscpy(mem->Buffer,InjectInfo->DllName); // Write the DLL name to target process
RtlInitUnicodeString(&mem->DllName,mem->Buffer); // Initialize the UNICODE_STRING structure
ApcState=(PKAPC_STATE)((PUCHAR)Thread+ApcStateOffset); // Calculate the address of the ApcState structure
ApcState->UserApcPending=TRUE; // Force the target thread to execute APC
memcpy((PKINJECT)(mem+1),InjectDllApc,(ULONG)KernelRoutine-(ULONG)InjectDllApc); // Copy the APC code to target process
DbgPrint("APC code address: %#x",(PKINJECT)(mem+1));
apc=(PKAPC)ExAllocatePool(NonPagedPool,sizeof(KAPC)); // Allocate the APC object
if(!apc)
{
DbgPrint("Error: Unable to allocate the APC object.");
size=0;
ZwFreeVirtualMemory(NtCurrentProcess(),(PVOID*)&mem,&size,MEM_RELEASE); // Free the allocated memory
KeDetachProcess(); // Detach from target process's address space
ObDereferenceObject(Process); // Dereference the target process
ObDereferenceObject(Thread); // Dereference the target thread
return FALSE;
}
KeInitializeApc(apc,Thread,OriginalApcEnvironment,KernelRoutine,NULL,(PKNORMAL_ROUTINE)((PKINJECT)mem+1),UserMode,mem); // Initialize the APC
DbgPrint("Inserting APC to target thread");
// Insert the APC to the target thread
if(!KeInsertQueueApc(apc,NULL,NULL,IO_NO_INCREMENT))
{
DbgPrint("Error: Unable to insert APC to target thread.");
size=0;
ZwFreeVirtualMemory(NtCurrentProcess(),(PVOID*)&mem,&size,MEM_RELEASE); // Free the allocated memory
KeDetachProcess(); // Detach from target process's address space
ObDereferenceObject(Process); // Dereference the target process
ObDereferenceObject(Thread); // Dereference the target thread
ExFreePool(apc); // Free the APC object
return FALSE;
}
delay.QuadPart=-100*10000;
while(!mem->Executed)
{
KeDelayExecutionThread(KernelMode,FALSE,&delay); // Wait for the injection to complete
}
if(!mem->DllBase)
{
DbgPrint("Error: Unable to inject DLL into target process.");
size=0;
ZwFreeVirtualMemory(NtCurrentProcess(),(PVOID*)&mem,&size,MEM_RELEASE);
KeDetachProcess();
ObDereferenceObject(Process);
ObDereferenceObject(Thread);
return FALSE;
}
DbgPrint("DLL injected at %#x",mem->DllBase);
size=0;
ZwFreeVirtualMemory(NtCurrentProcess(),(PVOID*)&mem,&size,MEM_RELEASE); // Free the allocated memory
KeDetachProcess(); // Detach from target process's address space
ObDereferenceObject(Process); // Dereference the target process
ObDereferenceObject(Thread); // Dereference the target thread
return TRUE;
}
NTSTATUS DriverDispatch(PDEVICE_OBJECT DeviceObject,PIRP irp)
{
PIO_STACK_LOCATION io;
PINJECT_INFO InjectInfo;
NTSTATUS status;
io=IoGetCurrentIrpStackLocation(irp);
irp->IoStatus.Information=0;
switch(io->MajorFunction)
{
case IRP_MJ_CREATE:
status=STATUS_SUCCESS;
break;
case IRP_MJ_CLOSE:
status=STATUS_SUCCESS;
break;
case IRP_MJ_READ:
status=STATUS_SUCCESS;
break;
case IRP_MJ_WRITE:
InjectInfo=(PINJECT_INFO)MmGetSystemAddressForMdlSafe(irp->MdlAddress,NormalPagePriority);
if(!InjectInfo)
{
status=STATUS_INSUFFICIENT_RESOURCES;
break;
}
if(!InjectDll(InjectInfo))
{
status=STATUS_UNSUCCESSFUL;
break;
}
status=STATUS_SUCCESS;
irp->IoStatus.Information=sizeof(INJECT_INFO);
break;
default:
status=STATUS_INVALID_DEVICE_REQUEST;
break;
}
irp->IoStatus.Status=status;
IoCompleteRequest(irp,IO_NO_INCREMENT);
return status;
}
NTSTATUS DriverEntry(PDRIVER_OBJECT pDriverObject,PUNICODE_STRING pRegistryPath)
{
PDEVICE_OBJECT DeviceObject;
PEPROCESS Process;
PETHREAD Thread;
PKAPC_STATE ApcState;
PVOID KdVersionBlock,NtdllBase;
PULONG ptr,Functions,Names;
PUSHORT Ordinals;
PLDR_DATA_TABLE_ENTRY MmLoadedUserImageList,ModuleEntry;
ULONG i;
PIMAGE_DOS_HEADER pIDH;
PIMAGE_NT_HEADERS pINH;
PIMAGE_EXPORT_DIRECTORY pIED;
pDriverObject->DriverUnload=Unload;
KdVersionBlock=(PVOID)__readfsdword(0x34); // Get the KdVersionBlock
MmLoadedUserImageList=*(PLDR_DATA_TABLE_ENTRY*)((PUCHAR)KdVersionBlock+0x228); // Get the MmLoadUserImageList
DbgPrint("KdVersionBlock address: %#x",KdVersionBlock);
DbgPrint("MmLoadedUserImageList address: %#x",MmLoadedUserImageList);
ModuleEntry=(PLDR_DATA_TABLE_ENTRY)MmLoadedUserImageList->InLoadOrderLinks.Flink; // Move to first entry
NtdllBase=ModuleEntry->DllBase; // ntdll is always located in first entry
DbgPrint("ntdll base address: %#x",NtdllBase);
pIDH=(PIMAGE_DOS_HEADER)NtdllBase;
pINH=(PIMAGE_NT_HEADERS)((PUCHAR)NtdllBase+pIDH->e_lfanew);
pIED=(PIMAGE_EXPORT_DIRECTORY)((PUCHAR)NtdllBase+pINH->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress);
Functions=(PULONG)((PUCHAR)NtdllBase+pIED->AddressOfFunctions);
Names=(PULONG)((PUCHAR)NtdllBase+pIED->AddressOfNames);
Ordinals=(PUSHORT)((PUCHAR)NtdllBase+pIED->AddressOfNameOrdinals);
// Parse the export table to locate LdrLoadDll
for(i=0;i<pIED->NumberOfNames;i++)
{
if(!strcmp((char*)NtdllBase+Names[i],"LdrLoadDll"))
{
LdrLoadDll=(PLDR_LOAD_DLL)((PUCHAR)NtdllBase+Functions[Ordinals[i]]);
break;
}
}
DbgPrint("LdrLoadDll address: %#x",LdrLoadDll);
Process=PsGetCurrentProcess();
Thread=PsGetCurrentThread();
ptr=(PULONG)Thread;
// Locate the ApcState structure
for(i=0;i<512;i++)
{
if(ptr[i]==(ULONG)Process)
{
ApcState=CONTAINING_RECORD(&ptr[i],KAPC_STATE,Process); // Get the actual address of KAPC_STATE
ApcStateOffset=(ULONG)ApcState-(ULONG)Thread; // Calculate the offset of the ApcState structure
break;
}
}
DbgPrint("ApcState offset: %#x",ApcStateOffset);
IoCreateDevice(pDriverObject,0,&DeviceName,FILE_DEVICE_UNKNOWN,FILE_DEVICE_SECURE_OPEN,FALSE,&DeviceObject);
IoCreateSymbolicLink(&SymbolicLink,&DeviceName);
for(i=0;i<IRP_MJ_MAXIMUM_FUNCTION;i++)
{
pDriverObject->MajorFunction[i]=DriverDispatch;
}
DeviceObject->Flags&=~DO_DEVICE_INITIALIZING;
DeviceObject->Flags|=DO_DIRECT_IO;
DbgPrint("DLL injection driver loaded.");
return STATUS_SUCCESS;
}