TCP劫持概念验证
这个Python脚本是一个使用Scapy库操作网络数据包的TCP连接中断工具。它定义了连接处理的自定义异常,并提供了通过读取Linux系统当前TCP连接列表/proc/net/tcp
来根据进程ID(PID)或TCP端口获取端点的功能。
核心功能
TCPBreaker
类是实现功能的核心,它能够过滤和拦截与指定本地和远程TCP端口相关的数据包,捕获TCP会话的序列号并发送重置(RST)数据包,从而有效终止连接。
该脚本还可以与ipset交互,添加或删除IP对来管理防火墙规则。它包含一个命令行界面供用户交互,支持指定PID、本地/远程端口以及选择数据包捕获方法(raw或nflog)等选项。
使用方式
1
|
python tcp_breaker.py [OPTIONS] [ipset_name]
|
选项参数
ipset_name
:(可选)要临时插入本地IP的ipset名称
--pid
:(可选)要终止连接的进程ID
--port
:(可选)要关闭连接的本地TCP端口
-d, --remote-port
:(可选)将端口参数视为远程端口而非本地端口
-c, --capture
:(可选)指定捕获方法,可选"raw"或"nflog"
--debug
:(可选)启用详细操作模式用于调试
示例命令
1
2
3
4
5
6
7
8
9
10
11
|
# 通过PID终止连接
python tcp_breaker.py --pid 1234 --port 8080
# 使用ipset终止连接
python tcp_breaker.py my_ipset --pid 1234
# 通过指定本地和远程端口终止连接
python tcp_breaker.py my_ipset --port 80 -d --remote-port
# 不使用ipset,使用raw捕获方法
python tcp_breaker.py --pid 5678 --port 443 --capture raw
|
技术实现
连接端点获取
脚本通过解析/proc/net/tcp
文件来获取当前系统的TCP连接信息:
1
2
3
4
5
|
def get_endpoints(pid=None, port_local=None, port_remote=None):
if pid:
matches = list(get_endpoints_by_pid(pid))
else:
matches = list(get_endpoints_by_port(port_local, port_remote))
|
TCP连接中断
TCPBreaker
类使用状态机模式来监控和中断TCP连接:
1
2
3
|
class TCPBreaker(Automaton):
def __init__(self, port_local, port_remote, timeout=False, **atmt_kwz):
self.ss_filter_port_local, self.ss_filter_port_remote = port_local, port_remote
|
RST包发送
当检测到目标连接时,脚本会构造并发送RST包:
1
2
3
4
5
|
rst = IP(**ordered('src', pkt_ip.src, 'dst', pkt_ip.dst)) \
/ TCP(**dict(it.chain.from_iterable(p.viewitems() for p in (
ordered('sport', pkt_tcp.sport, 'dport', pkt_tcp.dport),
ordered('seq', pkt_tcp.seq, 'ack', pkt_tcp.ack),
dict(flags=b'R', window=pkt_tcp.window)))))
|
注意事项
确保具有运行脚本的必要权限,因为它需要访问/proc/net/tcp
,并且可能需要提升权限来修改ipset规则或终止连接。
作者:ClumsyLulz(又名SleepTheGod Taylor Christian Newsome)