Python/Scapy Script Fixes Checksums

It is a fairly common occurrence to end up with bad checksums in your pcaps because of drivers that neglect to calculate the checksum properly and rely on the NIC to clean it up.

Often when you are testing an IPS with prerecorded packet captures, you need a properly checksummed packet for replaying purposes, as bad checksum packets are often dropped out of hand by an IPS. So cleaning a bad checksummed pcap is a common task. But, occasionally you do not always have time to load up Netdude, not to mention the problems just getting it installed. You want a nice, quick, command-line utility to clean things up.

Thanks to fellow author Bryan Burns, the following shows a nifty little Python script that leverages the packet editing abilities of scapy (see Scapy) that cleans up all checksums quite nicely, right from the command line.

Here's the Python script. You need both Python and scapy installed on your system to run the script:

#!/usr/bin/env python
# Scapy pcap checksum fixer
# 2006 Bryan Burns

import scapy
import sys

def fixpacket(p):
  for ptype in (scapy.IP, scapy.TCP, scapy.UDP):
    try:
      p.getlayer(ptype).chksum = None
    except AttributeError:
      pass

  return p

def fixpcap(filename):
  packets = scapy.rdpcap(filename)
  fixedpackets = map(fixpacket, packets)
  scapy.wrpcap(filename, fixedpackets)

def main(  ):
  try:
    fixpcap(sys.argv[1])
  except IndexError:
    print "usage: %s <filename>" % (sys.argv[0])
    sys.exit(1)

if __name__ == "__main_  _":
  main(  )

Simply give this script a pcap filename, and it cleans it up.