Skip to content

Instantly share code, notes, and snippets.

@menski
Created March 2, 2012 20:02
Show Gist options
  • Save menski/1960917 to your computer and use it in GitHub Desktop.
Save menski/1960917 to your computer and use it in GitHub Desktop.
Fake DNS Server
#!/bin/env python
import sys
import getopt
import socket
def response(data, ancount):
# id and flags
packet = data[:2] + '\x81\x80'
# counts
packet = ''.join([data[4:6], chr(ancount>>8), chr(ancount&0xff), '\x00\x00\x00\x00'])
# original question
packet += data[12:]
# answers
for i in range(ancount):
# pointer to domain name
packet += '\xc0\x0c'
# response type, ttl, resource length (4 bytes), resource
packet += '\x00\x01\x00\x01\x00\x00\x00\x3c\x00\x04'
packet += ''.join([chr(x) for x in [192, 168, 0, i%256]])
# id and flags (optional truncation)
return data[:2] + ('\x83\x80' if len(packet) > 508 else '\x81\x80') + packet
if __name__ == '__main__':
try:
opts, args = getopt.getopt(sys.argv[1:], 'h:p:a:')
except getopt.GetoptError, err:
print(str(err))
print('usage: fakedns.py [-h HOST] [-p PORT] [-a ANCOUNT]')
sys.exit(2)
host = 'localhost'
port = 50053
ancount = 42
for o, a in opts:
if o == '-h':
host = a
elif o == '-p':
port = int(a)
elif o == '-a':
ancount = int(a)
print('listen on {0}:{1} (ancount: {2})'.format(host, port, ancount))
udp_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
udp_sock.bind((host, port))
tcp_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcp_sock.bind((host, port))
tcp_sock.listen(1)
try:
while True:
data, addr = udp_sock.recvfrom(1024)
print('[UDP] received {0} bytes from {1}'.format(addr, len(data)))
packet = response(data, ancount)
print('[UDP] send {0} bytes to {1}'.format(len(packet), addr))
udp_sock.sendto(packet, addr)
if len(packet) > 512:
conn, addr = tcp_sock.accept()
data = conn.recv(1024)[2:]
print('[TCP] received {0} bytes from {1}'.format(addr, len(data)))
packet = response(data, ancount)
l = len(packet)
print('[TCP] send {0} bytes to {1}'.format(l, addr))
conn.send(''.join([chr(l>>8), chr(l&0xff), packet]))
conn.close()
except KeyboardInterrupt:
print('exiting')
udp_sock.close()
tcp_sock.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment