Search code examples
amazon-web-servicesnetwork-programmingnat

Is it possible to apply an iptables rule only for internal ips?


Currently, I have a NAT instance in AWS with some iptables rules, such as to forward the traffic that comes in a certain port to some other instance. So, if I do curl nat.address.com:8090, the traffic is forwarded to some other instance that is listening to the 8090 port, let's say it is instance A.

What I want is to know how to apply this rule only if the original source is inside the local network. That is, if the request to nat.address.com:8090comes from an internal instance with ip 172.31.10.10, the nat instance should forward it to instance A. However, if the request to nat.address.com:8090 comes from some external source (e.g. 189.58.200.10), it should not forward.

Is it possible?


Solution

  • As stated in Documentation you can use the -s option:

    -s, --source [!] address[/mask]
    Source specification. Address can be either a network name, a hostname (please note that specifying any name to be resolved with a remote query such as DNS is a really bad idea), a network IP address (with /mask), or a plain IP address. The mask can be either a network mask or a plain number, specifying the number of 1's at the left side of the network mask. Thus, a mask of 24 is equivalent to 255.255.255.0. A "!" argument before the address specification inverts the sense of the address. The flag --src is an alias for this option.

    For example:

    iptables -t nat -A POSTROUTING -s 172.31.10.0/24 -j MASQUERADE