过滤/丢弃数据包的网络功能

2024-06-30 05:34:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用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'

Tags: infromippacketsocketprotocollengthheader