scapy / dns server / snippet

scapy / dns server / snippet

  • Written by
    Walter Doekes
  • Published on

A few days ago, the Scapy project was brought to my attention.

Scapy is an internet packet manipulation library for Python2. It can be used to sniff and decode packets, or to generate your own custom packets.

In the most basic form, it runs on raw sockets, sniffing and decoding traffic like tcpdump. See the sniff() examples and the send(IP(dst="") / ICMP()) example for sending a simple packet.

But just as easily, it works on regular datagram sockets — those that you don’t need CAP_NET_RAW powers for. Like in the following example.

This example snippet demonstrates how Scapy takes the hassle out of parsing and creating DNS requests and responses. It accepts DNS requests on port 1053, in the form <NAME>.<IPV4>, returning <IPV4> as an A record.

This example provides a similar feature as the (or service: a wildcard DNS for any IPv4 address. Useful when serving development sites on internal IP addresses.

# Use scapy2.3.1+ from pip (secdev original) or for Python3 use the
# Scapy3K version.
# Example DNS server that resolves A record
# requests to an A:IPV4 response.
# $ dig -p 1053 @ +short

from scapy.all import DNS, DNSQR, DNSRR, dnsqtypes
from socket import AF_INET, SOCK_DGRAM, socket
from traceback import print_exc

sock = socket(AF_INET, SOCK_DGRAM)
sock.bind(('', 1053))

while True:
    request, addr = sock.recvfrom(4096)

        dns = DNS(request)
        assert dns.opcode == 0, dns.opcode  # QUERY
        assert dnsqtypes[dns[DNSQR].qtype] == 'A', dns[DNSQR].qtype
        query = dns[DNSQR].qname.decode('ascii')  #
        head, domain, tld, tail = query.rsplit('.', 3)
        assert domain == 'example' and tld == 'com' and tail == ''
        head = head.split('.', 1)[-1]  # drop leading "prefix." part

        response = DNS(
  , ancount=1, qr=1,
            an=DNSRR(rrname=str(query), type='A', rdata=str(head), ttl=1234))
        sock.sendto(bytes(response), addr)

    except Exception as e:
        print('garbage from {!r}? data {!r}'.format(addr, request))

As you can see, all the protocol stuff is nicely tucked away in pre-existing structures, so you get nice and readable Python. Thanks, Scapy!

Back to overview Newer post: Planned network maintenance (01:00-03:00 6 NOV 2015) Older post: flake8 / vim / python2 / python3