Running a file whose handle is opened(C++ winapi) - c++

I included a exe file as a resource in my c++ application and i need to run it, but i need to restrict it's access alot so the user can't copy it.
I need to keep it's handle opened so external programs can't access it, and because i used FILE_FLAG_DELETE_ON_CLOSE as a flag, so it will delete if my application gets killed.
But because of that i can't run it with CreateProcess() or WinExec().
I know it sounds weird, but i have a good reason.I need those to protect the executable of a game from a dll-injection cheat, and i don't have the code of that exe.

Since you can't lock the entire file, lock a very small part with LockFile. You'll need to find a byte range that Windows doesn't use. You might achieve this by adding a dummy resource to the EXE. (This does not require source code).

Related

Using temporary files safely

There is a static library I use in my program which can only take filenames as its input, not actual file contents. There is nothing I can do about the library's source code. So I want to: create a brand-new file, store data to being processed into it, flush it onto the disk(?), pass its name to the library, then delete it.
But I also want this process to be rather secure:
1) the file must be created anew, without any bogus data (maybe it's not critical, but whatever);
2) anyone but my process must not be able read or write from/to this file (I want the library to process my actual data, not bogus data some wiseguy managed to plug in);
3) after I'm done with this file, it must be deleted (okay, if someone TerminateProcess() me, I guess there is nothing much can be done, but still).
The library seems to use non-Unicode fopen() to open the given file though, so I am not quite sure how to handle all this, since the program is intended to run on Windows. Any suggestions?
You have a lot of suggestions already, but another option that I don't think has been mentioned is using named pipes. It will depend on the library in question as to whether it works or not, but it might be worth a try. You can create a named pipe in your application using the CreateNamedPipe function, and pass the name of the pipe to the library to operate on (the filename you would pass would be \\.\pipe\PipeName). Whether the library accepts a filename like that or not is something you would have to try, but if it works the advantage is your file never has to actually be written to disk.
This can be achieved using the CreateFile and GetTempFileName functions (if you don't know if you can write to the current working directory, you may also want to use , GetTempPath).
Determine a directory to store your temporary file in; the current directory (".") or the result of GetTempPath would be good candidates.
Use GetTempFileName to create a temporary file name.
Finally, call CreateFile to create the temporary file.
For the last step, there are a few things to consider:
The dwFlagsAndAttributes parameter of CreateFile should probably include FILE_ATTRIBUTE_TEMPORARY.
The dwFlagsAndAttributes parameter should probably also include FILE_FLAG_DELETE_ON_CLOSE to make sure that the file gets deleted no matter what (this probably also works if your process crashes, in which case the system closes all handles for you).
The dwShareMode parameter of CreateFile should probably be FILE_SHARE_READ so that other attempts to open the file will succeed, but only for reading. This means that your library code will be able to read the file, but nobody will be able to write to it.
This article should give you some good guidelines on the issue.
The gist of the matter is this:
The POSIX mkstemp() function is the secure and preferred solution where available. Unfortunately, it is not available in Windows, so you would need to find a wrapper that properly implements this functionality using Windows API calls.
On Windows, the tmpfile_s() function is the only one that actually opens the temporary file atomically (instead of simply generating a filename), protecting you from a race condition. Unfortunately, this function does not allow you to specify which directory the file will be created in, which is a potential security issue.
Primarily, you can create file in user's temporary folder (eg. C:\Users\\AppData\Local\Temp) - it is a perfect place for such files. Secondly, when creating a file, you can specify, what kind of access sharing do you provide.
Fragment of CreateFile help page on MSDN:
dwShareMode
0 Prevents other processes from opening a file or device
if they request delete, read, or write access.
FILE_SHARE_DELETE Enables subsequent open operations on a file or device to
request delete access. Otherwise, other processes cannot open the file or device if they
request delete access. If this flag is not specified, but the file or device has been opened for delete access, the function fails. Note: Delete access allows both delete and rename operations.
FILE_SHARE_READ Enables subsequent open operations on a
file or device to request read access. Otherwise, other processes cannot open the file or device if they request read access. If this flag is not specified, but the file or device has been opened for read access, the function fails.
FILE_SHARE_WRITE Enables subsequent open operations on a file or device to request
write access.
Otherwise, other processes cannot open the file or device if they
request write access.
If this flag is not specified, but the file or device has been opened
for write access or has a file mapping with write access, the function
fails.
Whilst suggestions given are good, such as using FILE_SHARE_READ, FILE_DELETE_ON_CLOSE, etc, I don't think there is a completely safe way to do thist.
I have used Process Explorer to close files that are meant to prevent a second process starting - I did this because the first process got stuck and was "not killable and not dead, but not responding", so I had a valid reason to do this - and I didn't want to reboot the machine at that particular point due to other processes running on the system.
If someone uses a debugger of some sort [including something non-commercial, written specifically for this purpose], attaches to your running process, sets a breakpoint and stops the code, then closes the file you have open, it can write to the file you just created.
You can make it harder, but you can't stop someone with sufficient privileges/skills/capabilities from intercepting your program and manipulating the data.
Note that file/folder protection only works if you reliably know that users don't have privileged accounts on the machine - typical Windows users are either admins right away, or have another account for admin purposes - and I have access to sudo/root on nearly all of the Linux boxes I use at work - there are some fileservers that I don't [and shouldn't] have root access. But all the boxes I use myself or can borrow of testing purposes, I can get to a root environment. This is not very unusual.
A solution I can think of is to find a different library that uses a different interface [or get the sources of the library and modify it so that it]. Not that this prevents a "stop, modify and go" attack using the debugger approach described above.
Create your file in your executable's folder using CreateFile API, You can give the file name some UUID, each time its created, so that no other process can guess the file name to open it. and set its attribute to hidden. After using it, just delete the file .Is it enough?

How to create virtual file system that file path can be accessed same as disk

I need to create FileSystem type of thing in memory or on disk, which can be accessed same as file on disk, which path is can be used in function like fopen(),etc.
Details:
I am using AddFontResourceEx function to load font in application. Since this function require file path so that file need to present on disk. But I've requirement, that the user cannot access/see the font file.
I tried AddFontMemResourceEx function, but the loaded font is not enumable so that user cannot see the font in the application. Also I tried with some library which create VFS, but they work like database, i.e you can create file/directory and access them. But cannot use their file path in AddFontResourceEx or any other function.
Is there exist some way by which I can create a Virtual FileSystem in memory or on disk which can be accessible through my application and I can write/read file on this virtual filesystem created and it's file path can be used by AddFontResourceEx function.
It can't really work. Yes, you can add a "virtual" file system. But either it's visible to user X or it isn't. Access Control on Windows works on a per-user base, not a per-program base. So, if user X can see the font in application A, he can also see it in application B - even if B is Explorer.EXE.
If the user is an administrator, you can't really prevent them from seeing the font file if they're determined enough. They could, for example, reverse engineer your program to figure out how you're generating the file and repeat the process by hand to make their own copy. Or (even if you could somehow tie the file permissions to your process) they could insert their own code into your process to retrieve the file, or to retrieve the font information directly from memory.
If it's good enough to make it difficult for them to see the font file, you could try this:
Create a directory in the temp folder, with write-only permission for the current user and no permissions for anyone else.
Create a sub-directory with a long, complex, cryptographically random name, and with full permission for the current user. (The name should be different each time.)
Write the font file to the sub-directory and load it.
Delete the font file and remove both directories.
The entire process should take only a fraction of a second, which should make it somewhat difficult for the user to override the permissions and retrieve the file. If they use a debugger to single-step through the program then I guess you're out of luck, but as I already pointed out, nothing's going to stop everyone.
Another option, presumably, would be to just use AddFontMemResourceEx and put up with the fact that the font isn't then enumerable. You'd just need to change your code so that wherever it enumerates fonts it adds your font(s) to the list manually.
If you didn't get the right answer, maybe you didn't ask the right question
Your post title mentions "virtual filesystem", but. later, you mention "accesing a font".
"Virtual Filesystems" its an ambiguos term used in several ways.
One common case, means adding devices or networks to an O.S.
In your case, seems like accesing from a an application.
There are several ways ( "libraries" ) to emulate or work with a filesystem.
Some of them work independent of the real filesystem. You work with them, save data in those "virtual" folders & files, and copy data from the real and the virtual one.
Some of them work, as a extension layer, between the real filesystem, and the programming filesystem.
Example: I worked with an application, that required temporally fast I.O. access. Found a library, that when you want to create a folder or save a file in the real filesystem, was done.
Additionally, I could add "virtual drives" that where stored in memory, but, accessed with file system operations. When the application finished, the "hard drives" and their data where erased from memory.
Its seems that your case is similar to my example.
What do you want a "virtual filesystem" library for ?
I have seen onb the web, several libraries, for C++, open source, freeware, and commercial.
It depends what do you want to do, to find out, which library its the better for your case.
Good Luck

Can I load a dll in such a way that it can be deleted while it's loaded?

The title pretty much says it all..
What I'm trying to do is write a tool that will monitor a dll file containing a plugin and when I overwrite it, by recompiling, it should automatically reload it.
I know I can make a copy, load the copy and monitor the original, but I thought there might be a better way..
If I understood it right the dll is completely loaded into memory so there shouldn't be a problem in deleting the file..
No, that's not how Windows works. Loading a DLL merely creates a memory mapped file, nothing is actually read from the file beyond the relocations (if necessary). Not until your code calls an exported function. Which causes a page fault because the code wasn't loaded yet. Now the code gets read from the file into RAM. If space is needed for other processes then the pages simply gets unmapped. Getting reloaded again on the next page fault.
The MMF puts a hard lock on the file. You can only rename it, not overwrite or delete it. That would crash the program. Release the lock with FreeLibrary().
Haven't tried it, I'm not on my Windows machine right now, but I think that Windows locks the file against writing when loading a DLL. You should check that first, can you actually overwrite the DLL (e.g. by compiling a new version) or does the compiler complain with "permission denied".
Otherwise I suppose you could use the file change notification API to achieve your goal.

MFC C++: how can I lock a file to be used only in my process?

I'd like to lock a couple of files to be only used by my process, denying any other application access to these files while my program is running. Of course I know that I can get exclusive access to a file using Createfile, but my application works differently, I read a bunch of filenames froma config, and process these files with a Lib linked to my application, i.e. one of the functions in my lib accesses the files, but I don't get a filoehandle or something similar in return.
So what I want to acchieve is that while my app is processing these files, no other application can modify them. Is this somehow possible? I am developing using MFC in Visual Studio 8.
I've never used them, but LockFile/LockFileEx docs say: Locks the specified file for exclusive access by the calling process.
You need cooperation from the OS, because that's the only way to influence other processes.
The OS requires that you use handles to refer to files. It's really the only practical way for the OS; using pathnames would be far too complex. So, you will need to call CreateFile. At that point, just request exclusive access.
Why doens't the CreateFile()'s exclusive flag achieve this? It looks like you don't need anything fancy. If your library opens the file with CFile::shareDenyRead and CFile::shareDenyWrite, no other process can read your files as long as they are open by your library.
What you're asking can't be done.
Because exclusive access is granted per handle, not per process, if you open a file with exclusive access once, every subsequent attempt to open it will fail, even if it is from the same process. Exclusive access here means your handle is the only valid one, not that only your process can access it.
So even if you lock a file, your lib won't be able to open it, so it's useless to you. The only way is to lock a file and pass the handle to your lib, which you can't do because your lib wants a filename. Likewise you can't lock the file once it's open by the lib because it won't give you the handle. If you don't have access to the source code of the lib, you're stuck.
You possibly could try something with user permissions, having you're process run from it's own user account and changing the ownership of the files you're about to modify and then changing it back when you're done.

modify an open file c++

Under Windows is there a way to modify a file/executable opened by another process using c++?
Is there a way to modify an open executable in windows?
No.
Is there a way to modify an open file in windows using c++?
Yes. If it has been opened with the proper share permissions. See http://msdn.microsoft.com/en-us/library/aa363858(VS.85).aspx FILE_SHARE_WRITE
It may be possible but perhaps not easy to achieve. You need inject thread in destination process and know PE format for correctly edit opened file and modify it.
All information is on web.
Good Luck.
I find this freeware tool, it proposes to unlock files and folders.
The OS holds the executable file open for read-only sharing as long as it's running, so there's no way to modify it directly. You can, however, open it for reading (if you specify read-sharing in your CreateFile call), and make a modified copy of it, while it's running.
I don't know if that's what you had in mind, but if it's your own program you're doing this to, you can start the new copy and have it pick up where the previous one left off... not straightforward, but not all that difficult either.