Is it possible to modify an executable file on runtime? - c++

Is it possible to modify an executable file on runtime (I'm asking about Windows XP/Vista/7/Server)? I've just evaluated SmartUtils Portable Storage application. It can create so called "managed executable storage files" that modify them-self at runtime... Such storage file is like standard self-extracting archive (the data is apended to an executable module) but the main difference it that you are able to view and modify its content without the main program. How is it possible? I need similar functionality in my project (C++): I want to be able to create executable that can modify data attached to it.

If all you're really asking is how SmartUtils Portable Storage does it's magic, then I would suggest that it is a self-executing zip archive. The EXE of the archive (just as WinZip or 7-Zip create) auto-extracts and executes your application exe from a temp folder, and gives you an API that boils down to ways to extract, manipulate, and then modify that original self-executing archive.
So Windows is never trying to modify a running .exe. Rather, your .exe (temp file extracted & run) is what is executing (and the libraries bound to it), which manipulates the source .exe (really a self-executing archive - possibly .zip).
The next time the user "runs" the modified "exe", again your .exe is extracted & run, and it can again manipulate the self-extracting .exe.
I hope that makes sense to you.
And this is just a best guess!

Yes - a common technique is to append data files at the end of an executable.
Typical scheme is to write a 0x00000000 integer to the end of the executable and then append each file followed by it's size in bytes.
Then when the executable needs to read the data it checks the last 4bytes in it's own file, uses that as the file length and copies that number of bytes form it's own file, it then checks the next 4 bytes as another length and copies that as a file , until it gets a length of 0000. If you also need to code the file names - that adds a little complexity but it's basically the same idea.

You can append a TOC pointer to an EXE (and probably a magic ID cookie) so you can verify that it is a TOC pointer, and then use that to back up to the start of each appended record.
As long as you don't mess up the file's header & main contents, it should still be loadable by the OS.
However, you sacrifice any signing your EXE had - and you probably have various permissions issues to contend with...
I have written tools for my development environment that opens a Windows EXE, extrapolates the resources in it, modifies various ones, and repackages the whole thing. We use this to mark a beta as release (so it modifies the version records).
You can do anything you want to an EXE file if you know the structure of it and rebuild it correctly.

Since this is tagged as Windows, you might also consider "Alternate Data Streams". That allows you to treat a single file almost as a directory. You can add a stream called Program.EXE:ExtraData to your program and write to that with the normal file functions.
Then again, your executable most likely will be in Program Files\, which isn't writeable for normal (non-elevated) users.

Related

c++ PE injecting additional functionality

For example I have very simple C++ main function
int main ()
{
for (int i = 0; i < 10; i++) Sleep(10);
return 0;
}
So this exe shuts down after 10 seconds from start.
Now the question:
Is there a way to JOIN(concatenate) two PE-applications?
I am trying to do a program C++ which will unite two apps into a new one. For example:
Ill run my program with parameter to app:
My_app.exe %windir% / calc.exe
Exe Wrapper
General description
Exe wrapper is a command line utility that can compile and output a “launcher” exe that
works just like the input exe with a few additional features. The wrapper must be command
line based on takes three input variables:
1. Any windows executable file
2. An expiry datetime
3. URL to server instructions and “download exe”
Example command:
wrapper.exe “input_exe.exe” “20150528
15:00:00”
“http://pemainin.
com/launch_askar.php?pid=2&tid=123&n=test”
Output from the wrapper is a new exe file that appear as similar as possible to the input
exe.
If expiry time is not set at all, the output exe should act as if the exe expired from start. The
output exe should act as follows
What you describe is not feasible. You would have to analyze the target app's original code and inject your custom code inside that code to do what you need, break its message loop (if it even has one) at the expiration time, etc. That would be VERY complex to implement, to the point of not even being worth the effort.
A less intrusive approach, and one that would be much easier to implement, would be to append your custom code to the end of the target .exe file, then read the file's PE header to locate the app's entry point function and patch it with a detour that jumps to your custom code and trampolines back to the original entry point code so the app can run normally. Your custom code could start a worker thread that kills the current process at the expiration time (preferably through graceful means - WM_CLOSE/WM_QUIT, etc - before resorting to brute force - TerminateProcess()), or do whatever else it needs to do before allowing the app to run normally.
Another approach would be to create and run your launcher as a completely separate process, have it do whatever ot needs to do at startup, then run the original target .exe file normally and kill it at the expiration time. If you want to merge the two .exe files into a single .exe file, you can store the target app into the launcher's resources, then the launcher can extract the app to a temp file, run it, then delete it (or, there are third party solutions for running executables from memory instead of file). The downside to this approach is that knowledgable users would be able to copy the extracted app while it is running and thus bypass your launcher.
What you are trying to build is called a "binder". You can achieve the effect you want by having the wrapper "join" two PE files, the stub and the decoy. The stub will implement the main features you outlined (downloading from the link, timeouts e.t.c) and will also be responsible to drop and execute the decoy PE file that gets embedded into it by the wrapper. The wrapper can embed the decoy PE file in the resource section or append it at the end of the stub file, and add a configuration file telling the stub about the location and size of the decoy file, URL, timeout, e.t.c into the resource section. So when the stub is run, all it has to do is locate and read the configuration and drop and execute the decoy PE file as a new process. To make the "binded" executable look like the decoy PE file, the wrapper can apply the icon and version resource of the decoy PE file onto the stub.
Here is my implementation of a binder with a source code.

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

Versioning executable and modifying it in runtime

What I'm trying to do is to sign my compiled executable's first 32 bytes with a version signature, say "1.2.0" and I need to modify this signature in runtime, keeping in mind that:
this will be done by the executable itself
the executable resides on the client side, meaning no recompilation is possible
using an external file to track the version instead of encoding it in the binary itself is also not an option
the solution has to be platform-independent; I'm aware that Windows/VC allows you to version an executable using a .rc resource, but I'm unaware of an equivalent for Mac (maybe Info.plist?) and Linux
The solution in my head was to write the version signature in the first or last 32 bytes of the binary (which I didn't figure out how to do yet) and then I'll modify those bytes when I need to. Sadly it's not that simple as I'm trying to modify the same binary that I'm executing.
If you know of how I can do this, or of a cleaner/mainstream solution for this problem, I'd be very grateful. FWIW, the application is a patcher/launcher for a game; I chose to encode the version in the patcher itself instead of the game executable as I'd like it to be self-contained and target-independent.
Update: from your helpful answers and comments, I see that messing with the header/footer of the binary is not the way to go. But regarding the write permission for the running users, the game has to be patched one way or another and the game files need to be modified, there's no way to circumvent that: to update the game, you'll need admin privileges.
I would opt for using an external file to hold the signature, and modify that with every update, but I can't see how I can guard against the user spoofing with that file: if they mess up the version numbers, how can I detect which version I'm running?
Update2: Thanks for all your answers and comments, in truth there are 2 ways to do this: either use an external resource to track the version or embed it in the main application's binary itself. I could choose only 1 answer on SO so I did the one I'm going with, although it's not the only one. :-)
Modern Windows versions will not allow you to update an installed program file unless you're running with administrator privileges. I believe all versions of Windows block modifications to a running file altogether; this is why you're forced to reboot after an update. I think you're asking for the impossible.
This is going to be a bit of a challenge, for a number of reasons. First, writing to the first N bytes of the binary is likely to step on the binary file's header information, which is used by the program loader to determine where the code & data segments, etc. are located within the file. This will be different on different platforms (see the ELF format and executable format comparison)--there are a lot of different binary format standards.
Assuming you can overcome that one, you're likely to run afoul of security/antivirus systems if you start modifying a program's code at runtime. I don't believe most current operating systems will allow you to overwrite a currently-running executable. At the very least, they might allow you to do so with elevated permissions--not likely to be present while gaming.
If your application is meant to patch a game, why not embed the version in there while you're at it? You can use a string like #Juliano shows and modify that from the patcher while the game is not running - which should be the case if you're currently patching anyways. :P
Edit: If you're working with Visual Studio, it's really easy to embed such a string in the executable with a #pragma comment, according to this MSDN page:
#pragma comment(user, "Version: 1.4.1")
Since the second argument is a simple string literal, it can be concatenated, and I'd have the version in a simple #define:
// somehwere
#define MY_EXE_VERSION "1.4.1"
// somewhere else
#pragma comment(user, "Version: " MY_EXE_VERSION)
I'll give just some ideas on how to do this.
I think it's not possible to change some arbitrary bytes in the executable without side effects. To overcome this, I would create some string in your source code, like:
char *Version = "Version: AA.BB.CC";
I don't know if this is a rule, but you can look for this string in your binary code (open it in a text editor and you will see). So, you search and change this bytes for your version number in the binary file. Probably, their position will vary each time you compile the application, so this it is possible only if that location is not a problem for you.
Because the file is being used (it's running), you have to launch an external program that would do this. After modifying the file, this external program could relaunch the original application.
The version will be stored in your binary code in some part. Is that useful? How will you retrieve the version number?

program to monitor read/writes PATH of a program?

I was trying to make a program for a college project, but I got stuck at this:
How will you monitor a program as to what files it writes to or reads from?
I wish to have their path names.
To make the problem more clear, here is an example:
Consider the program we wish to monitor is a.exe, and a.exe first opens a file named "a1" residing in the same folder as a.exe, and then opens another file named "a2".
The program has to give the relative or absolute path of "a1" and "a2" files, irrespective of them being opened for read/write..
How do I implement this in C++?
EDIT : Is it possible to divert the calls for a1 and a2 files to another path??
EDIT2 : ok, let me put it this way: i have moved the firefox.exe from C:\program files to D:\, now when i run firefox.exe it wont work coz it works on many files that are there in C:\program files, firefox.exe would be using relative paths for accessing the files. What i intend to do is to capture the calls for the files firefox.exe works on and then direct the call to the program files folder. Plz let me know if i have made myself clear..
On linux you can you use 'strace' wich output the different system calls performed by your application. If you need to implement a program which perfoms the same kind of output as strace, a quick implementation could consists in a simple shell program which greps the output of strace. Otherwise looking into the strace code is a good start.
On Windows 'Process monitor' from Sysinternals suite may help you out.
If you want to modify the arguments to open(2), creat(2), truncate(2), and so forth, then you could use the Linux ptrace(2) facility to intercept the systemcalls and replace the filename strings before executing the call.
ptrace(2) is dark magic, so unless it's an advanced course, it might not be what your professor intended. (If the next lecture is on writing a debugger like gdb(1), then this is exactly what your professor intended.)
Another mechanism you can use, and probably much more portably, is library or function interpositioning -- you can write little wrappers around specific functions in a library, and by loading the library with the LD_PRELOAD environment variable (see the ld.so(8) manpage for details on the environment variables that influence library loading), your functions will be called instead of the standard functions.
Library interposition is grey magic; it's better documented than ptrace(2), but still pretty easy to screw up.

Combining two executables

I have a command line executable that alters some bits in a file that i want to use from my program.
Is it possible to create my own executable that uses this tool and distribute only one executable?
[edit] Clarification:
The command line tool takes an offset and some bits and changes the bits at this offset in a given file. So I want to create a patcher for an application that changes specific bits to a specific value, so what I can do i write something like a batch file to do it but i want to create an executable that does it, i.e. embed the tool into a wrapper program that calls it with specific values.
I can code wrapper in (windows) c\c++, asm but no .net please.
It would be easier to roll your own implementation of this program than to write the wrapper; it sounds like it is trivial -- just open the file, seek to the right location, write your bits, close the file, you're done.
The easiest way is to embed this exe into your own and write it to disk to run it.
You can add the executable as a binary stream resource in your executable and when you need it you can extract it in a temporary folder and create new process with the temporary file.
The exact code you need to do this depends on whether you are writing .Net or C++ code.
Short answer: No.
Less short answer: Not unless it's an installer or a self extracting archive executeable.
Longer, speculative answer: If the file system supports alternate data streams, you could possibly add a stream containing the utility to your program, then your program could access it's own alternate data stream, extracting the utility when you need it. Ahaha.
You could append the one executable onto the end of the other and write some code to unpack it to a temporary folder.
I've done a similar thing before but with a configuration file and some bitmaps appended to an EXE in Windows. The way I did it was to firstly append my stuff onto the end of the EXE and then write a little struct after that which contains the file offset of the data which in your case would be the offset of the 2nd exe.
When running your app, seek to the end of the file minus the size of the struct, extract the file offset and copy the 2nd exe to a temporary folder, then launch it.
OK, here is a little more details as requestd. This is some pseudo-code to create the combined EXE. This is a little utility you run after compiling your main EXE:
Open destination file
Open main exe as a binary file
Copy main exe to destination file
offset = size of main exe
Open 2nd exe as a binary file
Copy 2nd exe to the output file
Write the offset to the output file
Now for the extraction procedure. This goes in your main EXE:
Find the location of our own EXE file (GetModuleFileName() under Windows)
Open the file in binary mode
Seek to the end minus sizeof(offset) (typically 4 bytes)
Read the offset value
Seek to the offset position
Open a temporary file in binary mode
Read bytes from the main EXE and write to the temporary file
Launch the temporary file
I think the easiest way to do this for your purposes is probably to use a self extracting executable package. For example, use a tool like Paquet Builder which will package the exe (and any other files you want) and can be configured to call the exe or a batch file or whatever else you want when the user unpacks the self-extracting executable.
If the exe was built to be relocatable (essentiall linker flag /fixed:no), you can actually do a LoadLibrary on it, get the base address, set up a call chain and call (jump) into it. It would not be worth the effort, and very few exe's are built this way so you would have to have the code to rebuild it, at which point you wouldn't be in this exercise.
So... No.
I'm more intrigued by the developer who doesn't mind writing in C/C++/asm, but 'not .net' - but is apparently stymied by fopen/fseek/fwrite - since that's about all the program you describe sounds like it's doing.
I think this is also possible by using AutoIt's FileInstall function. For this you'll have to setup AutoIt, create a script with the FileInstall function to include the who exe's and then use f.i. the function RunWait to execute them. Compile to an exe and you should be done.