Skip to content

Instantly share code, notes, and snippets.

@Ardumine
Created August 18, 2024 11:26
Show Gist options
  • Save Ardumine/e7914154f1f1899ac37c6a968d31081a to your computer and use it in GitHub Desktop.
Save Ardumine/e7914154f1f1899ac37c6a968d31081a to your computer and use it in GitHub Desktop.
Python DNS server to redirect all the requests to a IP
import socket
#From https://stackoverflow.com/questions/41723507/create-a-dns-server-and-redirect-all-request-to-my-site
#Translated and made it work with newer python
#Run as admin: sudo python3 redirecter.py
#You can test the server with the host command in linux: host google.com 127.0.0.1
class DNSQuery:
def __init__(self, data):
self.data = data
self.domain = bytearray()
type = ((data[2]) >> 3) & 15 # Opcode bits
if type == 0: # Standard query
ini = 12
lon = (data[ini])
while lon != 0:
self.domain += data[ini + 1 : ini + lon + 1] + b"."
ini += lon + 1
lon = (data[ini])
def Answer(self, ip):
packet = bytearray()
if self.domain:
packet += self.data[:2] + b"\x81\x80"
packet += (
self.data[4:6] + self.data[4:6] + b"\x00\x00\x00\x00"
) # Questions and Answers Counts
packet += self.data[12:] # Original Domain Name Question
packet += b"\xc0\x0c" # Pointer to domain name
packet += b"\x00\x01\x00\x01\x00\x00\x00\x3c\x00\x04" # Response type, ttl and resource data length -> 4 bytes
packet += str.join(
"", map(lambda x: chr(int(x)), ip.split("."))
).encode("utf-8") # 4bytes of IP
return packet
if __name__ == "__main__":
ipToRedirect = "127.0.0.1"#The IP address where all the requests will be solved to
udps = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
udps.bind(("", 53))#Start the UDP server
print(f"Server started! All DNS requests will be solved to {ipToRedirect}")
try:
while 1:
data, addr = udps.recvfrom(1024)
p = DNSQuery(data)
udps.sendto(p.Answer(ipToRedirect), addr)
print(f"Answer: {p.domain.decode("utf-8")} -> {ipToRedirect}")
except KeyboardInterrupt:
print("Stoping server...")
udps.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment