AWS IPTables – Destination NAT on the Same Network

amazon-web-servicesiptablesnat;

In AWS we have 3 instances in the same subnet/VPC. We would like to have the client instance make a DNS request to a second analysis instance, which will then forward the request to a third instance running a DNS service. The DNS service should then provide a response to the analysis instance, which should then respond to the client.

The purpose is so the Analysis instance can intercept the traffic between the Client and DNS instances for analysis purposes.

Client instance -> Analysis instance (NAT) -> DNS instance

The current setup allows the Client instance to send a DNS request through the Analysis instance to the DNS instance. The DNS instance responds to the Analysis instance per tcpdump but the Client instance never receives a response from the Analysis instance.

We have source/destination checks in AWS for the Analysis instance performing NAT turned off.

We first enabled forwarding on the Analysis instance:

sudo sysctl -w net.ipv4.ip_forward=1

We then add the following IPTables rules to the Analysis instance

sudo iptables -A FORWARD -p udp --dport 53 -d 192.168.1.151 -j ACCEPT
sudo iptables -t nat -A PREROUTING -p udp --dport 53 -j DNAT --to-destination 192.168.1.151
sudo iptables -t nat -A POSTROUTING -d 192.168.1.151 -s 192.168.1.156 -p udp --dport 53 -j SNAT --to 192.168.1.213

Other POSTROUTING rules such as the following were tried as well

sudo iptables -t nat -A POSTROUTING -j MASQUERADE
sudo iptables -t nat -A POSTROUTING -p udp -d 192.168.1.151 --dport 53 -j SNAT --to-source 192.168.1.213
sudo iptables -t nat -A POSTROUTING -p udp -d 192.168.1.151 --dport 53 -j MASQUERADE

All with the same result, Client instance never receives a DNS answer. Thoughts on what might be preventing the analysis instance from returning a response?

Best Answer

The issue was the FORWARD chain was not allowing return traffic so the following rule was needed:

sudo iptables -A FORWARD -m state --state RELATED,ESTABLISHED -j ACCEPT

The full solution looks like:

sudo iptables -A FORWARD -p udp --dport 53 -d 192.168.1.151 -j ACCEPT
sudo iptables -A FORWARD -m state --state RELATED,ESTABLISHED -j ACCEPT
sudo iptables -t nat -A PREROUTING -p udp --dport 53 -j DNAT --to-destination 192.168.1.151
sudo iptables -t nat -A POSTROUTING -p udp --dport 53 -j SNAT --to 192.168.1.213