Search code examples
pythoncpython-3.xpacket-capturewinpcap

C / Python WinPCap Translation


Sorry, this will be a very simple question for most of you.

I'm trying to convert some of the code from here into Python (3.4) as I don't know C. That's primarily the basis of this issue. While I have created the Python data structures according to the link:

from ctypes import *
u_short = c_ushort
u_char = c_ubyte
u_int = c_int

class ip_address(Structure):
    _fields=[("byte1",u_char),
             ("byte2",u_char),
             ("byte3",u_char),
             ("byte4",u_char)]

class ip_header(Structure):
    _fields=[("ver_ihl",u_char),
             ("tos",u_char),
             ("tlen",u_short),
             ("identification",u_short),
             ("flags_fo",u_short),
             ("ttl",u_char),
             ("proto",u_char),
             ("crc",u_short),
             ("saddr",ip_address),
             ("daddr",ip_address),
             ("op_pad",u_int)]

class udp_header(Structure):
    _fields=[("sport",u_short),
             ("dport",u_short),
             ("len",u_short),
             ("crc",u_short)]

class data(Structure):
    _fields[("data",c_char_p)]

I don't know enough about C to convert the following code in Python:

ip_header *ih;
udp_header *uh;
u_int ip_len;
u_short sport,dport;

/* retrieve the position of the ip header */
ih = (ip_header *) (pkt_data +
    14); //length of ethernet header

/* retrieve the position of the udp header */
ip_len = (ih->ver_ihl & 0xf) * 4;
uh = (udp_header *) ((u_char*)ih + ip_len);

/* convert from network byte order to host byte order */
sport = ntohs( uh->sport );
dport = ntohs( uh->dport );

/* print ip addresses and udp ports */
printf("%d.%d.%d.%d.%d -> %d.%d.%d.%d.%d\n",
    ih->saddr.byte1,
    ih->saddr.byte2,
    ih->saddr.byte3,
    ih->saddr.byte4,
    sport,
    ih->daddr.byte1,
    ih->daddr.byte2,
    ih->daddr.byte3,
    ih->daddr.byte4,
    dport);

I know that I need to change the "ih->ver_ihl" to "ih.ver_ihl" however I don't understand the rest. If I understand UDP packets correctly, the next section of the packet will be Data. I would also like to extract that from the packet if possible.

Thanks in advance for any help you can provide


Solution

  • Some notes:

    • For ctypes structures, you must use _fields_ not _fields.
    • As a rule of thumb, I tend to use Flake8 on my code, even on snippets.

    Test

    I tested my code on an NTP packet, as NTP is over UDP, to see if everything was correct.

    • Go to Wireshark wiki: NTP
    • Download first example capture ( SampleCaptures/NTP_sync.pcap )
    • Load pcap into wireshark > select first packet > go to "View " > ensure "Packet details" is cheked.
    • click on packet details window, Frame 1, (should read "Frame 1: 75 bytes on wire (600 bits), 75 bytes captured (600 bits)" > right click > "export selected packet bytes".

    Pass the saved file to the following script.

    Output

    192.168.50.50:1026 -> 192.168.0.1:53

    This is correct, according to wireshark.

    Code

    #!/usr/local/bin/python3
    # -*- coding: utf8 -*-
    
    import sys
    import ctypes
    import socket
    
    from ctypes import *
    u_short = c_ushort
    u_char = c_ubyte
    u_int = c_int
    
    
    class ip_address(Structure):
        _fields_ = [("byte1", u_char),
                    ("byte2", u_char),
                    ("byte3", u_char),
                    ("byte4", u_char)]
    
    
    class ip_header(BigEndianStructure):
        _fields_ = [("ver_ihl", u_char),
                    ("tos", u_char),
                    ("tlen", u_short),
                    ("identification", u_short),
                    ("flags_fo", u_short),
                    ("ttl", u_char),
                    ("proto", u_char),
                    ("crc", u_short),
                    ("saddr", ip_address),
                    ("daddr", ip_address),
                    ("op_pad", u_int)]
    
    
    class udp_header(BigEndianStructure):
        _fields_ = [("sport", u_short),
                    ("dport", u_short),
                    ("len", u_short),
                    ("crc", u_short)]
    
    
    def packet_handler(pkt_data):
    
        # cast pkt_data to void so we can do some pointer arithmetic
        v_pkt_data = ctypes.cast(pkt_data, ctypes.c_void_p)
    
        # retrieve the position of the ip header
        v_ip_header = ctypes.c_void_p(v_pkt_data.value + 14)
        pih = ctypes.cast(v_ip_header, ctypes.POINTER(ip_header))
        ih = pih.contents
    
        # retrieve the position of the udp header
        ip_len = (ih.ver_ihl & 0xf) * 4
        uh = ctypes.cast(ctypes.cast(pih, ctypes.c_void_p).value + ip_len,
                         ctypes.POINTER(udp_header)).contents
    
        # convert from network byte order to host byte order
        sport = socket.ntohs(uh.sport)
        dport = socket.ntohs(uh.dport)
    
        print("{}.{}.{}.{}:{} -> {}.{}.{}.{}:{}".format(
            ih.saddr.byte1, ih.saddr.byte2, ih.saddr.byte3, ih.saddr.byte4, sport,
            ih.daddr.byte1, ih.daddr.byte2, ih.daddr.byte3, ih.daddr.byte4, dport))
    
        # Extracting data
        #
    
        # data offset from ip header start
        data_offset = ip_len + ctypes.sizeof(udp_header)
        # data length
        data_len = ih.tlen - ip_len - ctypes.sizeof(udp_header)
        # get data
        arr_type = (ctypes.c_uint8 * data_len)
        data = arr_type.from_address(v_ip_header.value + data_offset)
    
        print(data[0:data_len])
    
        # note: same thing could be achieved from pkt_data
        print(pkt_data[14+data_offset:14+data_offset+data_len])
    
    
    def main(packet_file):
        with open(packet_file, "rb") as fd:
            data = fd.read()
    
        # create ctypes.c_char_array
        pkt_data = ctypes.c_buffer(data)
        packet_handler(pkt_data)
    
    if __name__ == '__main__':
        if len(sys.argv) == 2:
            main(sys.argv[1])