I had sort of an odd idea and was wondering whether it would be possible. Here's a rough outline of my plan.
Scenario: An application loads and interprets values from a config file at startup. I want to fuzz the application via the config file, without rewriting the config file.
Note: The config file is closed later on in the program, and the function that opens the config file is used to open various other files, so I do not want to hook this function. While SetKMode() and SetProcPermissions() are used here, answers that apply to Windows in general are just as helpful as Windows CE answers.
Plan:
Attain debug privileges over this process via SetKMode() and SetProcPermissions and attach a debugger via DebugActiveProcess()
Break after the function that loads the file returns
Create a temporary modified version of the file and open it in the parent process
Use VirtualAlloc() to allocate space for the FILE structure in the debugee
Transfer the entire FILE structure for the temporary file to the debugee using WriteProcessMemory()
Swap the pointer for the config file loaded by the debuggee to the pointer for the temporary file
Allow the debugee to run the file
Before the debugee closes the file, copy the old pointer for the original config file back to the new pointer so that it closes the correct file
Would the debugger be able to read the file? Would the parent be able to close the file after it's finished?
Edit:
Transferring the old pointer back to the debugee every time it tries to close the file no longer seems like a good solution after some RE, so on top of my current question I have an additional question: Would the debugee be able to close the file the debugger opened? Would that be a problem? And would the fact that the original file isn't closed properly be a problem?
Edit:
Sorry I'm a dummy who forgot that if I'm going through the trouble of injecting all this I can just inject a new filename and swap the pointer long before the call to fopen.
Assuming the entire file is loaded into memory and then parsed, I would hook whatever function loads the file data into memory, use a conditional to check the filename so you're only executing your code after the correct file is loaded into memory by checking the filename. Then I would perform my fuzzing by modifying the file data in memory and then return execution to the target process before the file dats is then parsed. In this manner you aren't touching any file permissions, only memory.
To automate it create a "loader' which executes the target process, injects, executes your hook and then checks for crash or other unwanted behavior.
One of the QIODevice reimplemented open() methods in QFile has a QFileDevice::FileHandleFlag argument. Taking a look at the documentation for it there are two options with contradicting descriptions.
From the QFileDevice documentation:
QFileDevice::AutoCloseHandle – The file handle passed into open() should be closed by close(), the default behavior is that close just flushes the file and the application is responsible for closing the file handle. When opening a file by name, this flag is ignored as Qt always owns the file handle and must close it.
QFileDevice::DontCloseHandle – If not explicitly closed, the underlying file handle is left open when the QFile object is destroyed.
So does Qt auto close files or not and does setting this option actually change anything?
After looking up the Qt source I found the line in QFSFileEngine.cpp:378* that ultimately uses the flag.
QFile::open() can be passed an existing (stdio.h) FILE handler which was not created by Qt and shouldn't be automatically closed by Qt. In contrast files opened by Qt are automatically closed by Qt.
The QFileDevice::FileHandleFlag flag is for the former case and allows the programmer to specify if QFile should auto-close a file ignoring the fact that it was not opened by Qt.
* Search for closeFileHandle if the line number doesn't match.
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?
As the title states:
My program opens a file.
Something comes along and moves that file. Inode should be the same, but name is different.
Close the file, then delete, but its not there anymore
So how can I detect that it has been moved and delete the correct filename?
Any ideas?
You could use inotify to detect a change to the old name (look for the IN_MOVE_SELF event). But if your real goal is simply to delete the file's name, you can just do that (using unlink(2)) immediately after opening the file. Unix file semantics will allow you to keep using the open file, and the data on disk will not actually be deleted until your handle is closed. And then no one will be able to rename the file.
try to access(2) the file before closing it. If you get ENOENT, the file has been moved. Follow the /proc/self/fd/$open_file_number/ symlink to find the new filename using readlink(2).
fstat the open file, stat the name, and compare the results.
But, in common with any any possible check, it is still racy; the name may change meaning after any check you make but before you act upon it. Time to revisit your requirements.
I am not sure how to explain this, so I will give a scenario.
I want to write a program, which will be set as the default program for a file extension. When the program opens, it will output everything in the program. i.e file.txt contains the word hello, and when opened, my program opens and displays the word hello.
The idea is like Notepad. When a text file is opened, the contents are displayed. However, mine will be in a DOS window.
How can I achieve this?
Sorry if there is another question like this somewhere on here, TBH I am not too sure what this is called and thus can't search.
EDIT: My apologies. I am running Windows 7
If you open a file "with" your program (for instance using file type associations or by dragging the file onto the .exe), then the filename of the data file is passed as the command-line parameter to your application.
See:
What are the arguments to main() for?
I want to write a program, which will be set as the default program for a file extension.
See:
How File Associations Work
File Types and File Associations
You will associate your app with file extension and your app will do whatever it has to do.