Intercepting Outbound DNS Queries (BASH)

I run a DNS server within my LAN, which overrides certain domains/zones (for things like adblocking etc), as well as allowing me to monitor for signs of malware etc.

Some devices and apps, though, insist on ignoring the DHCP provided DNS server and instead use Google's public DNS service. Rather than letting these queries sneak out, I opted to intercept them at the router

It's also useful, in some cases, when pentesting as it allows you to demonstrate the ability to use a router as a pivot point to silently send traffic to your "malicious" DNS server

This snippet details how to intercept and redirect DNS queries using iptable's NAT table on Linux

Details

  • Language: BASH

Snippet

# Create a new chain
iptables -t nat -N google-dns

# Redirect Google bound traffic into the chain
iptables -t nat -A PREROUTING -d 8.8.4.4/32 -p udp -m udp --dport 53 -j google-dns
iptables -t nat -A PREROUTING -d 8.8.4.4/32 -p tcp -m tcp --dport 53 -j google-dns
iptables -t nat -A PREROUTING -d 8.8.8.8/32 -p tcp -m tcp --dport 53 -j google-dns
iptables -t nat -A PREROUTING -d 8.8.8.8/32 -p udp -m udp --dport 53 -j google-dns

# If you wanted to intercept all DNS, you could do this
iptables -t nat -A PREROUTING -p tcp -m tcp --dport 53 -j google-dns
iptables -t nat -A PREROUTING -p udp -m udp --dport 53 -j google-dns

# Whitelist some clients (including our DNS server if it
# uses google as an upstream
#
#
# 192.168.1.70 - whitelisted client 
# 192.168.1.250 - our DNS server
iptables -t nat -A google-dns -s 192.168.1.70/32 -j RETURN
iptables -t nat -A google-dns -s 192.168.1.250/32 -j RETURN

# Redirect everything else to the local server
iptables -t nat -A google-dns -p udp -j DNAT --to-destination 192.168.1.250
iptables -t nat -A google-dns -d 192.168.1.250/32 -j REDIRECT
iptables -t nat -A google-dns -p tcp -j DNAT --to-destination 192.168.1.250