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.
Related
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.
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.
I have been trying to figure out how installers work and how they bundle everything into one executable file and how to create my own. I have tried using a hex editor called HxD which allows you to export the current hex-dump of a file into a .c source file with an array containing the hex dump that looks like the below.
Excited, I tried to write the file using some simple C++ code:
ofstream newbin("test.exe", ios::binary);
newbin << hex << rawData;
newbin.close();
... and then tried to run it.
After some further research it turns out that my little program is only writing the MZ. header which PE files use in windows and excluding the rest of the code. The executable that is created has a hex-dump of 4D 5A 90 or in ASCII MZ.. Is this a fault in my coding? Why won't it write the hex data? Would I need to use some lower-level writing tool or assembly? If so, are there any C/C++ libraries that allow me to write at such a level? Thanks!
rawData is a char* and is interpreted as a character string by the streaming operator, which is terminated by the first 0x00 byte it encounters.
For binary writing, you are best off using the
ostream& write(const char*, int);
method, leading to
newbin.write(rawData, 65536);
Assuming 65536 is the actual used size of the buffer.
Hope this helps :)
A better approach to storing binary data is to use resources. Menus, icons, bitmaps are stored in resources.
You can create a custom resource and use FindResource function, LoadResource, and then LockResource to map it into memory.
Then you can do whatever you want with the data, and of course write it to a file.
Installers usually use something like this rather than embedding lots binary data in the source code. This approach has other advantages:
You don't have to re-convert your data into source code and then recomplile the whole application when the data changes. Only resources have to be recompiled and re-linked.
The resources are not loaded into memory until use the functions above, what means until you need them. Thus the application loads faster into the memory. (Resource data are actually mapped into address space right from the file.)
With your current approach, all the data are loaded into memory, therefore your application requires more memory.
Additionally, you should better use specialized tools for creating installers.
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.
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.