2

This works:

sudo iptables -A OUTPUT -m owner --uid-owner {USERNAME} -j REJECT

to block internet for a specific user. But it's not permanent.

What's the easiest way to make this persistent after a reboot, with newer systems (with systemd)?

Creating a specific .service file is always tricky and takes some time to figure out: one-shot? stoppable? forking? etc. and many other options, so I was wondering what is the most natural way to persist a iptables rule with new systems.

Basj
  • 2,351
  • 9
  • 37
  • 70
  • you can persist your iptable rules with iptables-save like `iptables-save >/etc/sysconfig/iptables`. But if you have firewalld service, you shouldn't use both and need to disable that and enable `iptables-services` service. – binarysta Apr 25 '20 at 15:00
  • just install `iptables-persistent`, and you're done, no? – Vlastimil Burián Apr 25 '20 at 15:03
  • Thanks @binarysta. Is there a way to block permanently, and sometimes unblock it (from command line with a password) and have it blocked again on reboot ? – Basj Apr 25 '20 at 15:28
  • you can persist the rule in a file, then anytime you remove it with `iptables command` the rule will be disabled but in the next boot the rules will be read from the file, so you have all your rules. – binarysta Apr 25 '20 at 15:33

1 Answers1

1

For Debian/Ubuntu based distros this link is useful persist iptable rules, and also this one:

apt-get install iptables-persistent
iptables-save > /etc/iptables/rules.v4

For Redhat-based distros: The package iptables-services is needed.

# yum install iptables-services
# systemctl enable iptables
# systemctl start iptables

Backup current rules:

# cp /etc/sysconfig/iptables /etc/sysconfig/iptables.bak

Persist rules to file:

# iptables-save >/etc/sysconfig/iptables
Basj
  • 2,351
  • 9
  • 37
  • 70
binarysta
  • 2,912
  • 10
  • 14
  • Thanks! For a Debian-based distro, is it `apt install iptables-services`? Also, what does it do? Can you add some more details? This would be great for future reference. Like: is `/etc/sysconfig/iptables` read on each boot? Or is it specific, if and only if `iptables-services` is installed? – Basj Apr 25 '20 at 16:39
  • @Basj actually the logic is same just packages and related file names are different. – binarysta Apr 25 '20 at 16:48
  • @Basj yes correct. Also for some additional features like creation of systemd service unit you better install `netfilter-persistent` fully described here https://askubuntu.com/a/1072948/722342 – binarysta Apr 25 '20 at 17:26