第4天 — 我编写了一个捕获 Reverse Shell 的程序
抱歉,我需要您提供要翻译的具体文本内容(除了已经给出的 Source 链接之外),才能为您进行翻译。请粘贴文章的正文部分,我会按照要求保留链接、格式和代码块,只翻译正文内容。
介绍
直到昨天,我的脚本还是观察者。
今天,我的电脑开始反向观察——监控自身,而不是扫描目标。
这实际上正是大多数真实的网络安全工具所做的。
概念
恶意软件很少会自报家门。攻击者在入侵机器后需要进行通信(指令与控制回调、反向 shell)。
所有这些都会产生出站网络连接。
与其扫描攻击者,我决定实时监控自己机器的网络连接,基本上用 Python 构建一个小型主机入侵检测系统(HIDS)。
检测逻辑
- 监视每一个活动连接。
- 确认是哪个进程打开的。
- 检查目标 IP 和端口。
- 若行为看起来可疑则发出警报。
示例
- 浏览器 → 端口 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→ 仍然没有警报,因为大量连接在毫秒级别内打开并关闭,使得简单轮询不可靠。
模拟反向 shell
# Terminal 1
nc -lvnp 4444
# Terminal 2
nc 127.0.0.1 4444
输出:
[ALERT] Suspicious port connection! nc -> 127.0.0.1:4444
程序检测到了反向 shell,证实了基于行为的检测能够发挥作用。
改进
- Alert deduplication:程序最初对单个持久连接每秒打印数十个警报。
- Timeout logic:添加了 60 秒窗口,以仅报告每个事件一次,减少警报疲劳。
经验教训
- ICMP 与 TCP 监控: 不同的协议需要不同的观察方法。
- 进程到网络关联 对于上下文警报至关重要。
- 轮询不可靠 用于安全监控;真实的 EDR 工具使用内核级事件钩子。
- 警报抑制 是 SIEM 系统的核心功能。
- 基于签名的检测 寻找已知恶意软件;基于行为的检测 寻找可疑活动,这对攻击者更难规避。
未来工作
明天我计划监控文件修改,以检测类似勒索软件的活动。如果恶意软件需要通信,勒索软件就需要触及文件——因此监视文件系统的变化将是下一个合乎逻辑的步骤。