All NXDOMAIN belongs to InetSimby Michael Boman

The following code snippet will act as a DNS-server and will forward any unknown hosts (NXDOMAIN) to InetSim (as pointed out in TO variable. The benifit of doing it this way instead of using the DNS functionality of InetSim is that hosts that are still available will still resolve successfuly.

# twistd -y dns.py

from twisted.internet.protocol import Factory, Protocol
from twisted.internet import reactor
from twisted.names import dns
from twisted.names import client, server

TO = '192.168.1.87'
TTL = 60

class DNSServerFactory(server.DNSServerFactory):
    def gotResolverError(self, failure, protocol, message, address):
        ans = []
        ans.append(dns.RRHeader(name=message.queries[0].name.name, ttl=TTL, auth=False))
        ans[0].payload = dns.Record_A(TO,TTL)

        auth = []
        add = []

        args = (self, (ans, auth, add), protocol, message, address)
        return server.DNSServerFactory.gotResolverResponse(*args)

verbosity = 0

resolver = client.Resolver(servers=[('4.2.2.2', 53)])
factory = DNSServerFactory(clients=[resolver], verbose=verbosity)
protocol = dns.DNSDatagramProtocol(factory)
factory.noisy = protocol.noisy = verbosity

reactor.listenUDP(53, protocol)
reactor.listenTCP(53, factory)
reactor.run()

Just change the “TO” variable to your InetSim host and all unresolved requests will be redirected there. The TTL variable is for the DNS-record TTL value (TTL = Time To Live). I am using Level 3’s DNS server (4.2.2.2) as upstream, feel free to change that if you want.

Published 10 February 2015