Block a Linux Program from Accessing Network

Sometimes we want to block a specific program from accessing network, to check if it works well without network access, or to disable its telemetry (if any).

Linux namespaces provide a convenient way to do this. The “unshare” command (from the “util-linux” package) can run a program while unsharing the network namespace:

unshare --map-root-user --net [program [arguments]]

For example, we can run

unshare --map-root-user --net ip link

to check if the network access is blocked. The above command should show only the loopback interface “lo”. The loopback interface may be down. To run a problem that relies on “127.0.0.1/8”, enable the loopback interface before run the program:

unshare --map-root-user --net bash -c 'ip link set lo up && [program [arguments]]'

Note that the loopback interface is still isolated from other programs. That is, the “127.0.0.1/8” space is for the program alone. It cannot communicate with other programs via the loopback interface.

The above command runs the program as a fake “root” user. Some programs (like chromium) complain about that. We can also run the program as the current user:

unshare --map-current-user --net [program [arguments]]

But the option “--map-current-user” may be unavailable on some classical systems. And we do not have the permission to bring up the loopback interface, if it is down by default.

To run a program as the current user with unshared network namespace, but with a working loopback interface, we can use the “bwrap” command from the “bubblewrap” package:

bwrap --bind / / --dev /dev --unshare-net [program [arguments]]