Directory relative ZwCreateFile

核能气质少年 提交于 2020-01-15 03:28:09

问题


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??


回答1:


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.



来源:https://stackoverflow.com/questions/17168129/directory-relative-zwcreatefile

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!