Keyboard filter driver unload BSOD - windows

I have developed a keyboard filter driver that changes the keyboard button '1' (above the Q button) to '2'.
This driver works fine.
However, after Unload is executed, pressing the keyboard button causes BSOD.
If the driver is loaded and unloaded without pressing the keyboard button, it will be unloaded normally.
When I check it with Windbg, my driver's ReadCompletion () function is called even after it is unloaded.
I do not know why this is happening even though I've called IoDetachDevice () and IoDeleteDevice ().
In addition, after loading the driver, if you press the keyboard button '1' at the beginning, it does not change to '2'.
And then it changes very well.
I do not know what this is related to.
I hope you will find a solution to this problem.
please answer about my question.
Below is the source code.
#include <wdm.h>
typedef struct
{
PDEVICE_OBJECT NextLayerDeviceObject;
} DEVICE_EXTENSION, *PDEVICE_EXTENSION;
const WCHAR next_device_name[] = L"\\Device\\KeyboardClass0";
const char dbg_name[] = "[Test]";
NTSTATUS IrpSkip(IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp)
{
NTSTATUS ret = STATUS_SUCCESS;
PIO_STACK_LOCATION Stack = IoGetCurrentIrpStackLocation(Irp);
DbgPrint("%s IrpSkip() Start\n", dbg_name);
DbgPrint("%s IrpSkip() - MajorFunction %d\n", dbg_name, Stack->MajorFunction);
IoSkipCurrentIrpStackLocation(Irp);
ret = IoCallDriver(((PDEVICE_EXTENSION)(DeviceObject->DeviceExtension))->NextLayerDeviceObject, Irp);
DbgPrint("IoCallDriver return %x\n", ret);
DbgPrint("%s IrpSkip() End\n", dbg_name);
return ret;
}
NTSTATUS ReadCompletion(IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp, IN PVOID Context)
{
NTSTATUS ret = STATUS_SUCCESS;
PIO_STACK_LOCATION Stack;
unsigned char key[32];
DbgPrint("%s ReadCompletion() Start\n", dbg_name);
if (Irp->IoStatus.Status == STATUS_SUCCESS)
{
DbgPrint("%s ReadCompletion() - Success\n", dbg_name);
RtlCopyMemory(key, Irp->AssociatedIrp.SystemBuffer, 32);
DbgPrint("%s Data : %d %d %d %d %d %d %d %d\n", dbg_name, key[0], key[1], key[2], key[3], key[4], key[5], key[6], key[7]);
if (key[2] == 2)
{
key[2] = 3;
RtlCopyMemory(Irp->AssociatedIrp.SystemBuffer, key, 32);
DbgPrint("%s Key '1' changed '2'\n", dbg_name);
}
}
//else if (Irp->IoStatus.Status == STATUS_PENDING)
else
{
DbgPrint("%s ReadCompletion() - Fail... %x\n", Irp->IoStatus.Status);
}
if (Irp->PendingReturned)
{
IoMarkIrpPending(Irp);
}
DbgPrint("%s ReadCompletion() End\n", dbg_name);
return Irp->IoStatus.Status;
}
NTSTATUS Read(IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp)
{
NTSTATUS ret = STATUS_SUCCESS;
PIO_STACK_LOCATION Stack = IoGetCurrentIrpStackLocation(Irp);
DbgPrint("%s Read() Start\n", dbg_name);
PDEVICE_EXTENSION device_extension = (PDEVICE_EXTENSION)DeviceObject->DeviceExtension;
//IoCopyCurrentIrpStackLocationToNext(Irp);
PIO_STACK_LOCATION current_irp = IoGetCurrentIrpStackLocation(Irp);
PIO_STACK_LOCATION next_irp = IoGetNextIrpStackLocation(Irp);
*next_irp = *current_irp;
IoSetCompletionRoutine(Irp, ReadCompletion, DeviceObject, TRUE, TRUE, TRUE);
ret=IoCallDriver(((PDEVICE_EXTENSION)device_extension)->NextLayerDeviceObject, Irp);
DbgPrint("%s Read() End\n", dbg_name);
return ret;
}
NTSTATUS Unload(IN PDRIVER_OBJECT DriverObject)
{
NTSTATUS ret = STATUS_SUCCESS;
IoDetachDevice(((PDEVICE_EXTENSION)(DriverObject->DeviceObject->DeviceExtension))->NextLayerDeviceObject);
IoDeleteDevice(DriverObject->DeviceObject);
DbgPrint("%s Unload()...\n", dbg_name);
return ret;
}
NTSTATUS DriverEntry(IN PDRIVER_OBJECT DriverObject, IN PUNICODE_STRING RegistryPath)
{
NTSTATUS ret=STATUS_SUCCESS;
UNICODE_STRING _next_device_name;
DbgSetDebugFilterState(DPFLTR_DEFAULT_ID, DPFLTR_INFO_LEVEL, TRUE);
DbgPrint("%s DriverEntry() Start\n", dbg_name);
RtlInitUnicodeString(&_next_device_name, next_device_name);
for (int i = 0; i < IRP_MJ_MAXIMUM_FUNCTION ; i++)
{
DriverObject->MajorFunction[i] = IrpSkip;
}
DriverObject->DriverUnload = Unload;
DriverObject->MajorFunction[IRP_MJ_READ] = Read;
PDEVICE_OBJECT DeviceObject = 0;
PDEVICE_EXTENSION DeviceExtension;
ret = IoCreateDevice(DriverObject, sizeof(DEVICE_EXTENSION), 0, FILE_DEVICE_KEYBOARD, 0, TRUE, &DeviceObject);
if (ret == STATUS_SUCCESS)
{
DbgPrint("%s DriverEntry() - IoCreateDevice() Success\n", dbg_name);
}
else
{
DbgPrint("%s DriverEntry() - IoCreateDevice() Fail\n", dbg_name);
return ret;
}
DeviceExtension = (PDEVICE_EXTENSION)DeviceObject->DeviceExtension;
DeviceObject->Flags &= ~DO_DEVICE_INITIALIZING;
DeviceObject->Flags |= (DO_BUFFERED_IO | DO_POWER_PAGABLE);
ret = IoAttachDevice(DeviceObject, &_next_device_name, &DeviceExtension->NextLayerDeviceObject);
if (ret == STATUS_SUCCESS)
{
DbgPrint("%s DriverEntry() - IoAttachDevice() Success\n", dbg_name);
}
else
{
DbgPrint("%s DriverEntry() - IoAttachDevice() Fail\n", dbg_name);
IoDeleteDevice(DriverObject->DeviceObject);
return ret;
}
DbgPrint("%s DriverEntry() End\n", dbg_name);
return ret;
}
Below is Windbg Call Stack.
0: kd> k
# ChildEBP RetAddr
00 82f33604 82eea083 nt!RtlpBreakWithStatusInstruction
01 82f33654 82eeab81 nt!KiBugCheckDebugBreak+0x1c
02 82f33a1c 82e4c5cb nt!KeBugCheck2+0x68b
03 82f33a1c 975e36e0 nt!KiTrap0E+0x2cf
WARNING: Frame IP not in any known module. Following frames may be wrong.
04 82f33aac 82e83933 <Unloaded_Test.sys>+0x16e0
05 82f33af0 8efed7a2 nt!IopfCompleteRequest+0x128
06 82f33b14 8eea7b74 kbdclass!KeyboardClassServiceCallback+0x2fa
07 82f33b78 82e831b5 i8042prt!I8042KeyboardIsrDpc+0x18c
08 82f33bd4 82e83018 nt!KiExecuteAllDpcs+0xf9
09 82f33c20 82e82e38 nt!KiRetireDpcList+0xd5
0a 82f33c24 00000000 nt!KiIdleLoop+0x38
The CallBack function does not seem to be released properly.
How do I solve this problem?

if you pass pointer to own driver body (ReadCompletion in your case) - driver must not be unloaded until this pointer is used (ReadCompletion called and returned your case)
as notified Harry Johnston need use IoSetCompletionRoutineEx - but documentation for this is bad and not explain all details. absolute mandatory study windows src files (WRK-v1.2 for example) and binary windows code. if you look for implementation of IoSetCompletionRoutineEx - you can view that this routine nothing do for prevent you driver for unloading. it simply allocate small memory block, save here your DeviceObject, Context and CompletionRoutine and set IopUnloadSafeCompletion as completion and pointer to allocated memory block as context.
what is IopUnloadSafeCompletion doing ?
NTSTATUS
IopUnloadSafeCompletion(
IN PDEVICE_OBJECT DeviceObject,
IN PIRP Irp,
IN PVOID Context
)
{
PIO_UNLOAD_SAFE_COMPLETION_CONTEXT Usc = Context;
NTSTATUS Status;
ObReferenceObject (Usc->DeviceObject);
Status = Usc->CompletionRoutine (DeviceObject, Irp, Usc->Context);
ObDereferenceObject (Usc->DeviceObject);
ExFreePool (Usc);
return Status;
}
but this assume that Usc->DeviceObject IS VALID at calling IopUnloadSafeCompletion time. you can delete/de-reference DeviceObject inside CompletionRoutine , do some task which cause your driver unload - and will be no crash, because your CompletionRoutine protected by adding reference to your device. but if IopUnloadSafeCompletion will be called when your device already destroyed and driver unloaded - any way will be crash.
partial solution will be call ObfReferenceObject(DeviceObject) in your dispatch routine and ObfDereferenceObject(DeviceObject) in completion routine. this on practice resolve problem. so code must be next
NTSTATUS OnComplete(PDEVICE_OBJECT DeviceObject, PIRP Irp, PVOID /*Context*/)
{
ObfDereferenceObject(DeviceObject);// !!!
PIO_STACK_LOCATION IrpSp = IoGetCurrentIrpStackLocation(Irp);
if (Irp->PendingReturned)
{
IrpSp->Control |= SL_PENDING_RETURNED;
}
if (IrpSp->MajorFunction == IRP_MJ_READ &&
Irp->IoStatus.Status == STATUS_SUCCESS &&
(Irp->Flags & IRP_BUFFERED_IO))
{
if (ULONG n = (ULONG)Irp->IoStatus.Information / sizeof(KEYBOARD_INPUT_DATA))
{
PKEYBOARD_INPUT_DATA pkid = (PKEYBOARD_INPUT_DATA)Irp->AssociatedIrp.SystemBuffer;
do
{
DbgPrint("Port%x> %x %x\n", pkid->UnitId, pkid->MakeCode, pkid->Flags);
} while (pkid++, --n);
}
}
return ContinueCompletion;
}
NTSTATUS KbdDispatch(PDEVICE_OBJECT DeviceObject, PIRP Irp)
{
IoCopyCurrentIrpStackLocationToNext(Irp);
if (0 > IoSetCompletionRoutineEx(DeviceObject, Irp, OnComplete, NULL, TRUE, TRUE, TRUE))
{
IoSkipCurrentIrpStackLocation(Irp);
}
else
{
ObfReferenceObject(DeviceObject);// !!!
}
return IofCallDriver(
reinterpret_cast<DEVICE_EXTENSION*>(DeviceObject->DeviceExtension)->_NextDeviceObject, Irp);
}
call ObfReferenceObject(DeviceObject); in KbdDispatch prevent unload your driver until ObfDereferenceObject(DeviceObject); called inside OnComplete.
you can ask for what in this case IoSetCompletionRoutineEx at all, if we yourself call ObfReferenceObject / ObfDereferenceObject ? because if DriverUnload already called - all your code hold only on single reference on DeviceObject - so when you call ObfDereferenceObject(DeviceObject); from OnComplete - your device will be deleted and driver unloaded inside ObfDereferenceObject and finally this routine returned to your unloaded code. so sense of IoSetCompletionRoutineEx is protect your completion routine.
but need understand that this is anyway not 100% correct solution. call IoDetachDevice/IoDeleteDevice for attached device not correct from DriverUnload. ( this must be called from IRP_MN_REMOVE_DEVICE or FAST_IO_DETACH_DEVICE callback)
assume next scenario - somebody call NtReadFile for device A to which your B device is attached. NtReadFile get pointer to your B device via IoGetRelatedDeviceObject. internally this routine call IoGetAttachedDevice. read this:
IoGetAttachedDevice does not increment the reference count on the
device object. (Thus no matching call to ObDereferenceObject is
required.) Callers of IoGetAttachedDevice must ensure that no device
objects are added to or removed from the stack while
IoGetAttachedDevice is executing. Callers that cannot do this must use
IoGetAttachedDeviceReference instead.
assume that while NtReadFile using pointer to your B device, another thread called your DriverUnload which delete B device and unload driver. handle/file object exist on device A - this hold it and prevent from unloading. but your attached B device not hold nothing. as result if NtReadFile or any another I/O subsystem routine which use your device execute in concurrent with DriverUnload where you call detach/delete device - system can crash already inside NtReadFile code. and you nothing can do with this. only one way after call IoDetachDevice some(how many ?!) time wait before call IoDeleteDevice. fortunately possibility of this case very low usual.
so try understand - system can crash in NtReadFile already. even if your Dispatch called - your DeviceObject can be deleted/not valid already or driver unloaded during dispatch routine. only after you call ObfReferenceObject(DeviceObject) all become ok. and all this problem because you try detach attached device in DriverUnload (windows not designed for this).
also can noted many another errors in your code. say completion routine must not return Irp->IoStatus.Status it must return or StopCompletion (i.e STATUS_MORE_PROCESSING_REQUIRED ) or any another value - usual ContinueCompletion (i.e STATUS_CONTINUE_COMPLETION or 0) also need not hardcode "\\Device\\KeyboardClass0" but use IoRegisterPlugPlayNotification with GUID_CLASS_KEYBOARD if you not wdm driver. also for xp need special handler for IRP_MJ_POWER ( Passing Power IRPs ) but may be this is already not actual if xp support not actual.
code example can be look like:
struct DEVICE_EXTENSION
{
PDEVICE_OBJECT _NextDeviceObject;
};
NTSTATUS KbdPower(PDEVICE_OBJECT DeviceObject, PIRP Irp)
{
PoStartNextPowerIrp(Irp);
IoSkipCurrentIrpStackLocation(Irp);
return PoCallDriver(
reinterpret_cast<DEVICE_EXTENSION*>(DeviceObject->DeviceExtension)->_NextDeviceObject, Irp);
}
NTSTATUS OnComplete(PDEVICE_OBJECT DeviceObject, PIRP Irp, PVOID /*Context*/)
{
ObfDereferenceObject(DeviceObject);
PIO_STACK_LOCATION IrpSp = IoGetCurrentIrpStackLocation(Irp);
if (Irp->PendingReturned)
{
IrpSp->Control |= SL_PENDING_RETURNED;
}
if (IrpSp->MajorFunction == IRP_MJ_READ &&
Irp->IoStatus.Status == STATUS_SUCCESS &&
(Irp->Flags & IRP_BUFFERED_IO))
{
if (ULONG n = (ULONG)Irp->IoStatus.Information / sizeof(KEYBOARD_INPUT_DATA))
{
PKEYBOARD_INPUT_DATA pkid = (PKEYBOARD_INPUT_DATA)Irp->AssociatedIrp.SystemBuffer;
do
{
DbgPrint("Port%x> %x %x\n", pkid->UnitId, pkid->MakeCode, pkid->Flags);
} while (pkid++, --n);
}
}
return ContinueCompletion;
}
NTSTATUS KbdDispatch(PDEVICE_OBJECT DeviceObject, PIRP Irp)
{
IoCopyCurrentIrpStackLocationToNext(Irp);
if (0 > IoSetCompletionRoutineEx(DeviceObject, Irp, OnComplete, NULL, TRUE, TRUE, TRUE))
{
IoSkipCurrentIrpStackLocation(Irp);
}
else
{
ObfReferenceObject(DeviceObject);
}
return IofCallDriver(
reinterpret_cast<DEVICE_EXTENSION*>(DeviceObject->DeviceExtension)->_NextDeviceObject, Irp);
}
NTSTATUS KbdNotifyCallback(PDEVICE_INTERFACE_CHANGE_NOTIFICATION Notification, PDRIVER_OBJECT DriverObject)
{
if (::RtlCompareMemory(&Notification->Event, &GUID_DEVICE_INTERFACE_ARRIVAL, sizeof(GUID)) == sizeof(GUID))
{
DbgPrint("++%wZ\n", Notification->SymbolicLinkName);
HANDLE hFile;
OBJECT_ATTRIBUTES oa = { sizeof(oa), 0, Notification->SymbolicLinkName, OBJ_CASE_INSENSITIVE };
IO_STATUS_BLOCK iosb;
if (0 <= IoCreateFile(&hFile, SYNCHRONIZE, &oa, &iosb, 0, 0, FILE_SHARE_VALID_FLAGS, FILE_OPEN, 0, 0, 0, CreateFileTypeNone, 0, IO_ATTACH_DEVICE))
{
PFILE_OBJECT FileObject;
NTSTATUS status = ObReferenceObjectByHandle(hFile, 0, 0, 0, (void**)&FileObject, 0);
NtClose(hFile);
if (0 <= status)
{
PDEVICE_OBJECT DeviceObject, TargetDevice = IoGetAttachedDeviceReference(FileObject->DeviceObject);
ObfDereferenceObject(FileObject);
if (0 <= IoCreateDevice(DriverObject, sizeof(DEVICE_EXTENSION), 0,
TargetDevice->DeviceType,
TargetDevice->Characteristics & (FILE_REMOVABLE_MEDIA|FILE_DEVICE_SECURE_OPEN),
FALSE, &DeviceObject))
{
DeviceObject->Flags |= TargetDevice->Flags &
(DO_BUFFERED_IO|DO_DIRECT_IO|DO_SUPPORTS_TRANSACTIONS|DO_POWER_PAGABLE|DO_POWER_INRUSH);
DEVICE_EXTENSION* pExt = (DEVICE_EXTENSION*)DeviceObject->DeviceExtension;
if (0 > IoAttachDeviceToDeviceStackSafe(DeviceObject, TargetDevice, &pExt->_NextDeviceObject))
{
IoDeleteDevice(DeviceObject);
}
else
{
DeviceObject->Flags &= ~DO_DEVICE_INITIALIZING;
DbgPrint("++DeviceObject<%p> %x\n", DeviceObject, DeviceObject->Flags);
}
}
ObfDereferenceObject(TargetDevice);
}
}
}
return STATUS_SUCCESS;
}
PVOID NotificationEntry;
void KbdUnload(PDRIVER_OBJECT DriverObject)
{
DbgPrint("KbdUnload(%p)\n", DriverObject);
if (NotificationEntry) IoUnregisterPlugPlayNotification(NotificationEntry);
PDEVICE_OBJECT NextDevice = DriverObject->DeviceObject, DeviceObject;
while (DeviceObject = NextDevice)
{
NextDevice = DeviceObject->NextDevice;
DbgPrint("--DeviceObject<%p>\n", DeviceObject);
IoDetachDevice(reinterpret_cast<DEVICE_EXTENSION*>(DeviceObject->DeviceExtension)->_NextDeviceObject);
IoDeleteDevice(DeviceObject);
}
}
NTSTATUS KbdInit(PDRIVER_OBJECT DriverObject, PUNICODE_STRING /*RegistryPath*/)
{
DbgPrint("KbdInit(%p)\n", DriverObject);
DriverObject->DriverUnload = KbdUnload;
#ifdef _WIN64
__stosq
#else
__stosd
#endif
((PULONG_PTR)DriverObject->MajorFunction, (ULONG_PTR)KbdDispatch, RTL_NUMBER_OF(DriverObject->MajorFunction));
ULONG MajorVersion;
PsGetVersion(&MajorVersion, 0, 0, 0);
if (MajorVersion < 6) DriverObject->MajorFunction[IRP_MJ_POWER] = KbdPower;
IoRegisterPlugPlayNotification(
EventCategoryDeviceInterfaceChange,
PNPNOTIFY_DEVICE_INTERFACE_INCLUDE_EXISTING_INTERFACES,
(void*)&GUID_CLASS_KEYBOARD, DriverObject,
(PDRIVER_NOTIFICATION_CALLBACK_ROUTINE)KbdNotifyCallback,
DriverObject, &NotificationEntry);
return STATUS_SUCCESS;
}

This sounds like it explains your problem:
Note Only a driver that can guarantee it will not be unloaded before its completion routine finishes can use IoSetCompletionRoutine. Otherwise, the driver must use IoSetCompletionRoutineEx, which prevents the driver from unloading until its completion routine executes.
(From the MSDN documentation for IoSetCompletionRoutine.)
PS: the one-keystroke delay in the functionality taking effect is to be expected, because your driver isn't hooked into the read operation that was already in progress when it was loaded. I'm not sure whether there's any reasonable way to do that.

Related

How to hook DNS query request in windows?

I want to hook DNS query request in windows, I use IAThook to hook "gethostbyname","getaddrinfo","GetAddrInfoW", "GetAddrInfoExA","GetAddrInfoExW","WSAAsyncGetHostByName", but seems most app didn't link the ws2_32.dll statically at all. So I also hook "GetProcAddress" in kernel32.dll, but them also don't use "gethostbyname"...at all(but the DNS query request actually be sent). I test this with MsEdge explorer and many other apps. I do this in LSP.
Do these apps not usr such as "gethostbyname" function to send a DNS request? How can I do?
Can somebody give me some help?
my code like this:
long hookGetProcAddress()
{
long ret = 0;
FUNCBEGINLOG
if (g_hHook_GetProcAddressFunc != NULL)
{
dbgprint("%s hookGetProcAddress already hooked!", moduleBaseName);
return ret;
}
ret = IATHook(GetModuleHandleW(NULL), "kernel32.dll", "GetProcAddress",
LSPGetProcAddress, &g_hHook_GetProcAddressFunc);
dbgprint("%s hookGetProcAddress func ret %d!", moduleBaseName, ret);
FUNCFINISHLOG
return ret;
}
long hookgethostbyname()
{
long ret = 0;
FUNCBEGINLOG
if (g_hHook_gethostbynameFunc != NULL)
{
dbgprint("%s hookgethostbyname already hooked!", moduleBaseName);
return ret;
}
ret = IATHook(GetModuleHandleW(NULL), "Ws2_32.dll", "gethostbyname",
LSPgethostbyname,
&g_hHook_gethostbynameFunc);
dbgprint("%s hookgethostbyname func ret %d!", moduleBaseName, ret);
FUNCFINISHLOG
return ret;
}
long hookgetaddrinfo()
{
long ret = 0;
FUNCBEGINLOG
if (g_hHook_getaddrinfoFunc != NULL)
{
dbgprint("%s hookgetaddrinfo already hooked!", moduleBaseName);
return ret;
}
ret = IATHook(GetModuleHandleW(NULL), "Ws2_32.dll", "getaddrinfo", LSPgetaddrinfo, &g_hHook_getaddrinfoFunc);
dbgprint("%s hookgetaddrinfo func ret %d!", moduleBaseName, ret);
FUNCFINISHLOG
return ret;
}

Keyboard Filter Driver BSOD

I do not understand why my source code is not working properly.
My source code is just a simple driver that just drops the IRP.
#include <wdm.h>
typedef struct
{
PDEVICE_OBJECT NextLayerDeviceObject;
} DEVICE_EXTENSION, *PDEVICE_EXTENSION;
const WCHAR next_device_name[] = L"\\Device\\KeyboardClass0";
const char dbg_name[] = "[Test]";
NTSTATUS IrpSkip(IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp)
{
NTSTATUS ret = STATUS_SUCCESS;
PIO_STACK_LOCATION Stack = IoGetCurrentIrpStackLocation(Irp);
DbgPrint("%s IrpSkip() Start\n", dbg_name);
DbgPrint("%s IrpSkip() - MajorFunction %d\n", dbg_name, Stack->MajorFunction);
IoSkipCurrentIrpStackLocation(Irp);
ret = IoCallDriver(((PDEVICE_EXTENSION)(DeviceObject->DeviceExtension))->NextLayerDeviceObject, Irp);
DbgPrint("%s IrpSkip() End\n", dbg_name);
return ret;
}
NTSTATUS Unload(IN PDRIVER_OBJECT DriverObject)
{
NTSTATUS ret = STATUS_SUCCESS;
IoDetachDevice(((PDEVICE_EXTENSION)(DriverObject->DeviceObject->DeviceExtension))->NextLayerDeviceObject);
IoDeleteDevice(DriverObject->DeviceObject);
DbgPrint("%s Unload()...\n", dbg_name);
return ret;
}
NTSTATUS DriverEntry(IN PDRIVER_OBJECT DriverObject, IN PUNICODE_STRING RegistryPath)
{
NTSTATUS ret=STATUS_SUCCESS;
UNICODE_STRING _next_device_name;
DbgSetDebugFilterState(DPFLTR_DEFAULT_ID, DPFLTR_INFO_LEVEL, TRUE);
DbgPrint("%s DriverEntry() Start\n", dbg_name);
RtlInitUnicodeString(&_next_device_name, next_device_name);
for (int i = 0; i < IRP_MJ_MAXIMUM_FUNCTION ; i++)
{
DriverObject->MajorFunction[i] = IrpSkip;
}
DriverObject->DriverUnload = Unload;
//DriverObject->MajorFunction[IRP_MJ_READ] = Read;
PDEVICE_OBJECT DeviceObject = 0;
PDEVICE_EXTENSION DeviceExtension;
ret = IoCreateDevice(DriverObject, sizeof(DEVICE_EXTENSION), 0, FILE_DEVICE_KEYBOARD, 0, TRUE, &DeviceObject);
if (ret == STATUS_SUCCESS)
{
DbgPrint("%s DriverEntry() - IoCreateDevice() Success\n", dbg_name);
}
else
{
DbgPrint("%s DriverEntry() - IoCreateDevice() Fail\n", dbg_name);
return ret;
}
DeviceExtension = (PDEVICE_EXTENSION)DeviceObject->DeviceExtension;
DeviceObject->Flags |= (DO_BUFFERED_IO | DO_POWER_PAGABLE);
DeviceObject->Flags &= DO_DEVICE_INITIALIZING;
ret = IoAttachDevice(DeviceObject, &_next_device_name, &DeviceExtension->NextLayerDeviceObject);
if (ret == STATUS_SUCCESS)
{
DbgPrint("%s DriverEntry() - IoAttachDevice() Success\n", dbg_name);
}
else
{
DbgPrint("%s DriverEntry() - IoAttachDevice() Fail\n", dbg_name);
IoDeleteDevice(DriverObject->DeviceObject);
return ret;
}
DbgPrint("%s DriverEntry() End\n", dbg_name);
return ret;
}
Below are the results from WinDbg
[Test] DriverEntry() Start
[Test] DriverEntry() - IoCreateDevice() Success
[Test] IrpSkip() Start
[Test] IrpSkip() - MajorFunction 2
[Test] IrpSkip() End
[Test] DriverEntry() - IoAttachDevice() Success
[Test] DriverEntry() End
[Test] IrpSkip() Start
[Test] IrpSkip() - MajorFunction 3
[Test] IrpSkip() End
*** Fatal System Error: 0x0000000a
(0x00000000,0x00000002,0x00000001,0x82E41C24)
Break instruction exception - code 80000003 (first chance)
A fatal system error has occurred.
Debugger entered on first try; Bugcheck callbacks have not been invoked.
A fatal system error has occurred.
nt!RtlpBreakWithStatusInstruction:
82e83110 cc int 3
0: kd> k
# ChildEBP RetAddr
00 82f30634 82ee7083 nt!RtlpBreakWithStatusInstruction
01 82f30684 82ee7b81 nt!KiBugCheckDebugBreak+0x1c
02 82f30a48 82e495cb nt!KeBugCheck2+0x68b
03 82f30a48 82e41c24 nt!KiTrap0E+0x2cf
04 82f30ae4 8fba3588 nt!memmove+0x124
05 82f30b14 8fb8fb74 kbdclass!KeyboardClassServiceCallback+0xe0
06 82f30b78 82e801b5 i8042prt!I8042KeyboardIsrDpc+0x18c
07 82f30bd4 82e80018 nt!KiExecuteAllDpcs+0xf9
08 82f30c20 82e7fe38 nt!KiRetireDpcList+0xd5
09 82f30c24 00000000 nt!KiIdleLoop+0x38
It seems that CallBack is not working properly.
I do not know where the problem occurred.
I just dropped the IRP and I do not know why this is happening.
I have been searching for driver 's books and internet for two days but have not found the cause.
When the blue screen comes up, the message 'iRQL_NOT_LESS_OR_EQUAL' appears.
Help plz.
P.S. I do not speak English well. And that's the first question. I hope you understand if my question is strange.

Kernel Mode Driver and IOCTL

What I'm trying to do:
User-mode app sends Process ID to driver
Driver gets handle to specified Process ID
Drivers passes opened handle to user-mode app
I'm not sure if this code is even completely working. I'm quite new to drivers, so I haven't set up debugging yet and virtual machine hasn't finished downloading (slow connection problems).
Getting Process ID from user-mode app should be working fine and it should be getting stored in PROCESS_INFO struct as ProcessId. The opened handle is stored in the same struct as ProcessHandle to be sent back to the user-mode application. I'm not sure how to return data from kernel to user-mode tho, maybe someone could explain briefly.
Here's my code:
#include <ntifs.h>
#include <wdf.h>
DRIVER_INITIALIZE DriverEntry;
UNICODE_STRING DeviceName = RTL_CONSTANT_STRING(L"\\Device\\GetSysHandle"), SymbolicLink = RTL_CONSTANT_STRING(L"\\DosDevices\\GetSysHandle");
typedef struct _PROCESS_INFO
{
HANDLE ProcessId;
HANDLE ProcessHandle;
}PROCESS_INFO, *PPROCESS_INFO;
BOOLEAN GetSysHandle(PPROCESS_INFO ProcessInfo)
{
NTSTATUS status = STATUS_ACCESS_DENIED;
PEPROCESS eProcess = NULL;
status = PsLookupProcessByProcessId(ProcessInfo->ProcessId, &eProcess);
if ((!NT_SUCCESS(status)) || (!eProcess))
{
return FALSE;
}
status = ObOpenObjectByPointer(eProcess, 0, NULL, 0, 0, KernelMode, &ProcessInfo->ProcessHandle);
if ((!NT_SUCCESS(status)) || (!ProcessInfo->ProcessHandle))
{
ObDereferenceObject(eProcess);
return FALSE;
}
return TRUE;
}
void Unload(PDRIVER_OBJECT pDriverObject)
{
DbgPrint("# GetSysHandle driver unloaded.");
IoDeleteSymbolicLink(&SymbolicLink);
IoDeleteDevice(pDriverObject->DeviceObject);
}
NTSTATUS DriverDispatch(PDEVICE_OBJECT DeviceObject, PIRP irp)
{
PIO_STACK_LOCATION io;
PPROCESS_INFO ProcessInfo;
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:
ProcessInfo = (PPROCESS_INFO)MmGetSystemAddressForMdlSafe(irp->MdlAddress, NormalPagePriority);
if (!ProcessInfo)
{
status = STATUS_INSUFFICIENT_RESOURCES;
break;
}
if (!GetSysHandle(ProcessInfo))
{
DbgPrint("# Failed to get process handle");
status = STATUS_UNSUCCESSFUL;
break;
}
status = STATUS_SUCCESS;
irp->IoStatus.Information = sizeof(PROCESS_INFO);
break;
default:
status = STATUS_INVALID_DEVICE_REQUEST;
break;
}
irp->IoStatus.Status = status;
IoCompleteRequest(irp, IO_NO_INCREMENT);
return status;
}
NTSTATUS DriverEntry(_In_ PDRIVER_OBJECT DriverObject, _In_ PUNICODE_STRING RegistryPath)
{
PDEVICE_OBJECT DeviceObject;
ULONG i;
DbgPrint("# GetSysHandle driver loaded");
IoCreateDevice(DriverObject, 0, &DeviceName, FILE_DEVICE_UNKNOWN, FILE_DEVICE_SECURE_OPEN, FALSE, &DeviceObject);
IoCreateSymbolicLink(&SymbolicLink, &DeviceName);
for (i = 0;i<IRP_MJ_MAXIMUM_FUNCTION;i++)
{
DriverObject->MajorFunction[i] = DriverDispatch;
}
return STATUS_SUCCESS;
}
First and foremost (to avoid confusion): this code is for Windows and Windows Drivers.
The biggest issue I see with your driver code is that you aren't registering the IRP major functions inside of DriverEntry. You will need to set the MajorFunction parameters of the PDRIVER_OBJECT DriverObject to the dispatch functions. Without assigning these MajorFunctions, the driver will have no way of knowing what function to call when receiving a command.
To do this, break up the cases for the switch (io->MajorFunction) into different dispatch functions. For example, IRP_MJ_WRITE will be its own function, and you can declare it like so:
DRIVER_DISPATCH DispatchReadFunction;
In this case, we will want all read commands issued to the driver to run whatever code is inside the DispatchReadFunction function. So the definition will look a little like this:
NTSTATUS DispatchReadFunction(_In_ PDEVICE_OBJECT DriverObject, _In_ PIRP Irp)
{
NTSTATUS status = STATUS_SUCCESS;
//Do read code here
return status;
}
Once we have the DispatchReadFunction function written, you will need to assign it to the DriverObject->MajorFunction in the DriverEntry function like so:
DriverObject->MajorFunction[IRP_MJ_READ] = DispatchReadFunction;
Finally, stub out and write the rest of the IRP_MJ_ functions that you need, making sure that you assign them to the MajorFunction memeber of DriverObject.
My DriverEntry function looks like this (I removed extra functionality):
NTSTATUS DriverEntry(_In_ PDRIVER_OBJECT DriverObject, _In_ PUNICODE_STRING RegistryPath)
{
NTSTATUS status;
status = STATUS_SUCCESS;
DriverObject->MajorFunction[IRP_MJ_READ] = DispatchReadFunc;
DriverObject->MajorFunction[IRP_MJ_CREATE] = DispatchCreateFunc;
DriverObject->MajorFunction[IRP_MJ_CLOSE] = DispatchCloseFunc;
DriverObject->MajorFunction[IRP_MJ_WRITE] = DispatchWriteFunc;
DriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL] = DispatchDevCtrlFunc;
return status;
}
A good starting point would be here. This link also includes a simple example (driver code and application code) that does what you are attempting to do.
Good Luck!

Filter hook driver: dispatch routine isn't called

I'm trying to write legacy filter-hook driver, firewall-like: look for dst port and block it.
But when packets are sent, dispatcher routine isn't called.
Register dispatch:
DriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL] = DrvDispatch;
Start ipfilter driver:
C:\Users\unnamed>net start ipfilterdriver
After that, launch debug driver via Visual DDK. Driver load successfully, but breakpoint in dispatcher isn't reached. What am I doing wrong?
NTSTATUS DriverEntry(IN PDRIVER_OBJECT DriverObject, IN PUNICODE_STRING RegistryPath)
{
UNICODE_STRING DeviceName,Win32Device;
PDEVICE_OBJECT DeviceObject = NULL;
NTSTATUS status;
unsigned i;
RtlInitUnicodeString(&DeviceName,L"\\Device\\driver10");
RtlInitUnicodeString(&Win32Device,L"\\DosDevices\\driver10");
for (i = 0; i <= IRP_MJ_MAXIMUM_FUNCTION; i++)
DriverObject->MajorFunction[i] = driver1DefaultHandler;
/*
DriverObject->MajorFunction[IRP_MJ_CREATE] = driver1CreateClose;
DriverObject->MajorFunction[IRP_MJ_CLOSE] = driver1CreateClose;
DriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL] = DrvDispatch;
*/
status = IoCreateDevice(DriverObject, 0, &DeviceName,
FILE_DEVICE_DRVFLTIP, 0, FALSE,
&DeviceObject);
if (NT_SUCCESS(status)) {
status = IoCreateSymbolicLink(&Win32Device, &DeviceName);
if (!NT_SUCCESS(status))
dprintf("DrvFltIp.SYS: IoCreateSymbolicLink failed\n");
DriverObject->MajorFunction[IRP_MJ_CREATE] =
DriverObject->MajorFunction[IRP_MJ_CLOSE] =
DriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL] = DrvDispatch;
DriverObject->DriverUnload = driver1Unload;
}
if (!NT_SUCCESS(status)) {
dprintf("Error in initialization. Unloading...");
driver1Unload(DriverObject);
}
if (!DeviceObject)
return STATUS_UNEXPECTED_IO_ERROR;
/*
DeviceObject->Flags |= DO_DIRECT_IO;
DeviceObject->Flags &= ~DO_DEVICE_INITIALIZING;
DeviceObject->AlignmentRequirement = FILE_WORD_ALIGNMENT;
*/
DbgPrint("Driver started\n");
return status;
}
NTSTATUS DrvDispatch(IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp)
{
dprintf("DrvDispatch called\n");
PIO_STACK_LOCATION irpStack;
PVOID ioBuffer;
ULONG inputBufferLength;
ULONG outputBufferLength;
ULONG ioControlCode;
NTSTATUS ntStatus;
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = 0;
irpStack = IoGetCurrentIrpStackLocation(Irp);
switch (irpStack->MajorFunction) {
case IRP_MJ_CREATE:
dprintf("DrvFltIp.SYS: IRP_MJ_CREATE\n");
break;
case IRP_MJ_CLOSE:
dprintf("DrvFltIp.SYS: IRP_MJ_CLOSE\n");
break;
case IRP_MJ_DEVICE_CONTROL:
dprintf("DrvFltIp.SYS: IRP_MJ_DEVICE_CONTROL\n");
break;
}
ntStatus = Irp->IoStatus.Status;
IoCompleteRequest(Irp, IO_NO_INCREMENT);
return ntStatus;
}
Just forgot register filter-hook callback function in the DriverEntry:
Registering and Clearing a Filter Hook

Asynchronous NtQueryDirectoryFile?

Has anyone managed to figure out how asynchronous calls to NtQueryDirectoryFile work?
By an asynchronous call, I mean calling NtQueryDirectoryFile on directories not opened with FILE_SYNCHRONOUS_IO_ALERT or with FILE_SYNCHRONOUS_IO_NONALERT.
For me, it seems to return STATUS_PENDING just like a normal NtReadFile request does on a normal file, but when I tried using NtWaitForSingleObject on the directory, it didn't end properly, and I still don't get all the data... why does this happen?
As far as I know, none of the Windows filesystems support asynchronous query directory calls.
The Win32 APIs never call NtQueryDirectoryFile asnchronously, so support for it is hit-or-miss.
NTFS theoretically supports asynchronous NtQueryDirectoryFile but (as I mentioned) it is not extensively tested so it may not work.
You response indicated that you called WaitForSingleObject on the directory - that's not how the async pattern works in NT - you need to call WaitForSingleObject on the event handle provided as a parameter to NtQueryDirectoryFile.
This update is a result of asking the NTFS developer for more information, he tested this scenario on his machine and it worked for him (on Windows 7).
NtQueryDirectoryFile works well in asynchronous!
pass callback in ApcRoutine, and callback data in ApcContext
asynchronous procedure calls only call when the thread is in alertable state(for example: calling SleepEx(INFINITE, TRUE), WSAaccept)
this program shows how asynchronous NtQueryDirectoryFile work.
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <stdio.h>
#include <winternl.h>
#include <winnt.h>
#define LIST_DIR_SIZE 2000
#define STATUS_NO_MORE_FILES ((NTSTATUS)80000006)
typedef struct _FILE_NAMES_INFORMATION {
ULONG NextEntryOffset;
ULONG FileIndex;
ULONG FileNameLength;
WCHAR FileName[1];
} FILE_NAMES_INFORMATION, * PFILE_NAMES_INFORMATION;
typedef struct {
HANDLE hFile;
OVERLAPPED ol;
DECLSPEC_ALIGN(4) FILE_NAMES_INFORMATION buf[LIST_DIR_SIZE];
IO_STATUS_BLOCK iob;
bool finished;
} LIST_DIR_DATA, * PLIST_DIR_DATA; // my private data
__kernel_entry NTSYSCALLAPI
NTSTATUS
NTAPI
NtQueryDirectoryFile(
_In_ HANDLE FileHandle,
_In_opt_ HANDLE Event,
_In_opt_ PIO_APC_ROUTINE ApcRoutine,
_In_opt_ PVOID ApcContext,
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
_Out_writes_bytes_(Length) PVOID FileInformation,
_In_ ULONG Length,
_In_ FILE_INFORMATION_CLASS FileInformationClass,
_In_ BOOLEAN ReturnSingleEntry,
_In_opt_ PUNICODE_STRING FileName,
_In_ BOOLEAN RestartScan
);
#define NTDLL_extern(s) typedef decltype(&s) s##T;s##T s##F;
#define NTDLL_import(s) s##F = (s##T)GetProcAddress(ntdll, #s);
NTDLL_extern(NtOpenFile);
NTDLL_extern(NtQueryDirectoryFile);
NTDLL_extern(NtClose);
NTDLL_extern(RtlInitUnicodeString);
HMODULE ntdll;
VOID NTAPI callback(
IN PVOID ApcContext,
IN PIO_STATUS_BLOCK IoStatusBlock,
IN ULONG Reserved) {
UNREFERENCED_PARAMETER(Reserved);
PFILE_NAMES_INFORMATION file_info = ((PLIST_DIR_DATA)ApcContext)->buf;
do {
fputws(file_info->FileName, stdout);
putwchar(L'\t');
file_info = (PFILE_NAMES_INFORMATION)((char*)file_info + file_info->NextEntryOffset);
} while (file_info->NextEntryOffset);
fputws(file_info->FileName, stdout);
putwchar(L'\t');
PLIST_DIR_DATA c = (PLIST_DIR_DATA)ApcContext;
if (IoStatusBlock->Information != 0) {
NTSTATUS status = NtQueryDirectoryFileF(
c->hFile,
NULL,
callback,
ApcContext,
&c->iob,
c->buf,
sizeof(c->buf),
FILE_INFORMATION_CLASS(12),
FALSE, NULL, FALSE);
switch (status) {
case STATUS_PENDING:
break;
default:
fputs("warning: status != STATUS_PENDING", stderr);
}
}
else {
c->finished = true;
}
}
BOOL init() {
ntdll = LoadLibraryW(L"NtDLL.dll");
if (ntdll == NULL) {
fputs("LoadLibraryW", stderr);
return FALSE;
}
NTDLL_import(NtQueryDirectoryFile);
NTDLL_import(NtOpenFile);
NTDLL_import(NtClose);
NTDLL_import(RtlInitUnicodeString);
if (NtCloseF != NULL && NtOpenFileF != NULL && NtCloseF != NULL) {
return TRUE;
}
else {
fputs("GetProcAddress", stderr);
return FALSE;
}
}
int main() {
if (init() == FALSE) {
fputs("error: init() failed!", stderr);
return -1;
}
NTSTATUS status;
PLIST_DIR_DATA data = new LIST_DIR_DATA{};
{
OBJECT_ATTRIBUTES ObjectAttributes;
UNICODE_STRING s;
RtlInitUnicodeStringF(&s, L"\\??\\c:\\Windows\\System32");
InitializeObjectAttributes(
&ObjectAttributes,
&s,
OBJ_CASE_INSENSITIVE,
NULL,
NULL);
status = NtOpenFileF(
&data->hFile,
FILE_READ_DATA | FILE_LIST_DIRECTORY, // | FILE_TRAVERSE | SYNCHRONIZE
&ObjectAttributes,
&data->iob,
FILE_SHARE_READ,
FILE_DIRECTORY_FILE); // | FILE_SYNCHRONOUS_IO_NONALERT
}
if (status < 0 || data->hFile == NULL) {
fputs("error: NtOpenFile failed", stderr);
return -2;
}
status = NtQueryDirectoryFileF(
data->hFile,
NULL,
callback,
data,
&data->iob,
data->buf,
sizeof(data->buf),
FILE_INFORMATION_CLASS(12),
FALSE, NULL, FALSE);
switch (status) {
case STATUS_PENDING:
break;
default:
fputs("warning: status != STATUS_PENDING", stderr);
}
for (;data->finished==false;) SleepEx(INFINITE, TRUE); // put main thread into alertable wait
NtCloseF(data->hFile);
FreeLibrary(ntdll);
return 0;
}
if you want UTF-8 output, try this (note: recommand use support UTF-8 terminal)
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <winternl.h>
#include <winnt.h>
#include <crtdbg.h>
#include <cstdio>
#define LIST_DIR_SIZE 200
#define STATUS_NO_MORE_FILES ((NTSTATUS)80000006)
typedef struct _FILE_NAMES_INFORMATION {
ULONG NextEntryOffset;
ULONG FileIndex;
ULONG FileNameLength;
WCHAR FileName[1];
} FILE_NAMES_INFORMATION, * PFILE_NAMES_INFORMATION;
typedef struct {
HANDLE hFile;
OVERLAPPED ol;
DECLSPEC_ALIGN(4) FILE_NAMES_INFORMATION buf[LIST_DIR_SIZE];
IO_STATUS_BLOCK iob;
bool finished;
} LIST_DIR_DATA, * PLIST_DIR_DATA; // my private data
__kernel_entry NTSYSCALLAPI
NTSTATUS
NTAPI
NtQueryDirectoryFile(
_In_ HANDLE FileHandle,
_In_opt_ HANDLE Event,
_In_opt_ PIO_APC_ROUTINE ApcRoutine,
_In_opt_ PVOID ApcContext,
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
_Out_writes_bytes_(Length) PVOID FileInformation,
_In_ ULONG Length,
_In_ FILE_INFORMATION_CLASS FileInformationClass,
_In_ BOOLEAN ReturnSingleEntry,
_In_opt_ PUNICODE_STRING FileName,
_In_ BOOLEAN RestartScan
);
#define NTDLL_extern(s) typedef decltype(&s) s##T;s##T s##F;
#define NTDLL_init(s) s##F = (s##T)GetProcAddress(ntdll, #s);
NTDLL_extern(NtOpenFile);
NTDLL_extern(NtQueryDirectoryFile);
NTDLL_extern(NtClose);
NTDLL_extern(RtlInitUnicodeString);
HMODULE ntdll;
HANDLE heap;
VOID NTAPI callback(
IN PVOID ApcContext,
IN PIO_STATUS_BLOCK IoStatusBlock,
IN ULONG Reserved) {
UNREFERENCED_PARAMETER(Reserved);
PLIST_DIR_DATA c = (PLIST_DIR_DATA)ApcContext;
if (IoStatusBlock->Information){
PFILE_NAMES_INFORMATION file_info = c->buf;
ULONG_PTR length = 0;
ULONG last;
do {
last = file_info->NextEntryOffset;
file_info->FileNameLength /= 2; // wide char length always base of 2 in bytes
length += (
file_info->FileIndex=WideCharToMultiByte(
CP_UTF8, WC_ERR_INVALID_CHARS,
file_info->FileName, file_info->FileNameLength,
NULL, 0,
NULL, NULL)
)+1;
if (file_info->FileIndex == 0) { // FileIndex is how many byte is the UTF-8 string
_RPTF0(_CRT_WARN, "WideCharToMultiByte failed!");
}
file_info = (PFILE_NAMES_INFORMATION)((char*)file_info + file_info->NextEntryOffset);
} while (last);
LPSTR pData = (LPSTR)HeapAlloc(heap, HEAP_NO_SERIALIZE, length), ptr=pData;
if (ptr == NULL) {
_RPTF0(_CRT_ERROR, "HeapAlloc failed!");
return;
}
file_info = c->buf;
do {
last = file_info->NextEntryOffset;
if (WideCharToMultiByte(
CP_UTF8, WC_ERR_INVALID_CHARS,
file_info->FileName, file_info->FileNameLength,
pData, file_info->FileIndex,
NULL, NULL)==0) {
_RPTF0(_CRT_WARN, "WideCharToMultiByte failed!");
}
pData += file_info->FileIndex;
*pData++ = '\n';
file_info = (PFILE_NAMES_INFORMATION)((char*)file_info + file_info->NextEntryOffset);
} while (last);
// use data here
fwrite(ptr, length, 1, stdout);
// use data here
HeapFree(heap, HEAP_NO_SERIALIZE, ptr);
NTSTATUS status = NtQueryDirectoryFileF(
c->hFile,
NULL,
callback,
ApcContext,
&c->iob,
c->buf,
sizeof(c->buf),
FILE_INFORMATION_CLASS(12),
FALSE, NULL, FALSE);
switch (status) {
case STATUS_PENDING:
break;
default:
_RPTF0(_CRT_WARN, "status != STATUS_PENDING");
}
}else{
c->finished = true;
}
}
BOOL init() {
ntdll = LoadLibraryW(L"NtDLL.dll");
if (ntdll == NULL) {
_RPTF0(_CRT_ERROR, "fail to load NtDLL.dll");
return FALSE;
}
NTDLL_init(NtQueryDirectoryFile);
NTDLL_init(NtOpenFile);
NTDLL_init(NtClose);
NTDLL_init(RtlInitUnicodeString);
if (NtCloseF != NULL &&
NtOpenFileF != NULL &&
NtCloseF != NULL &&
(heap = HeapCreate(HEAP_NO_SERIALIZE, 4096,0))!=NULL
){
return TRUE;
}
else {
_RPTF0(_CRT_ERROR, "failed to load function and create heap");
return FALSE;
}
}
int main() {
if (init() == FALSE) {
_RPTF0(_CRT_ERROR, "init failed");
return -1;
}
SetConsoleCP(CP_UTF8);
NTSTATUS status;
PLIST_DIR_DATA data = new LIST_DIR_DATA{};
{
OBJECT_ATTRIBUTES ObjectAttributes;
UNICODE_STRING s;
RtlInitUnicodeStringF(&s, L"\\??\\c:\\Users");
InitializeObjectAttributes(
&ObjectAttributes,
&s,
OBJ_CASE_INSENSITIVE,
NULL,
NULL);
status = NtOpenFileF(
&data->hFile,
FILE_READ_DATA | FILE_LIST_DIRECTORY, // | FILE_TRAVERSE | SYNCHRONIZE
&ObjectAttributes,
&data->iob,
FILE_SHARE_READ,
FILE_DIRECTORY_FILE); // | FILE_SYNCHRONOUS_IO_NONALERT
}
if (status < 0 || data->hFile == NULL) {
_RPTF0(_CRT_ERROR, "NtOpenFile failed!");
return -2;
}
status = NtQueryDirectoryFileF(
data->hFile,
NULL,
callback,
data,
&data->iob,
data->buf,
sizeof(data->buf),
FILE_INFORMATION_CLASS(12),
FALSE, NULL, FALSE);
switch (status) {
case STATUS_PENDING:
break;
default:
_RPTF0(_CRT_WARN, "status != STATUS_PENDING");
}
for (;data->finished==false;) SleepEx(INFINITE, TRUE); // put main thread into alertable wait
if (NtCloseF(data->hFile)<0) {
_RPTF0(_CRT_ERROR, "NtClose failed!");
}
if (FreeLibrary(ntdll) == FALSE) {
_RPTF0(_CRT_WARN, "failed to Free libary");
}
if (HeapDestroy(heap) == FALSE) {
_RPTF0(_CRT_WARN, "fail to destroy heap");
}
}

Resources