-
Notifications
You must be signed in to change notification settings - Fork 0
/
K_driver.c
383 lines (307 loc) · 12.4 KB
/
K_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
#include <ntdef.h>
#include <ntddk.h>
#include <ntimage.h>
#include <wdm.h>
#include <windef.h>
#include <ntstrsafe.h>
#define NTOSKRNL_LIB
#pragma comment(lib, "Ntoskrnl.lib")
#define IOCTL_GET_PROCESS_IDS CTL_CODE(FILE_DEVICE_UNKNOWN, 0x800, METHOD_BUFFERED, FILE_READ_ACCESS)
#define IOCTL_GET_MODULES CTL_CODE(FILE_DEVICE_UNKNOWN, 0x801, METHOD_BUFFERED, FILE_READ_ACCESS)
#define MAX_PROCESS_INFO_COUNT 80000 // Maximum number of process info entries
#define MAX_MODULE_INFO_COUNT 80000 // Maximum number of module info entries
#define MAX_PATH 260
typedef struct _PROCESS_INFO {
HANDLE ProcessId;
WCHAR Name[MAX_PATH];
} PROCESS_INFO, * PPROCESS_INFO;
typedef struct _PEB_LDR_DATA {
UCHAR Reserved1[8];
PVOID Reserved2[3];
LIST_ENTRY InLoadOrderModuleList;
} PEB_LDR_DATA, * PPEB_LDR_DATA;
typedef struct _PEB
{
BYTE Reserved1[2];
BYTE BeingDebugged;
BYTE Reserved2[1];
PVOID Reserved3[2];
PPEB_LDR_DATA Ldr;
// other fields...
} PEB, * PPEB;
typedef struct _MODULE_INFO {
PVOID Base;
ULONG Size;
WCHAR Name[MAX_PATH];
} MODULE_INFO, * PMODULE_INFO;
typedef enum _SYSTEM_INFORMATION_CLASS {
SystemProcessInformation = 5
} SYSTEM_INFORMATION_CLASS;
extern NTSTATUS PsLookupProcessByProcessId(
IN HANDLE ProcessId,
OUT PEPROCESS* Process
);
extern NTSTATUS NtQuerySystemInformation(
IN SYSTEM_INFORMATION_CLASS SystemInformationClass,
OUT PVOID SystemInformation,
IN ULONG SystemInformationLength,
OUT PULONG ReturnLength
);
extern PVOID PsGetProcessWow64Process(
IN PEPROCESS Process
);
extern NTSTATUS NTAPI ZwQuerySystemInformation(
IN SYSTEM_INFORMATION_CLASS SystemInformationClass,
OUT PVOID SystemInformation,
IN ULONG SystemInformationLength,
OUT PULONG ReturnLength OPTIONAL
);
typedef struct _SYSTEM_PROCESS_INFORMATION {
ULONG NextEntryOffset;
ULONG NumberOfThreads;
LARGE_INTEGER Reserved[3];
LARGE_INTEGER CreateTime;
LARGE_INTEGER UserTime;
LARGE_INTEGER KernelTime;
UNICODE_STRING ImageName;
KPRIORITY BasePriority;
HANDLE ProcessId;
HANDLE InheritedFromProcessId;
} SYSTEM_PROCESS_INFORMATION, * PSYSTEM_PROCESS_INFORMATION;
typedef struct _LDR_DATA_TABLE_ENTRY {
LIST_ENTRY InLoadOrderLinks;
PVOID Reserved1[2];
PVOID DllBase;
PVOID EntryPoint;
ULONG SizeOfImage;
PVOID Reserved2[3];
UNICODE_STRING FullDllName;
ULONG Reserved3[8];
PVOID Reserved4[3];
LIST_ENTRY InMemoryOrderLinks;
} LDR_DATA_TABLE_ENTRY, * PLDR_DATA_TABLE_ENTRY;
// Logging macros
#define LogFunctionEntry() DbgPrint("[%s] Entering: %s\n", __FUNCTION__, __FUNCTION__)
#define LogFunctionExit() DbgPrint("[%s] Exiting: %s\n", __FUNCTION__, __FUNCTION__)
#define LogMessage(format, ...) DbgPrint("[%s] " format "\n", __FUNCTION__, __VA_ARGS__)
NTSTATUS GetProcessIds(PPROCESS_INFO ProcessInfo, ULONG ProcessInfoCount, PULONG ReturnLength)
{
LogFunctionEntry();
NTSTATUS status = STATUS_SUCCESS;
ULONG bufferSize = 0;
ULONG actualCount = 0;
// Determine the required buffer size
status = NtQuerySystemInformation(SystemProcessInformation, NULL, 0, &bufferSize);
if (status != STATUS_INFO_LENGTH_MISMATCH)
{
LogMessage("Failed to get process information size. Error: 0x%X", status);
return status;
}
LogMessage("Obtained required process info size: %lu", bufferSize);
// Allocate memory for the buffer
PVOID processInfoBuffer = ExAllocatePoolWithTag(NonPagedPool, bufferSize, 'Proc');
if (processInfoBuffer == NULL)
{
LogMessage("Failed to allocate memory for process information");
return STATUS_INSUFFICIENT_RESOURCES;
}
LogMessage("Successfully allocated memory for process info");
// Retrieve the process information
status = NtQuerySystemInformation(SystemProcessInformation, processInfoBuffer, bufferSize, &bufferSize);
if (!NT_SUCCESS(status))
{
LogMessage("Failed to get process info. Error: 0x%X", status);
ExFreePool(processInfoBuffer);
return status;
}
// Traverse the process information and copy to the output buffer
PSYSTEM_PROCESS_INFORMATION currentProcessInfo = (PSYSTEM_PROCESS_INFORMATION)processInfoBuffer;
while (currentProcessInfo != NULL && actualCount < ProcessInfoCount)
{
ProcessInfo[actualCount].ProcessId = currentProcessInfo->ProcessId;
RtlCopyMemory(ProcessInfo[actualCount].Name, currentProcessInfo->ImageName.Buffer, currentProcessInfo->ImageName.Length);
ProcessInfo[actualCount].Name[currentProcessInfo->ImageName.Length / sizeof(WCHAR)] = UNICODE_NULL;
LogMessage("Copied process info: ProcessId=%lu, Name=%ls", ProcessInfo[actualCount].ProcessId, ProcessInfo[actualCount].Name);
actualCount++;
if (currentProcessInfo->NextEntryOffset == 0)
break;
currentProcessInfo = (PSYSTEM_PROCESS_INFORMATION)((PBYTE)currentProcessInfo + currentProcessInfo->NextEntryOffset);
}
*ReturnLength = actualCount * sizeof(PROCESS_INFO);
ExFreePool(processInfoBuffer);
LogMessage("Completed process info retrieval");
LogFunctionExit();
return status;
}
NTSTATUS GetLoadedModules(HANDLE ProcessId, PMODULE_INFO ModuleInfo, ULONG ModuleInfoCount, PULONG ReturnLength)
{
LogFunctionEntry();
PEPROCESS process = NULL;
PPEB peb = NULL;
PLIST_ENTRY listEntry = NULL;
PLDR_DATA_TABLE_ENTRY ldrEntry = NULL;
NTSTATUS status = STATUS_SUCCESS;
ULONG actualCount = 0;
// Retrieve the process object.
status = PsLookupProcessByProcessId(ProcessId, &process);
if (!NT_SUCCESS(status))
{
LogMessage("Failed to lookup process by process ID. Error: 0x%X", status);
return status;
}
// Retrieve the PEB address.
peb = (PPEB)PsGetProcessWow64Process(process);
if (peb == NULL)
{
LogMessage("Failed to retrieve process PEB");
ObDereferenceObject(process);
return STATUS_UNSUCCESSFUL;
}
// Retrieve the first module.
listEntry = peb->Ldr->InLoadOrderModuleList.Flink;
ldrEntry = CONTAINING_RECORD(listEntry, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks);
while (actualCount < ModuleInfoCount)
{
ProbeForRead(ldrEntry, sizeof(LDR_DATA_TABLE_ENTRY), 1);
ModuleInfo[actualCount].Base = ldrEntry->DllBase;
ModuleInfo[actualCount].Size = ldrEntry->SizeOfImage;
RtlCopyMemory(ModuleInfo[actualCount].Name, ldrEntry->FullDllName.Buffer, ldrEntry->FullDllName.Length);
ModuleInfo[actualCount].Name[ldrEntry->FullDllName.Length / sizeof(WCHAR)] = UNICODE_NULL;
LogMessage("Copied module info: Base=%p, Size=%lu, Name=%ls", ModuleInfo[actualCount].Base, ModuleInfo[actualCount].Size, ModuleInfo[actualCount].Name);
actualCount++;
if (listEntry == peb->Ldr->InLoadOrderModuleList.Blink)
{
break;
}
listEntry = listEntry->Flink;
ldrEntry = CONTAINING_RECORD(listEntry, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks);
}
*ReturnLength = actualCount * sizeof(MODULE_INFO);
ObDereferenceObject(process);
LogFunctionExit();
return status;
}
NTSTATUS DispatchCreateClose(PDEVICE_OBJECT pDeviceObject, PIRP pIrp)
{
LogFunctionEntry();
UNREFERENCED_PARAMETER(pDeviceObject);
pIrp->IoStatus.Status = STATUS_SUCCESS;
pIrp->IoStatus.Information = 0;
// Check if the IRP is being canceled
if (pIrp->Cancel)
{
pIrp->IoStatus.Status = STATUS_CANCELLED;
IoCompleteRequest(pIrp, IO_NO_INCREMENT);
return STATUS_CANCELLED;
}
IoCompleteRequest(pIrp, IO_NO_INCREMENT);
LogFunctionExit();
return STATUS_SUCCESS;
}
NTSTATUS DispatchIoctl(PDEVICE_OBJECT pDeviceObject, PIRP pIrp)
{
LogFunctionEntry();
UNREFERENCED_PARAMETER(pDeviceObject);
PIO_STACK_LOCATION pIoStackLocation = IoGetCurrentIrpStackLocation(pIrp);
ULONG controlCode = pIoStackLocation->Parameters.DeviceIoControl.IoControlCode;
NTSTATUS status = STATUS_INVALID_DEVICE_REQUEST;
ULONG returnLength = 0;
if (controlCode == IOCTL_GET_PROCESS_IDS)
{
LogMessage("Input Buffer Length for IOCTL_GET_PROCESS_IDS: %lu", pIoStackLocation->Parameters.DeviceIoControl.InputBufferLength);
LogMessage("Output Buffer Length for IOCTL_GET_PROCESS_IDS: %lu", pIoStackLocation->Parameters.DeviceIoControl.OutputBufferLength);
if (pIoStackLocation->Parameters.DeviceIoControl.OutputBufferLength < sizeof(PROCESS_INFO))
{
LogMessage("Insufficient buffer size for process info");
status = STATUS_BUFFER_TOO_SMALL;
goto Exit;
}
PPROCESS_INFO processInfo = (PPROCESS_INFO)pIrp->AssociatedIrp.SystemBuffer;
ULONG processInfoCount = pIoStackLocation->Parameters.DeviceIoControl.OutputBufferLength / sizeof(PROCESS_INFO);
status = GetProcessIds(processInfo, processInfoCount, &returnLength);
if (status == STATUS_INFO_LENGTH_MISMATCH)
{
LogMessage("Insufficient buffer size for process info");
status = STATUS_BUFFER_TOO_SMALL;
}
}
else if (controlCode == IOCTL_GET_MODULES)
{
LogMessage("Input Buffer Length for IOCTL_GET_MODULES: %lu", pIoStackLocation->Parameters.DeviceIoControl.InputBufferLength);
LogMessage("Output Buffer Length for IOCTL_GET_MODULES: %lu", pIoStackLocation->Parameters.DeviceIoControl.OutputBufferLength);
if (pIoStackLocation->Parameters.DeviceIoControl.InputBufferLength < sizeof(HANDLE) || pIoStackLocation->Parameters.DeviceIoControl.OutputBufferLength < sizeof(MODULE_INFO))
{
LogMessage("Insufficient buffer size for module info");
status = STATUS_BUFFER_TOO_SMALL;
goto Exit;
}
PHANDLE pProcessId = (PHANDLE)pIrp->AssociatedIrp.SystemBuffer;
PMODULE_INFO moduleInfo = (PMODULE_INFO)((PUCHAR)pIrp->AssociatedIrp.SystemBuffer + sizeof(HANDLE));
ULONG moduleInfoCount = (pIoStackLocation->Parameters.DeviceIoControl.OutputBufferLength - sizeof(HANDLE)) / sizeof(MODULE_INFO);
// Validate the process ID
PEPROCESS process = NULL;
status = PsLookupProcessByProcessId(*pProcessId, &process);
if (!NT_SUCCESS(status))
{
// Invalid process ID
LogMessage("Invalid process ID");
status = STATUS_INVALID_PARAMETER;
goto Exit;
}
ObDereferenceObject(process);
status = GetLoadedModules(*pProcessId, moduleInfo, moduleInfoCount, &returnLength);
if (status == STATUS_INFO_LENGTH_MISMATCH)
{
LogMessage("Insufficient buffer size for module info");
status = STATUS_BUFFER_TOO_SMALL;
}
}
Exit:
pIrp->IoStatus.Status = status;
pIrp->IoStatus.Information = returnLength;
IoCompleteRequest(pIrp, IO_NO_INCREMENT);
LogFunctionExit();
return status;
}
VOID DriverUnload(PDRIVER_OBJECT pDriverObject)
{
LogFunctionEntry();
UNICODE_STRING dosDeviceName;
RtlInitUnicodeString(&dosDeviceName, L"\\DosDevices\\ModuleList");
IoDeleteSymbolicLink(&dosDeviceName);
IoDeleteDevice(pDriverObject->DeviceObject);
LogFunctionExit();
}
extern NTSTATUS DriverEntry(PDRIVER_OBJECT pDriverObject, PUNICODE_STRING pRegistryPath)
{
LogFunctionEntry();
UNREFERENCED_PARAMETER(pRegistryPath);
NTSTATUS status;
// Set up dispatch routines
pDriverObject->MajorFunction[IRP_MJ_CREATE] = DispatchCreateClose;
pDriverObject->MajorFunction[IRP_MJ_CLOSE] = DispatchCreateClose;
pDriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL] = DispatchIoctl;
pDriverObject->DriverUnload = DriverUnload;
// Create a device object
UNICODE_STRING deviceName;
RtlInitUnicodeString(&deviceName, L"\\Device\\ModuleList");
PDEVICE_OBJECT pDeviceObject;
status = IoCreateDevice(pDriverObject, 0, &deviceName, FILE_DEVICE_UNKNOWN, FILE_DEVICE_SECURE_OPEN, FALSE, &pDeviceObject);
if (!NT_SUCCESS(status))
{
LogMessage("Failed to create device. Error: 0x%X", status);
return status;
}
// Create a symbolic link
UNICODE_STRING dosDeviceName;
RtlInitUnicodeString(&dosDeviceName, L"\\DosDevices\\ModuleList");
status = IoCreateSymbolicLink(&dosDeviceName, &deviceName);
if (!NT_SUCCESS(status))
{
LogMessage("Failed to create symbolic link. Error: 0x%X", status);
IoDeleteDevice(pDeviceObject);
return status;
}
LogFunctionExit();
return STATUS_SUCCESS;
}