Python Sniffing from Black Hat Python book

后端 未结 2 1757
孤街浪徒
孤街浪徒 2021-02-07 12:15
import socket
import os
import struct
import sys
from ctypes import *

# host to listen on
host   = sys.argv[1]

class IP(Structure):

    _fields_ = [
        (\"ihl\",         


        
2条回答
  •  青春惊慌失措
    2021-02-07 12:39

    #raw_buffer = sniffer.recvfrom(65565)[0]
    raw_buffer = sniffer.recvfrom(65535)[0]
    

    IP paket size is (2^16) - 1

    The problem is with 32 vs 64 bit systems.
    ip_header = IP(raw_buffer[:20]) works on x86 Ubuntu.
    ip_header = IP(raw_buffer[:32]) works on amd64 CentOS 6.6 Python 2.6.6
    ip_header = IP(raw_buffer) works in both.

    You have to change these,

    ("src",           c_ulong),
    ("dst",           c_ulong)  
    
    self.src_address = socket.inet_ntoa(struct.pack("

    into

    ("src",           c_uint32),
    ("dst",           c_uint32)  
    
    self.src_address = socket.inet_ntoa(struct.pack("@I",self.src))
    self.dst_address = socket.inet_ntoa(struct.pack("@I",self.dst))
    

    '@I' is unisigned int in native order. because c_ulong is 4 bytes in i386 and 8 in amd64. Check the following,

    struct.calcsize('@BBHHHBBHLL')  
    

    is 20 in i386 and 32 in amd64 which is size of _fields_. In actual it's 28 bytes in amd64 plus 4 bytes padded for word alignment.

    ip_header = IP(raw_buffer[:20]) now works correctly independent of platforms.

提交回复
热议问题