How To Use IPTables to Block a Specific DNS Request?

adil
4 min readMar 5, 2024

--

Part 1: Understanding Network Packets: IP Header, UDP Header

It is possible to block DNS requests based on the DNS port number (53) using IPTables.

Photo by Pawel Czerwinski on Unsplash

Is it possible to block a specific DNS Request?

Can we block all MX DNS queries?
Can we block MX DNS queries for google.com only?

Yes, we can do both using IPTables.

We need the hexadecimal values of the DNS query:

I will sniff the network via tcpdump

tcpdump -i any port 53 -Xn

And I will query the MX records of google.com

dig mx google.com

Examine it:

The DNS header for DNS queries is given below:

Source: tcpipguide.com

In the DNS header, the domain details (Question Name) are immediately followed by the 16-bit Question Type (A, CNAME, MX, etc.), followed by the 16-bit Question Class (Internet).

I need to know the hex values of google.com to find them in the tcpdump output.

I will convert the words google and com from ASCII to Hexadecimal using an online tool:

google’s hex values:

I will find the word google in the tcpdump output. The length of the word google is 6 bytes. So, I’ll find 6 and google’s hexadecimal value:

1 hexadecimal value is 4 bits.

After 06, I colored 12 hexadecimal characters.

12 hexadecimal characters * 4 = 48 bits
48 bits / 8 = 6 bytes

com’s hexadecimal values:

the length of the word com is 3 bytes. So, I’ll find 3 and com’s hexadecimal value:

6 hexadecimal characters * 4 = 24 bits
24 bits / 8 = 3 bytes.

The next 00 is the end of label:

I found the MX DNS Records’ value on the internet: https://en.wikipedia.org/wiki/List_of_DNS_record_types

Its decimal value is 15. So, the hexadecimal value of 15 is f. QTYPE (A, CNAME, MX, etc.) has 16 bits in the DNS header.

But f is 4 bits. Therefore, the remaining 12 bits are zero:

The next block is the Question Class (Internet, 0001):

I found the required hexadecimal values. Let’s block requests!

Let’s block all MX queries via IPTables:

iptables -A OUTPUT -p udp --dport 53 --match string --algo kmp --hex-string '|00 00 0f 00 01|' -j DROP

To ensure I was blocking MX queries, I added the end-of-label before the MX record and the question class after the MX record.

Examine it:

It works.

Let’s block MX queries only for google.com using IPTables:

iptables -A OUTPUT -p udp --dport 53 --match string --algo kmp --hex-string '|06 67 6f 6f 67 6c 65 03 63 6f 6d 00 00 0f 00 01|' -j DROP

Examine it:

--

--