Skip to content

Instantly share code, notes, and snippets.

@waldyrious
Created May 30, 2018 14:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save waldyrious/948a6f0ddee13aed07de32f86b617af4 to your computer and use it in GitHub Desktop.
Save waldyrious/948a6f0ddee13aed07de32f86b617af4 to your computer and use it in GitHub Desktop.
Script to block Internet access during the morning period
#!/bin/sh
# Script to set up rules to implement offline periods
# during which Internet connection is blocked.
# Start or extend sudo session
sudo -v
# Get the local network address subnet, which should be allowed
# https://askubuntu.com/a/872939/23900
# TODO: how to allow *.local addresses as well?
LOCALNET=$(ip r l | grep -v "default" | grep "proto kernel" | awk '{print $1}')
# Define the day and time periods for blocking
# https://askubuntu.com/a/124512/23900
# --kerneltz should enforce local time zone instead of UTC,
# but it doesn't seem to work for me...
OFFTIME="--weekdays Mon,Tue,Wed,Thu,Fri --timestart 00:00 --timestop 12:00"
# Submit the rules
# TODO: do we need to block both INPUT and OUTPUT? Would only a subset be enough?
sudo iptables -A INPUT --match time $OFFTIME ! --src "$LOCALNET" -j DROP
sudo iptables -A OUTPUT --match time $OFFTIME ! --dst "$LOCALNET" -j DROP
# Review the rules just added
sudo iptables -L | grep -P -A2 '.+policy.+'
# Save the rules
sudo iptables-save | sudo tee /etc/iptables.rules >/dev/null
echo 'iptables-restore < /etc/iptables.rules' | sudo tee -a /etc/rc.local >/dev/null
@waldyrious
Copy link
Author

waldyrious commented May 30, 2018

Despite what is said here, it doesn't seem to be necessary to enable the firewall (ufw) for this to work.

In any case, if that's needed, this command should do:

test $(sudo ufw status | cut -d' ' -f2) = "inactive" && sudo ufw enable

(Or perhaps simply run sudo ufw enable, as that should silently do nothing if it's already enabled.)

@davidak
Copy link

davidak commented Oct 10, 2021

it doesn't seem to be necessary to enable the firewall (ufw)

Yes, ufw is just a frontend for iptables.

TODO: how to allow *.local addresses as well?

That's basically DNS which could in theory also resolve to addresses on the internet. But they should all be in the LAN that you already have. If you would have multiple LANs and your computer has not an IP in all of them, you could add them manually to the list or write a script to get them.

TODO: do we need to block both INPUT and OUTPUT? Would only a subset be enough?

in theory, when you don't send anything out, no one should try to access your device from the internet, so OUTPUT might be enough. but it does not hurt to block both. a subnet would not be enough, since most IPv4 addresses are used

Thanks a lot for sharing this. That's exactly what i was looking for!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment