Jarred Kenny
Jarred Kenny

Reputation: 33

Can iptables allow DNS queries only for a certain domain name?

I have iptables blocking all UDP traffic at the moment, however I want to allow only certain DNS queries to get through.

Let's use google.com as an example.

I am trying to use string matching to find the domain name in the request, and allow it. This is what I came up with.

iptables -A OUTPUT -o eth0 -p udp --sport 53 -m string --string "google.com" --algo bm -j ACCEPT

I have also tried --dport 53 instead of --sport. No dice.

If anyone knows how this can be done or see's where I went wrong your help is appreciated!

Thanks, Jarred

Upvotes: 16

Views: 22963

Answers (2)

Corey
Corey

Reputation: 16564

I know this is a bit late, but since you haven't closed the question...

If you look at the contents of the DNS request packet in wireshark or similar you will find that the dot character is not used. Each part of the domain name is a counted string, so the actual bytes of the request for google.com will be:

06 67 6f 6f 67 6c 65 03 63 6f 6d

The first byte (06) is the length of google, followed by the 6 ASCII characters, then a count byte (03) for the length of com followed by... you get the idea.

To match this in iptables, use the following:

iptables -A OUTPUT -o eth0 -p udp --port 53 -m string --hex-string "|06|google|03|com" -algo bm -j ACCEPT

The --hex-string parameter parses the provided string looking for hex values delimited by pairs of vertical bars. Anything outside of the vertical bars is interpreted as ASCII text.

If you list the OUTPUT table after adding the entry you'll find something along the lines of:

ACCEPT     udp  --  anywhere             anywhere             udp dpt:domain STRING match  "|06676f6f676c6503636f6d|" ALGO name bm TO 65535

You can tune the rule slightly - and speed it up - by restricting the search range using the --from and --to parameters.

Upvotes: 27

Saverio Proto
Saverio Proto

Reputation: 1145

I found that is not reliable with strings with dots.

This will work:

iptables -A OUTPUT -o eth0 -p udp --port 53 -m string --string google --algo bm -j ACCEPT

Upvotes: 4

Related Questions