python/scapy DNS sniffer and parser

user1627588 picture user1627588 · Jul 17, 2014 · Viewed 15.7k times · Source

I have python/scapy sniffer for DNS. I am able to sniff DNS messages and get IP/UDP source and destination IP address and ports but I have problems parsing DNS part I would appreciate some help or solution to work this out.

#!/usr/bin/env python

from scapy.all import *
from datetime import datetime
import time
import datetime
import sys

############# MODIFY THIS PART IF NECESSARY ###############
interface = 'eth0'
filter_bpf = 'udp and port 53'

# ------ SELECT/FILTER MSGS
def select_DNS(pkt):
    pkt_time = pkt.sprintf('%sent.time%')
# ------ SELECT/FILTER DNS MSGS
    try:
        if DNSQR in pkt and pkt.dport == 53:
        # queries
           print '[**] Detected DNS QR Message at: ' + pkt_time
           # 
        elif DNSRR in pkt and pkt.sport == 53:
        # responses
           print '[**] Detected DNS RR Message at: ' + pkt_time
 # 
    except:
        pass
# ------ START SNIFFER 
sniff(iface=interface, filter=filter_bpf, store=0,  prn=select_DNS)

Answer

wookie919 picture wookie919 · Jul 17, 2014
>>> ls(DNS)
id         : ShortField           = (0)
qr         : BitField             = (0)
opcode     : BitEnumField         = (0)
aa         : BitField             = (0)
tc         : BitField             = (0)
rd         : BitField             = (0)
ra         : BitField             = (0)
z          : BitField             = (0)
rcode      : BitEnumField         = (0)
qdcount    : DNSRRCountField      = (None)
ancount    : DNSRRCountField      = (None)
nscount    : DNSRRCountField      = (None)
arcount    : DNSRRCountField      = (None)
qd         : DNSQRField           = (None)
an         : DNSRRField           = (None)
ns         : DNSRRField           = (None)
ar         : DNSRRField           = (None)
>>> ls(DNSQR)
qname      : DNSStrField          = ('.')
qtype      : ShortEnumField       = (1)
qclass     : ShortEnumField       = (1)
>>> ls(DNSRR)
rrname     : DNSStrField          = ('.')
type       : ShortEnumField       = (1)
rclass     : ShortEnumField       = (1)
ttl        : IntField             = (0)
rdlen      : RDLenField           = (None)
rdata      : RDataField           = ('')
>>> 

If the above layer definitions and fields are not enough, you can either define your own layer and decode the packet using your custom layer, or simply retrieve the data straight from the raw payload. As for the timestamp, you can do pkt.time.