💾 Archived View for perso.pw › blog › articles › linux-forbid-user-except-vpn.gmi captured on 2023-05-24 at 18:06:29. Gemini links have been rewritten to link to archived content
⬅️ Previous capture (2023-01-29)
-=-=-=-=-=-=-
If for some reasons you want to prevent a system user to use network interfaces except one, it's doable with a couple of iptables commands.
The use case would be to force your user to go through a VPN and make sure it can't reach the Internet if the VPN is not available.
We can use simple rules using the "owner" module, basically, we will allow traffic through tun0 interface (the VPN) for the user, and reject traffic for any other interface.
Iptables is applying first matching rule, so if traffic is going through tun0, it's allowed and otherwise rejected. This is quite simple and reliable.
We will need the user id (uid) of the user we want to restrict, this can be found as third field of /etc/passwd or by running "id the_user".
iptables -A OUTPUT -o lo -m owner --uid-owner 1002 -j ACCEPT iptables -A OUTPUT -o tun0 -m owner --uid-owner 1002 -j ACCEPT iptables -A OUTPUT -m owner --uid-owner 1002 -j REJECT
Note that instead of --uid-owner it's possible to use --gid-owner with a group ID if you want to make this rule for a whole group.
To make the rules persistent across reboots, please check your Linux distribution documentation.
I trust firewall rules to do what we expect from them. Some userland programs may be able to restrict the traffic, but we can't know for sure if it's truly blocking or not. With iptables, once you made sure the rules are persistent, you have a guarantee that the traffic will be blocked.
There may be better ways to achieve the same restrictions, if you know one that is NOT complex, please share!