Skip to content

Instantly share code, notes, and snippets.

@EricMyers47
Created January 13, 2019 21:32
Show Gist options
  • Save EricMyers47/f7abe656726ef6a3f19c01937bbfe500 to your computer and use it in GitHub Desktop.
Save EricMyers47/f7abe656726ef6a3f19c01937bbfe500 to your computer and use it in GitHub Desktop.
Simple fake DNS server which returns a single IP address for every query
#!/usr/bin/python -u
#
# MINI FAKE DNS SERVER (PYTHON RECIPE)
# by Francisco Santos (15 April 2006)
# From http://code.activestate.com/recipes/491264-mini-fake-dns-server/
# just slightly modified by Eric Myers <myers@spy-hill.net> 7 July 2018
########################################################################
# IP address to be returned in response to any query
ip='192.168.48.1'
import socket
class DNSQuery:
def __init__(self, data):
self.data=data
##print("Req: ", data)
self.domain=''
type = (ord(data[2]) >> 3) & 15 # Opcode bits
if type == 0: # Standard query
ini=12
lon= ord(data[ini])
while lon != 0:
self.domain += data[ini+1:ini+lon+1]+'.'
ini += lon+1
lon = ord(data[ini])
def response(self, ip):
packet=''
if self.domain:
packet+=self.data[:2] + "\x81\x80"
# Questions and Answers Counts
packet+=self.data[4:6] + self.data[4:6] + '\x00\x00\x00\x00'
packet+=self.data[12:] # Original Domain Name Question
packet+='\xc0\x0c' # Pointer to domain name
# Response type, ttl and resource data length -> 4 bytes
packet+='\x00\x01\x00\x01\x00\x00\x00\x3c\x00\x04'
# 4bytes of IP
packet+=str.join('',map(lambda x: chr(int(x)), ip.split('.')))
return packet
if __name__ == '__main__':
print('MiniFakeDNS:: dom.query. 60 IN A %s' % ip)
udps = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
udps.bind(('',53))
try:
while 1:
data, addr = udps.recvfrom(1024)
p = DNSQuery(data)
udps.sendto(p.response(ip), addr)
print( 'Response: %s -> %s' % (p.domain, ip) )
except KeyboardInterrupt:
print('MiniFakeDNS done.')
udps.close()
##
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment