Can iptables change its rules based on the network you're currently in?

2

Does iptables have a way to automatically adapt some of its rules or just straight out switch which rule sets it's using based on what your current network is?

I have a lot of uses for something like this but the two cleanest examples would be:

  1. If I am on my home network, expose certain ports to the LAN. When I'm not, drop traffic to them.
  2. If I have a work computer that is supposed to send syslogs to a UDP log forwarder, but that target changes IPs based on what network I'm on (because log forwarders are not on standardized IPs), only allow UDP traffic to specified IPs when certain network conditions are met.

I know I could just write up a little python script that would give me this behavior. But, lately I've been trying to get myself to ACTUALLY use the tools the system is already providing me instead of re-inventing every wheel I come across.

The OS is Kali (Debian based), sometimes CentOS too, so pretty much any linux-y option is on the table if iptables isn't the correct level to solve this problem.

codykochmann

Posted 2018-10-07T15:36:24.343

Reputation: 200

1Iptables does not have a way to know what network you are on. The closest thing would be to allow traffic to/from addresses in the ranges of the known networks, but this is obviously nowhere close to foolproof. You may be able to hack some post-up script into whatever network configuration tool you use in order to apply the correct rules. – multithr3at3d – 2018-10-07T16:08:42.013

If your home and work networks use different IP ranges. – schroeder – 2018-10-07T16:13:32.680

Are there tools that already exist that are good at this kind of thing? – codykochmann – 2018-10-07T16:21:32.710

Answers

1

iptables itself is completely static. You will need a frontend which is network-aware.

Are there tools that already exist

Fedora/CentOS use firewalld, which has a concept of 'zones' (similar to those seen in Windows Firewall). If your system uses NetworkManager, you can assign a zone to each network profile and it will load firewall rules accordingly.

Your other option is to make use of post-up 'hooks' in your network configuration tool, to make it run a script that loads the desired ruleset every time you connect to a different network. It could be as simple as a shellscript that calls iptables-restore < /etc/iptables/rules.$ZONE depending on what Wi-Fi SSID is active.

user1686

Posted 2018-10-07T15:36:24.343

Reputation: 283 655