windowsdriverminifilterwdm

What is a "context" used for in regards to a Windows NT MiniFilter Driver?


I built a very simple minifilter driver as part of a lesson on minifilters. I've also read the minifilter documentation that Microsoft provides which is in the form of a PDF doc, as well as this reference. These guides explain how to set up a context and an instance. However, they do not explain why one would use a context and/or instance and what they are for. My very small filter driver used NULL for both context and instance and still operates, so I am wondering the use-case for these constructs.


Solution

  • There are many reasons why you would want to use contexts for files, volumes etc.. Certainly filters and even file-systems could operate without them, but the performance would be really bad.

    Imagine this scenario: you are an AV (AntiVirus) and want to scan some files to check if they contain malicious code or not. You register your minifilter and callbacks and now you are being called and you need to make a decision on a file as it is opened.

    There are a few steps involved:

    1. You query the file name and security context
    2. You read the file contents
    3. Alternatively hash the file with a SHA256 to see if it matches in your AV database for example
    4. You check if the file is digitally signed, also part of your check
    5. You parse the file's PE header if it has one to see what kind of file or executable it is to help you in your decision
    6. You apply your policy on the file based on all the information above

    Now let's assume the file is clean and goes away. If you cannot hold on to the information that you just learnt about the file, the next time the file is opened you will have to re-do it all over again. Your performance will suck, and your OS will crash and burn slowly to the ground.

    This is where contexts come in handy.

    Now that you have all this information about the file, you store all of it in your context that is then associated with this file. Next time you see the file you simply query its context and have all the information you need.

    Of course some things will need to be updated, for example if you notice the file has been changed then you mark it as dirty and update as needed on the next Create or Cleanup callback.

    Alternatively you could use a cache, where after the file is closed for good and the minifilter wants to free the context you have associated with the file you can save it yourself. Now, the next time the file is opened you look for the context of the file ( NTFS support unique file ids for files ) and just associated it with your file and know immediately everything you need to know about that file

    This is only one usage, but now you can think for yourself of many more scenarios where they are useful.