LoneWolf LoneWolf - 2 months ago 32
Python Question

getting error while using tcp.dport in dpkt

Im trying to parse the recorded PCAP file using dpkt of python. when i tried to filter tcp connections which is having http(on port 80) requests, I'm getting error as follows ::`

import dpkt
import socket
counter=0
ipcounter=0
tcpcounter=0
udpcounter=0
httpcounter=0

filename='sampledata.pcap'

for ts, pkt in dpkt.pcap.Reader(file(filename, "rb")):

counter+=1
eth=dpkt.ethernet.Ethernet(pkt)
if eth.type!=dpkt.ethernet.ETH_TYPE_IP:
continue

ip=eth.data
tcp=ip.data
ipcounter+=1

if ip.p==dpkt.ip.IP_PROTO_TCP:
tcpcounter+=1

if ip.p==dpkt.ip.IP_PROTO_UDP:
udpcounter+=1

if tcp.dport == 80 and tcp.flags & tcp.TH_SYN == 1 and tcp.flags & tcp.TH_SYN == 1 and tcp.flags & tcp.TH_ACK == 1 :
src = socket.inet_ntoa(ip.src)
dst = socket.inet_ntoa(ip.dst)
print "%s -> %s" %(src,dst)`


error:: I am getting some OSPF error as follows

Traceback (most recent call last):
File "test.py", line 72, in <module>
if tcp.dport == 80 and tcp.flags & tcp.TH_SYN == 1 and tcp.flags & tcp.TH_SYN == 1 and tcp.flags & tcp.TH_ACK == 1 :
AttributeError: 'OSPF' object has no attribute 'dport'

Answer

You are assuming that the data encapsulated in the IP packet is tcp. But in this case, it is an OSPF packet. OSPF does not use a TCP/IP transport protocol (UDP, TCP), but is encapsulated directly in IP datagrams with protocol number 89.

You need to check the protocol type in the packet, and if it is tcp or udp then use the dport.

# Include the following condition in your for loop
if ip.p not in (dpkt.ip.IP_PROTO_TCP, dpkt.ip.IP_PROTO_UDP):
    continue