我正在尝试在python中实现一个无状态网络功能,它将嗅探传入的数据包,然后判断它们是“好”数据包还是“坏”数据包。 如果它们“好”,我希望程序转发数据包(转发到另一个网络/ IP),如果它们坏了,我想放弃它们。 我已经有了嗅探部分,但我一直在努力使其余的功能发挥作用。
有没有人有任何想法?感谢
import socket # Import socket module
import sys
from struct import *
s = socket.socket( socket.AF_PACKET , socket.SOCK_RAW , socket.ntohs(0x0003))
allowed_services = [80, 443]
allowed_hosts = []
for x in range(1, 11): #allows 192.168.0.1-10
allowed_hosts += ['192.168.0.%d' % x]
while True:
packet = s.recvfrom(65565)
#packet string from tuple
packet = packet[0]
eth_length = 14
eth_header = packet[:eth_length]
eth = unpack('!6s6sH' , eth_header)
eth_protocol = socket.ntohs(eth[2])
#Parse IP packets, IP Protocol number = 8
if eth_protocol == 8 :
#Parse IP header
#take first 20 characters for the ip header
ip_header = packet[eth_length:20+eth_length]
#now unpack them :)
iph = unpack('!BBHHHBBH4s4s' , ip_header)
version_ihl = iph[0]
version = version_ihl >> 4
ihl = version_ihl & 0xF
iph_length = ihl * 4
protocol = iph[6]
saddr = socket.inet_ntoa(iph[8]);
daddr = socket.inet_ntoa(iph[9]);
# print 'Incoming packet from ' + str(saddr) + ' going to ' + str(daddr) + '\n'
#TCP protocol
if protocol == 6:
t = iph_length + eth_length
tcp_header = packet[t:t+20]
#now unpack them :)
tcph = unpack('!HHLLBBHHH' , tcp_header)
sport = tcph[0]
dport = tcph[1]
if daddr in allowed_hosts and dport in allowed_services or saddr in allowed_hosts and sport in allowed_services:
print 'Good TCP packet (from %s) \n' % saddr
else:
print 'Bad Packet -> Dropping from %s \n Verify IP and/or Port\n' % saddr
print '---------------------------------------------------------------\n'