Day 4 — Reverse Shell을 잡는 프로그램을 만들었습니다
Source: Dev.to
Introduction
어제까지 내 스크립트는 관찰자에 불과했습니다.
오늘 내 컴퓨터가 되돌아보며—대상을 스캔하는 대신 스스로를 모니터링하기 시작했습니다.
사실 이것이 대부분의 실제 사이버 보안 도구가 하는 일입니다.
Concept
악성코드는 거의 스스로를 알리지 않는다. 시스템을 장악한 공격자는 통신이 필요하다(명령 & 제어 콜백, 역쉘 등).
이 모든 것이 외부 네트워크 연결을 만든다.
공격자를 스캔하는 대신, 나는 내 컴퓨터의 네트워크 연결을 실시간으로 모니터링하기로 했으며, 사실상 파이썬으로 작은 호스트 침입 탐지 시스템(HIDS)을 구축한 것이다.
Detection Logic
- 모든 활성 연결을 감시한다.
- 해당 연결을 연 프로세스를 식별한다.
- 목적지 IP와 포트를 확인한다.
- 행동이 악의적으로 보이면 경고한다.
Examples
- 브라우저 → 포트 443 → 정상.
- PDF 리더 → 포트 4444 → 매우 의심스러움.
구현
Python 라이브러리 psutil은 프로세스, 메모리, CPU, 열려 있는 포트 및 네트워크 소켓과 같은 운영 체제 내부에 대한 접근을 제공합니다.
import psutil
import time
import socket
import logging
logging.basicConfig(
filename="connection_alerts.log",
level=logging.WARNING,
format="%(asctime)s - %(message)s"
)
SUSPICIOUS_PORTS = {4444, 5555, 6666, 1337, 9001, 12345}
seen_connections = set()
connection_times = {}
ALERT_TIMEOUT = 60 # seconds
def resolve_ip(ip):
try:
return socket.gethostbyaddr(ip)[0]
except Exception:
return ip
print("Starting Network Monitoring")
while True:
for conn in psutil.net_connections(kind='inet'):
if conn.status != "ESTABLISHED":
continue
if not conn.raddr:
continue
remote_ip = conn.raddr.ip
remote_port = conn.raddr.port
if conn.pid:
try:
pname = psutil.Process(conn.pid).name()
except Exception:
pname = "UnknownProcess"
else:
pname = "Kernel/Hidden"
connection_id = f"{pname}-{remote_ip}-{remote_port}"
current_time = time.time()
# Cleanup old alerts
for cid in list(connection_times):
if current_time - connection_times[cid] > ALERT_TIMEOUT:
seen_connections.discard(cid)
del connection_times[cid]
if remote_port in SUSPICIOUS_PORTS:
if connection_id not in seen_connections:
seen_connections.add(connection_id)
connection_times[connection_id] = current_time
msg = f"[ALERT] Suspicious port connection! {pname} -> {resolve_ip(remote_ip)}:{remote_port}"
print(msg)
logging.warning(msg)
time.sleep(0.2)
테스트
초기 시도
ping google.com→ 알림 없음 (ping은 ICMP를 사용하고 TCP가 아님).curl→ 여전히 알림 없음. 많은 연결이 밀리초 단위로 열리고 닫히기 때문에 단순 폴링이 신뢰할 수 없습니다.
리버스 셸 시뮬레이션
# Terminal 1
nc -lvnp 4444
# Terminal 2
nc 127.0.0.1 4444
Output:
[ALERT] Suspicious port connection! nc -> 127.0.0.1:4444
프로그램이 리버스 셸을 감지했으며, 행동 기반 탐지가 작동함을 확인했습니다.
Improvements
- Alert deduplication: 프로그램이 단일 지속 연결에 대해 초당 수십 개의 알림을 처음에 출력했습니다.
- Timeout logic: 각 사고를 한 번만 보고하도록 60초 창을 추가하여 알림 피로도를 줄였습니다.
Lessons Learned
- ICMP vs. TCP monitoring: 서로 다른 프로토콜은 서로 다른 관찰 방법을 필요로 합니다.
- Process‑to‑network correlation은 상황에 맞는 알림을 위해 필수적입니다.
- Polling is unreliable는 보안 모니터링에 신뢰할 수 없으며, 실제 EDR 도구는 커널 수준 이벤트 훅을 사용합니다.
- Alert suppression은 SIEM 시스템의 핵심 기능입니다.
- Signature‑based detection은 알려진 악성코드를 찾고, behavior‑based detection은 의심스러운 활동을 찾아 공격자가 회피하기 어렵게 합니다.
향후 작업
내일은 파일 수정 사항을 모니터링하여 랜섬웨어와 유사한 활동을 감지할 계획입니다. 악성코드가 통신이 필요하다면, 랜섬웨어는 파일에 접근해야 하므로 파일 시스템 변화를 감시하는 것이 다음 논리적 단계가 될 것입니다.