Title: Restrict users to a network interface on Linux | |
Author: Solène | |
Date: 20 December 2021 | |
Tags: linux networking security privacy | |
Description: I explain how to use iptables to restrict an user to a | |
specific network interface, preventing data to leak when not using a | |
VPN. | |
# Introduction | |
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. | |
iptables man page | |
# Iptables | |
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 commands | |
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. | |
# Going further | |
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! |