c++ PE injecting additional functionality - c++

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.

Related

Redirect stdout from Executable Custom Action to MSI log

I have a Custom Action that runs an executable within an msi installer package. The exe is compiled as a console application and stdouts necessary info.
I want that output redirected to the MSI log file.
I don't want the console to be shown during the installation.
For number 2 I suppose I can use windows as a subsystem, which will not open a console at all. But no output will be shown even if I run the exe from a terminal (PowerShell/CMD).
For number 1 I thought of running an executable as a subprocess called within a Custom Action DLL, but it is not possible since the exe is stored in a binary table and won't be generated when I need it. Moreover, it will have a random name.
The Custom Action's logic MUST be run as a separate process.
EDIT: Some colleagues wrote a free guide on installation testing. Maybe it will be useful in the future, to avoid such costly mistakes.
I don't think you can do it if you want to run the custom action as a separate process. I might be wrong. But I never tried this and it doesn't seem/sound possible.
Basically, the MSIEXEC process will own the handle of the log file created by the installation and I don't think you can share it with a separate process.
Why do you need to use a separate custom action process?
As a test - you could try to create an additional DLL custom action, that runs asynchronously. The purpose of this custom action is simply to communicate with your EXE process and write inside the log file any information you want to pass from the EXE custom action. I never tried this approach, but if you have time to kill and really need the main logic to remain in the EXE custom action, you could give it a try.

C++ executable builder

I'm looking to create an application (preferably C++) that would let me compile an executable with small modifications in the source code (These options would be presented to the user in a console window) such as string data modifications. An example would be I run the application A which prompts me for a string value and I enter Y and then application B is created with a string value that would of been modified to Y.
The reason behind this that I need to produce files through a builder that can be easily distributed without configuration files and such.
I'm just wondering, how can I do it?
Usually, you don't need such an application. Use configuration files, data files or anything else to make sure your actual program can adapt without recompiling, but with changing its input data.
Example: application A prompts you for string value, you enter Y, it saves Y to a config file and then launches application B which reads that Y from the config file.
The only case I could imagine when you would actually want to do what you describe, is when a user would supply source/machine code you'll need to execute. But then again, that's why we have embedded scripting langauges and conception of plugins.
You can create a "pseudo" configuration file: you create all data that would be saved to a configuration file and then append that data to your executable. When the created program runs, it can read the data from the executing file.

Is it possible to modify an executable file on runtime?

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.

Intercept windows open file

I'm trying to make a small program that could intercept the open process of a file.
The purpose is when an user double-click on a file in a given folder, windows would inform to the software, then it process that petition and return windows the data of the file.
Maybe there would be another solution like monitoring Open messages and force Windows to wait while the program prepare the contents of the file.
One application of this concept, could be to manage desencryption of a file in a transparent way to the user.
In this context, the encrypted file would be on the disk and when the user open it ( with double-click on it or with some application such as notepad ), the background process would intercept that open event, desencrypt the file and give the contents of that file to the asking application.
It's a little bit strange concept, it could be like "Man In The Middle" network concept, but with files instead of network packets.
Thanks for reading.
The best way to do it to cover all cases of opening from any program would be via a file system filter driver. This may be too complex for your needs though.
You can use the trick that Process Explorer uses to replace itself with task manager. Basically create a key like this:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\taskmgr.exe
Where you replace 'taskmgr.exe' with the name of the process to intercept. Then add a string value called 'Debugger' that has the path to your executable. E.g:
Debugger -> "C:\windows\system32\notepad.exe"
Every a process is run that matches the image name your process will actually be called as a debugger for that process with the path to the actual process as an argument.
You could use code injection and API redirection. You'd start your target process and then inject a DLL which hooks the windows API functions that you want to intercept. You then get called when the target process thinks it's calling OpenFile() or whatever and you can do what you like before passing the call on to the real API.
Google for "IAT hooking".
Windows has an option to encrypt files on the disk (file->properties->advanced->encrypt) and this option is completely transparent to the applications.
Maybe to encrypt decrypt file portions of a disk you should consider softwares like criptainer?
There is this software as well http://www.truecrypt.org/downloads (free and open source) but I haven't tried it.
Developing a custom solution sounds very difficult.

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.