dotfiles/.local/bin/scripts/walli

32 lines
1.5 KiB
Bash
Executable File

#!/bin/sh
# Blocks internet at night using iptables and enables it only upon request
# TODO Migrate to nftables
# Auto-elevate
test "$EUID" -eq 0 || exec sudo "$0" "$@"
set -e
# https://askubuntu.com/a/124512 and https://blog.sleeplessbeastie.eu/2018/06/21/how-to-create-iptables-firewall-using-custom-chains/
iptables --new-chain chain-times 2>/dev/null || iptables --flush chain-times
# Always allow local connections - https://serverfault.com/a/550278
iptables -A chain-times -m owner --uid-owner janek -d 192.168.1.0/24 -j ACCEPT
iptables -A chain-times -m owner --uid-owner janek -d 127.0.0.0/8 -j ACCEPT
time9=$(date -u -d "$(date -d 09:00)" +%k)
iptables -A chain-times -m owner --uid-owner janek -j DROP -m time \
--timestart $(date -u -d "$(date -d "${1:-15 min}")" +%k:%M) --timestop $(expr $time9 - 2):00
# TODO Only 10 minutes every hour, anything else needs justification
# Only allow periodical internet access in the morning
#iptables -A chain-times -m owner --uid-owner janek -j DROP -m time --weekdays 1-5 \
# --timestart $time9:20 --timestop $(expr $time9 + 1):00
#iptables -A chain-times -m owner --uid-owner janek -j DROP -m time --weekdays 1-5 \
# --timestart $(expr $time9 + 1):20 --timestop $(expr $time9 + 2):00
iptables -L OUTPUT | grep -q "^chain-times" || iptables -A OUTPUT -j chain-times
if test "$2" = "--save"; then
iptables-save | tee /etc/iptables/walli.rules
echo "@reboot root $(which iptables-restore) < /etc/iptables/walli.rules" | tee /etc/cron.d/iptables-times
fi