Question

I have to implement cross view file integrity checker for my University project. For that how do I list the files of a Directory in Kernel Mode??

Was it helpful?

Solution

Your starting point would be ZwCreateFile - which has options such as "FILE_LIST_DIRECTORY".

You will then use ZwQueryDirectoryFile to get the information about the file(s) within that directory.

Make SURE that you are not forgetting to ZwClose after you open something - it's not so critical in a user-mode application that closes again after it's been used. But the kernel doesn't know when a driver stops using a file (or, for that matter, if some other driver has been given that filehandle, and will be using it at some point), so even if your driver is unloaded, files that it opened will remain open until the system restarts - I quite like to "not restart" my systems, and with a good set of drivers, running a machine for more than a year should be possible. If your driver so much as leaks one handle a day, that's 365 handles leaked.

So, the code would look something like this:

HANDLE h;
NTSTATUS status;
OBJECT_ATTRIBUTES oa = { sizeof(OBJECT_ATTRIBUTES), NULL, L"mydir",
                         OPEN_CASE_INSENSITIVE, NULL, NULL };
IO_STATUS_BLOCK iosb = {};

status = ZwCreateFile(&h, FILE_LIST_DIRECTORY, &oa, &iosb, NULL, 
                      FILE_ATTRIBUTE_NORMAL, FILE_OPEN, FILE_DIRECTORY_FILE,
                      NULL, 0);
if (status != STATUS_SUCCESS)
{
   ... do something... 
   return errorcode;
}
else
{
    FILE_DIRECTORY_INFORMATION info;
    for(;;)
    {
        status = ZwQueryDirectoryFile(h, NULL, NULL, &iosb, &info, sizeof(info), 
                                      FileDirectoryInformation, TRUE, L"*.*",
                                      FALSE);
        if (status != STATUS_SUCCESS) 
        {
            ... check error code and perhaps print if unexpected error ... 
            break;
        }
        ... do soemthing with `info` ... 
    }
}
ZwClose(h);

This is just a "rough sketch". I don't have a setup to compile this right now, and I may have missed something important. But it should give you some idea. There are LOTS of optional parameters and optional choices here, and some I've "guessed" what you'd want, but I think I've made reasonable choices. There may be details missing that make this not work, but as a rough starting point, it should give you an idea at least.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top