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

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.

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:
You query the file name and security context
You read the file contents
Alternatively hash the file with a SHA256 to see if it matches in your AV database for example
You check if the file is digitally signed, also part of your check
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
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.

Related

Does Windows Filter Manager have any restrictions on modifying file reads?

If I understand right, through Windows' Filter Manager we can write a filter to make an operation to read one file instead actually read another. So for example, if you've added hooks to monitor certain DLLs and an attacker attempts to load a fresh DLL from source, I'm trying to figure out if I can use a mini-filter to have that attempt actually result in loading a copy of that DLL in another folder.
Is Filter Manager capable of facilitating that outcome? If so, is there any limitation on, for example, affecting read operations against a protected directory such as the System32 folder?

How to let Windows know that a file is "being used" by my application?

I'm making a simple VB.net application, which basically asks the user for multiple files and later it will need to access the selected files and modify them.
Right now, I'm saving the full paths of the selected files, and in the future, the application will iterate through each path, open the file from such path, and modify it.
The problem with that is that the user could select a file (so the full path is saved) and then they delete or move the file before my application modifies it.
Normally, I'd throw an error saying "File not found", but I'm under the impression that Windows had a feature that would disallow you from deleting/moving/renaming a file because "a program was using it" - which is a feature that would fit way better for my application.
I'm not very advanced with VB.NET, but I suppose that if I "open" a file using my application (with some IO thing), the feature I mentioned earlier would indeed trigger and the user would be unable to modify the file because it is "opened" by my application.
However, since my only desire is to "reserve" files, it seems to be quite wasteful to actually open them when I don't really need to (yet). Is there a way to tell Windows I need a certain file to be intact?
Opening files (with specifying desired sharing mode) is the way to do that.
I don't believe there is anything really wrong with opening multiple files (also you still will not be able to do anything for cases like removing of removable drive). In old times there were restrictions on number of opened files per process, but I it no longer practical limitation - Pushing the Limits of Windows: Handles
There is an easy solution: open each file in exclusive mode.
It should look like this:
Sub test()
Dim FS = System.IO.File.Open("path", IO.FileMode.Open, IO.FileAccess.ReadWrite, IO.FileShare.None)
End Sub
But beware: You have opened a file handle and if you code responsible for closing files fails without terminating the application files will still be locked for very long (till app shuts down).
You can use a using clause or a try/catch/finally clause - I don't know enough about your program to recommend anyone.

NSFileCoordinator correct usage

when writing a file using NSFileCoordinator i need to specify the correct NSFileCoordinatorWritingOptions. Although they are explained in detail, I am not sure when to use which one. The available options are:
NSFileCoordinatorWritingForDeleting
NSFileCoordinatorWritingForReplacing
NSFileCoordinatorWritingForMoving
NSFileCoordinatorWritingForMerging
For example, what option is the correct one if I want to create a file (a plist for example)?
Wich one when I modify a file?
Can someone explain the NSFileCoordinatorWritingOptions for a better understanding?
I agree, documentation is not complete on that front, and hard to understand. And no sample code is available even for basic operations like these.
I try to think of these options in the perspective of other apps that have that specific file open, that helps getting the whole picture.
Pass no option (0) to simply update the file and notify others of your changes.
Let's say you are deleting a file that TextEdit currently displays, by providing the NSFileCoordinatorWritingForDeleting option, you're telling TextEdit to close the file as it does not exist anymore (or it could propose to save it to another place if it's in memory). It acts because of deletion.
If you're overwriting a file (as opposed to updating a file), you want about that same behavior for other apps. That's NSFileCoordinatorWritingForReplacing.
NSFileCoordinatorWritingForMoving says other apps to track the file to it's new location, so that it can be later updated.
NSFileCoordinatorWritingForMerging asks other processes to first commit their changes so that you can then merge your own changes with those.
To answer your question, you should use NSFileCoordinatorWritingForReplacing when creating a new file (even when no file exists, as it was to appear in the mean time from another app, you'd be replacing it with your own, unrelated contents). And NSFileCoordinatorWritingForMerging should be used when updating an existing file with new data, as it allows integrating the latest changes to that file immediately (instead of doing later with conflict resolution).

Is it acceptable to leave files in user temp folder?

I'm working on an application that generates a set of bitmaps and then loads them into a form for a user to pick from.
The bitmaps are generated from a small vector library which the user can add to. The code now creates the files and then deletes them immediatelyafter use, only to have to generate them again (making the UI take seconds to load) next time the user opens the UI.
So what I'm wondering is, is it okay to leave my bitmaps in the user temp folder "forever", and regenerate them if they are not in the folder? I can't expect to be able to store the images in the application directory, due to possible permission issues, and like I said, I can't prepopulate the files since the user can add more.
Ideally you should generate any temporary data into the RAM rather to the file system.
It is acceptable to depend on temporary files if you can make sure that your application is storing only a limited amount of such files per user. Any temporary files can be left behind on unexpected crashes/power offs no matter what your code does. You therefore need to implement a mechanism that will delete any stale files created by the same application in a previous session - presumably during its next start up.
Assuming such a safety mechanism, intentionally leaving behind temporary files when the application exits sounds like a non-standard but reasonable "cache".
Caveat: the next version of your application may need a slightly different file format, and should detect, delete and regenerate any files in a mismatched format based on some simple versioning scheme to avoid cross-build dependences.

Registry vs. INI file for storing user configurable application settings [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
I'm a new Windows programmer and I'm not sure where I should store user configurable application settings. I understand the need to provide a user friendly means for the user to change application settings, like an Edit | Settings form or similar. But where should I store the values after the user hits the Apply button on that form?
What are the pros and cons of storing settings in the Windows registry vs. storing them in a local INI file or config file or similar?
Pros of config file:
Easy to do. Don't need to know any Windows API calls. You just need to know the file I/O interface of your programming language.
Portable. If you port your application to another OS, you don't need to change your settings format.
User-editable. The user can edit the config file outside of the program executing.
Pros of registry:
Secure. The user can't accidentally delete the config file or corrupt the data unless he/she knows about regedit. And then the user is just asking for trouble.
I'm no expert Windows programmer, but I'm sure that using the registry makes it easier to do other Windows-specific things (user-specific settings, network administration stuff like group policy, or whatever else).
If you just need a simple way to store config information, I would recommend a config file, using INI or XML as the format. I suggest using the registry only if there is something specific you want to get out of using the registry.
Jeff Atwood has a great article about Windows' registry and why is better to use .INI files instead.
My life would be a heck of a lot easier if per-application settings were stored in a place I could easily see them, manipulate them, and back them up. Like, say... in INI files.
The registry is a single point of failure. That's why every single registry editing tip you'll ever find starts with a big fat screaming disclaimer about how you can break your computer with regedit.
The registry is opaque and binary. As much as I dislike the angle bracket tax, at least XML config files are reasonably human-readable, and they allow as many comments as you see fit.
The registry has to be in sync with the filesystem. Delete an application without "uninstalling" it and you're left with stale registry cruft. Or if an app has a poorly written uninstaller. The filesystem is no longer the statement of record-- it has to be kept in sync with the registry somehow. It's a total violation of the DRY principle.
The registry is monolithic. Let's say you wanted to move an application to a different path on your machine, or even to a different machine altogether. Good luck extracting the relevant settings for that one particular application from the giant registry tarball. A given application typically has dozens of settings strewn all over the registry.
There's one more advantage to using an INI file over the registry which I haven't seen mentioned:
If the user is using some sort of volume/file based encryption, they can get the INI file to be encrypted pretty easily. With the registry it will probably be more problematic.
According to the documentation for GetPrivateProfileString, you should use the registry for storing initialisation information.
However, in so saying, if you still want to use .ini files, and use the standard profile APIs (GetPrivateProfileString, WritePrivateProfileString, and the like) for accessing them, they provide built-in ways to automatically provide "virtual .ini files" backed by the registry. Win-win!
There's a similar question here that covers some of the pros and cons.
I would suggest not using the registry unless your application absolutely needs it. From my understanding, Microsoft is trying to discourage the use of the registry due to the flexibility of settings files. Also, I wouldn't recommend using .ini files, but instead using some of the built-in functionality to .Net for saving user/app settings.
Use of an ini file, in the same directory as the application, makes it possible to back it up with the application. So after you reload your OS, you simply restore the application directory, and you have your configuration the way you want it.
I agree with Daniel. If it's a large application I think I'd do things in the registry. If it's a small application and you want to have aspects of it user-configurable without making a configuration form, go for a quick INI file.
I usually do the parsing like this (if the format in the .ini file is option = value, 1 per line, comments starting with #):
static void Parse()
{
StreamReader tr = new StreamReader("config.ini");
string line;
Dictionary<string, string> config = new Dictionary<string, string>();
while ((line = tr.ReadLine()) != null)
{
// Allow for comments and empty lines.
if (line == "" || line.StartsWith("#"))
continue;
string[] kvPair = line.Split('=');
// Format must be option = value.
if (kvPair.Length != 2)
continue;
// If the option already exists, it's overwritten.
config[kvPair[0].Trim()] = kvPair[1].Trim();
}
}
Edit: Sorry, I thought you had specified the language. The implementation above is in C#.
As Daniel indicated, storing configuration data in the registry gives you the option to use Admin Templates. That is, you can define an Admin Template, use it in a Group Policy and administer the configuration of your application network-wide. Depending on the nature of the application, this can be a big boon.
The existing answers cover a lot of ground but I thought I would mention one other point.
I use the registry to store system-wide settings. That is, when 2 or more programs need the exact same setting. In other words, a setting shared by several programs.
In all other cases I use a local config file that sits either in the same path as the executable or one level down (in a Configuration directory). The reasons are already covered in other answers (portable, can be edited with a text editor etc).
Why put system-wide settings into the registry? Well, I found that if a setting is shared but you use local config files you end up duplicating settings. This may mean you end up needing to change a setting in multiple places.
For example, say Program A and Program B both point to the same database. You can have a "system-wide" registry setting for the connection string. If you want to point to a different database, you can change the connection string in one place, and both programs will now run against the other database.
Note - there is no point in using the registry in this way if two or more programs don't need to use the same values. Such as, Program A and Program B both needing a database connection string that may be the same, but not always. For example, I want Program B to now use a test database but Program A should carry on using a production database.
With the above example, you could have some local configuration override system-wide settings but it may start getting overly complicated for simple tasks.
The registry is optimized for quick access and easy update, and it's the only way to do certain Windows-specific things like associating with an extension. And you can ignore the argument about deleting a single directory to uninstall your program - Windows Vista won't let you modify files in the Program Files directory, so your config will need to go in a different folder anyway.
There's a general guideline for Windows programming - do things the way Microsoft expects you to, and your life will be a lot easier.
That said, I can see the appeal of the INI file, and I wouldn't blame anyone for considering it.
There is one drawback to ini or config files and that is locating them if the user has the option to select where the program is installed.
Other disadvantage of using the registry is that it is a pain if you are working in a mixed environment of 32 and 64 bit applications, as the system call for accessing the registry will randomly(*) add \Wow6432Node\ to your registry path making you crazy while debugging.
(*of course not randomly, but very easy to get lost)
Advantages:
Replacement for a large number of configuration files.
Common administrative functions at a central point.
Almost any data can be saved by applications / drivers.
In contrast to configuration files, code sequences can even be saved.
Access faster than files because the database is indexed.
Access can be logged using the RegMon utility
Disadvantages:
Difficult to work with in the absence of graphical configuration programs.
Direct changes using the registry editor can create inconsistent states produce.
Incomplete uninstallers leave “reminiscences” in the registry Cause problems, e.g. with a new installation.
Installed applications are difficult to export to other PCs.
Chronically poorly documented.
Proprietary structure, therefore not suitable for standard DB access (e.g. SQL)
Computer-specific, therefore not portable to other computers.
Insufficient protection of the registry: depends on the configuration.

Resources