How to restrict user's access to the internet for time intervals?

Solution 1:

  1. login as root:

    sudo su

  2. check the status of your firewall:

    ufw status
    

    if the firewall is inactive, issue:

    ufw enable
    
  3. in order to restrict user wilhelm internet access on Sundays, Tuesdays,Wednesdays and Fridays to the allowed time intervals (14:00-16:00 & 17:00-18:30) :

    iptables -I OUTPUT -p tcp -m owner --uid-owner wilhelm -m time --weekdays Su,Tu,We,Fr --timestart 00:00:01 --timestop 14:00:00 -j DROP 
    iptables -I OUTPUT -p tcp -m owner --uid-owner wilhelm -m time --weekdays Su,Tu,We,Fr --timestart 16:00:00 --timestop 17:00:00 -j DROP 
    iptables -I OUTPUT -p tcp -m owner --uid-owner wilhelm -m time --weekdays Su,Tu,We,Fr --timestart 18:30:00 --timestop 23:59:59 -j DROP 
    

    side note: *please note the use of -I switch rather than -A switch of the iptables command. the -I switch inserts the aforementioned rules (3.) at the beginning (top) of the OUTPUT rule chain rather than at the bottom of the chain. placing the manually appended rules on top of the regular firewall policies is important since rules are processed top to bottom. if the top most rules ACCEPT a packet, the chain, OUTPUT, is no longer checked for the following rules which might have DROPped the packet.

  4. please make sure that the rules were indeed properly entered:

    iptables -L OUTPUT
    

    in order to delete an inappropriate rule, say rule No. 1, (1-based count from top of iptables -v -L OUTPUT) issue: iptables -D OUTPUT 1.

  5. save iptables for restoring on the next boot:

    iptables-save > /etc/iptables.rules
    
  6. in /etc/rc.local append the line:

    iptables-restore < /etc/iptables.rules
    

done

--

tested on Ubuntu 11.10 (oneiric), locale: he

Solution 2:

You can use iptables's owner extension to block a user from accessing the net, like

 sudo iptables -A OUTPUT -m owner --uid-owner user_you_want_to_block -j REJECT

Now you can use cron to add or remove those rules (which may need a little bit of shell scripting if you already have some iptable rules or want it to to for different users at different times).