Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UDP packet headers from socket() are not as expected

I am building a UDP server to parse and verify incoming UDP packets. I am able to receive and parse packets but the header values are not what I expected.

This is structure of incoming packet

Packet ID ( 4 bytes )
Packet Sequence ( 4 bytes )
XOR Key ( 2 bytes )
Number of Checksums in packet ( 2 bytes )
Cyclic checksum CRC32 (variable)

To send the packet,

with open('payloadfile.bin') as op:
    payload = pickle.load(op)

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

for i in payload:
    sock.sentto(payload, ('127.0.0.1',4545))

To receive and parse this packet

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind('127.0.0.1',4545)

while 1:
    packet = sock.recvfrom(65565)
    packet = packet[0]

    # parse IP
    ip_header = packet[0:20]
    iph = struct.unpack('!BBHHHBBH4s4s' , ip_header)

    #all the following values are incorrect
    version_ihl = iph[0]
    version = version_ihl >> 4
    ihl = version_ihl & 0xF

    ttl = iph[5]
    protocol = iph[6]
    s_addr = socket.inet_ntoa(iph[8]);
    d_addr = socket.inet_ntoa(iph[9]);

    # parse UDP
    packet = packet[20:28]
    data = packet[header_length:]
    source_port, dest_port, data_length, checksum = struct.unpack("!HHHH", header)

From what I understand so far, this should be the general structure
IP_HEADER ( UDP_HEADER ( PAYLOAD )))

I want to parse the headers correctly, and then extract the payload.

like image 508
Uday Ayyagari Avatar asked Oct 03 '16 16:10

Uday Ayyagari


1 Answers

Unfortunately the standard socket interface doesn't give you access to the data frames that your data arrive in, neither does it include the IP Datagram headers nor the TCP/UDP headers from the transport layer.

To get hold of lower-level data you are forced to use the so-called raw socket interface, which Windows for one tries to block you from using because you might be a hacker. This article might give you some clues.

like image 91
holdenweb Avatar answered Oct 01 '22 23:10

holdenweb