How to block internet access to certain programs on Linux
Solution 1:
The solution for me happened to be straight forward.
- Create, validate new group; add required users to this group:
- Create:
groupadd no-internet
- Validate:
grep no-internet /etc/group
- Add user:
useradd -g no-internet username
Note: If you're modifying already existing user you should run:usermod -a -G no-internet userName
check with :sudo groups userName
- Create:
- Create a script in your path and make it executable:
- Create:
nano /home/username/.local/bin/no-internet
- Executable:
chmod 755 /home/username/.local/bin/no-internet
- Content:
#!/bin/bash
sg no-internet "$@"
- Create:
- Add iptables rule for dropping network activity for group no-internet:
iptables -I OUTPUT 1 -m owner --gid-owner no-internet -j DROP
Note: Don't forget to make the changes permanent, so it would be applied automatically after reboot. Doing it, depends on your Linux distribution.
4. Check it, for example on Firefox by running:
no-internet "firefox"
In case you would want to make an exception and allow a program to access local network:
iptables -A OUTPUT -m owner --gid-owner no-internet -d 192.168.1.0/24 -j ACCEPT
iptables -A OUTPUT -m owner --gid-owner no-internet -d 127.0.0.0/8 -j ACCEPT
iptables -A OUTPUT -m owner --gid-owner no-internet -j DROP
NOTE: In case of spawning the rules will be maintained. For example, if you run a program with no-internet rule and that program will open browser window, still the rules will be applied.
Solution 2:
A more straightforward possibility: use firejail. It runs the application inside sandbox. At the sandbox, you can control the access of the application to any network or folder in your computer.
To execute a certain application without network access do following:
firejail --net=none <application>
In that case, "The sandbox looks like a computer without any network interfaces." (See Network Section in documentation)
For example, firejail --net=none firefox
will start firefox without any network connection.
Installation
See the Installation documentation.
You should install from the package system in your distribution, or better get the latest version LTS. (For example, this latest LTS version, 9.56.2
, works also in Ubuntu 16.04.)