Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code to analyze pcap file

I am trying to analyse a file containing packets captured using tcpdump. I first want to categorize the packets into flows using 5-tuple. Then I need to get the size and inter-arrival time of each packet in each flow. I tried Conversation list in wireshark but it gives only the number of packets in the flow not information about each packet in the flow. A suggestion for any code (c++ or shell script) that can do the job? Thank you

like image 274
Tesse M Avatar asked Sep 17 '25 17:09

Tesse M


1 Answers

UmNyobe,

If you haven't heard of Scapy yet I beleive what you are trying to do would be a near perfect fit. For example I wrote this little snippet to parse a pcap field and give me something like what you are talking about using Scapy.

#!/usr/bin/python -tt

from scapy import *
import sys
from datetime import datetime

'''Parse PCAP files into easy to read NETFLOW like output\n
   Usage:\n
   python cap2netflow.py <[ pcap filename or -l ]>\n
   -l is live capture switch\n
   ICMP packets print as source ip, type --> dest ip, code'''


def parse_netflow(pkt):  
    # grabs 'netflow-esqe' fields from packets in a PCAP file
    try:
        type = pkt.getlayer(IP).proto
    except:
        pass

    snifftime = datetime.fromtimestamp(pkt.time).strftime('%Y-%m-%d %H:%M:%S').split(' ')[1]

    if type == 6:
        type = 'TCP'
    if type == 17:
        type = 'UDP'
    if type == 1:
        type = 'ICMP'

    if type == 'TCP' or type == 'UDP':
        print( ' '.join([snifftime, type.rjust(4, ' '), str(pkt.getlayer(IP).src).rjust(15, ' ') , str(pkt.getlayer(type).sport).rjust(5, ' ') , '-->' , str(pkt.getlayer(IP).dst).rjust(15, ' ') , str(pkt.getlayer(type).dport).rjust(5, ' ')]))

    elif type == 'ICMP':
        print(' '.join([snifftime, 'ICMP'.rjust(4, ' '),  str(pkt.getlayer(IP).src).rjust(15, ' ') , ('t: '+ str(pkt.getlayer(ICMP).type)).rjust(5, ' '), '-->' , str(pkt.getlayer(IP).dst).rjust(15, ' '), ('c: ' + str(pkt.getlayer(ICMP).code)).rjust(5, ' ')]))

    else:
        pass
if '-l' in sys.argv:
    sniff(prn=parse_netflow)
else:
    pkts = rdpcap(sys.argv[1])
    print(' '.join(['Date: ',datetime.fromtimestamp(pkts[0].time).strftime('%Y-%m-%d %H:%M:%S').split(' ')[0]]))
    for pkt in pkts:
        parse_netflow(pkt)

Install Python and Scapy then use this to get you started. Let me know if you need any assistance figuring it all out, if you know C++ chances are this will already make alot of sense to you.

Get Scapy here

http://www.secdev.org/projects/scapy/

There are tons of links on this page to helpful tutorials, keep in mind Scapy does alot more but hone in on the areas that talk about pcap parsing..

I hope this helps!

dc

like image 163
dc5553 Avatar answered Sep 20 '25 08:09

dc5553