我尝试使用本文中概述的原则在 Python 3 中为防火墙编写一个基本的 TCP 打孔器。不过,我无法连接任何东西。这是代码:
#!/usr/bin/python3
import sys
import socket
import _thread as thread
def client():
c = socket.socket()
c.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
c.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
c.bind((socket.gethostbyname(socket.gethostname()), int(sys.argv[3])))
while(c.connect_ex((sys.argv[1], int(sys.argv[2])))):
pass
print("connected!")
thread.interrupt_main()
def server():
c = socket.socket()
c.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
c.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
c.bind((socket.gethostbyname(socket.gethostname()), int(sys.argv[3])))
c.listen(5)
c.accept()
print("connected!")
thread.interrupt_main()
def main():
thread.start_new_thread(client, ())
thread.start_new_thread(server, ())
while True:
pass
if __name__ == '__main__':
main()
我决定在本地机器上尝试打孔器,这样我就可以捕获两个实例发送的所有流量。我首先设置了一个环回防火墙:
iptables -A INPUT -i lo -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -A INPUT -i lo -j DROP
然后我启动了两个脚本副本:
left$ ./tcphole.py localhost 20012 20011
和
right$ ./tcphole.py localhost 20011 20012
根据 Wireshark,我可以看到 SYN 数据包是双向传输的:
但从来没有打印过“已连接!” 我究竟做错了什么?