About me: My name is Solène Rapenne, pronouns she/her. I like learning and sharing knowledge. Hobbies: '(BSD OpenBSD Qubes OS Lisp cmdline gaming security QubesOS internet-stuff). I love percent and lambda characters. OpenBSD developer solene@. No AI is involved in this blog.

Contact me: solene at dataswamp dot org or @solene@bsd.network (mastodon).

I'm a freelance OpenBSD, FreeBSD, Linux and Qubes OS consultant, this includes DevOps, DevSecOps, technical writing or documentation work. If you enjoy this blog, you can sponsor my open source work financially so I can write this blog and contribute to Free Software as my daily job.

Restrict users to a network interface on Linux

Written by Solène, on 20 December 2021.
Tags: #linux #networking #security #privacy

Comments on Fediverse/Mastodon

Table of contents

1. 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

2. 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 -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.

3. 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!