Question

Over the last few days, I am passionate about the ICMP protocol and I found a python function that calculates its checksum:

def carry_around_add(a, b):
    c = a + b
    return (c & 0xffff) + (c >> 16)

def checksum(msg):
   s = 0
   for i in range(0, len(msg), 2):
       w = ord(msg[i]) + (ord(msg[i+1]) << 8)
       s = carry_around_add(s, w)
   return ~s & 0xffff

print checksum("abcdefghijklmnopqrst")

In this picture of a wireshark capture: http://memory00stack.files.wordpress.com/2013/12/resultat.png

The checksum is "0xcfcb" but the function in my test returns "55 245 -> 0xd7cd". Why ?

Thanks so much =)

Was it helpful?

Solution

Your wireshark dump shows the ICMP checksum, but (wikipedia):

The third and fourth bytes are a checksum of the entire ICMP message.

...

Checksum – Error checking data, calculated from the ICMP header and data, with value 0 substituted for this field. The Internet Checksum is used, specified in RFC 1071.

Your input to the checksum routine in your test is only the ASCII payload portion. You must provide the entire ICMP input.


For example:

def carry_around_add(a, b):
    c = a + b
    return (c & 0xffff) + (c >> 16)

def checksum(msg):
   s = 0
   for i in range(0, len(msg), 2):
       w = ord(msg[i]) + (ord(msg[i+1]) << 8)
       s = carry_around_add(s, w)
   return ~s & 0xffff

payload_body = "abcdefghijklmnopqrst"
chk = checksum(payload_body)
print chk, '{:x}'.format(chk), '(host byte order)'

msg_type = '\x08' # ICMP Echo Request
msg_code = '\x00' # must be zero
msg_checksum_padding = '\x00\x00' # "...with value 0 substituted for this field..."
rest_header = '\x00\x01\x00\x01' # from pcap
entire_message = msg_type + msg_code + msg_checksum_padding + rest_header + payload_body
entire_chk = checksum(entire_message)
print entire_chk, '{:x}'.format(entire_chk), '(host byte order)'

When I run this on my (little endian) machine, I get:

$ ./icmp_checksum_test.py 
52695 cdd7 (host byte order)
52175 cbcf (host byte order)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top