Thursday, December 22, 2016

Forbid outbound connections to a certain port from a Linux user

Done on Ubuntu 14.04.

By default there are no netfilter rules:
admin@host:~$ sudo iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

We will use `iptables-apply` to enable the rule to be sure we are not locked out because of bad netfilter rules:
admin@host:~$ cat it.sh
iptables -A OUTPUT -o eth0 -p tcp --dport 27017 -m owner --uid-owner user -j REJECT
admin@host:~$ sudo iptables-apply -c ./it.sh
Running command './it.sh'... done.
Can you establish NEW connections to the machine? (y/N) y
... then my job is done. See you next time.

Now check that `user`  cannot make outbound connections on the port `27017`:
user@host:~$ telnet mongodb0.host 27017
Trying *.*.*.*...
telnet: Unable to connect to remote host: Connection refused

The new netfilter rule is there:
admin@host:~$ sudo iptables -L --line-numbers
Chain INPUT (policy ACCEPT)
num  target     prot opt source               destination

Chain FORWARD (policy ACCEPT)
num  target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
num  target     prot opt source               destination
1    REJECT     tcp  --  anywhere             anywhere             tcp dpt:27017 owner UID match user reject-with icmp-port-unreachable

The rule will not survive server restart. So we will use `iptables-persistent`.

admin@host:~$ sudo apt install iptables-persistent

You answer "Yes" during installation when prompted to save current IPv4 rules or do:

admin@host:~$ sudo sh -c "iptables-save > /etc/iptables/rules.v4"

Restart the server and check that the rules are still active.

No comments:

Post a Comment