Many years back, there's clear difference between different families of malwares .They used to have their own features specific to one family. But now a days we can see Trojans with worm capabilities or viruses with Trojan capabilities, and so on.
One feature which is very common among malwares that is infecting other legitimate executable files and inject malicious code into them. These are known as File Viruses. File viruses can attach themselves to various locations of the original executable file, replace code, fill in open spaces in the code etc etc. And when the infected file executes, it will first execute the malicious code embedded inside it and then transfer the program control to main executable code.
A virus infects executable and injects its procedure in to the interior of a portable executable files in many ways.
- It can create a new executable section for the code in the target executable for our code to be injected. This technique is described here :
- Inject code between unused space between two PE section. In this article we will use the second technique to inject some code into our target executable.
In this post we will have a look at how can we inject our code (Shell Code) into a legitimate windows executable file.Here I will inject code into Calculator.exe. Here I will use harmless MessageBox shell code generated from Metasploit.
Steps to Achieve This:
1. Generate MessageBox Shellcode from Metsaploit.
2. Fixing the shellcode: Actually we need to modify the generated shellcode little bit to get things work smoothly. We will Add a pusha and popa instruction to the start and end of the shellcode, respectively.This will actually save all register contents and jmp to original entry after completion. So that it will not have any effect of the actual program execution.
3. Next step is to calculate the space left available for our shellcode inside the PE.
4. After that we need to check whether we have enough space for the shellcode in the executable file or not.
5. Now if enough space is available,the most important part is Changing the Original Entry Point of the executable. So that our injected code gets executed first. When our Shellcode execution will be finished the shellcode will transfer the program Control to the actual entry point of the executable.
As usual I used Python's pefile library to manipulate the target windows executable. You can find the code below.