Block YouTube with iptables

My son uses connects the Internet via our local WLAN network. To help him to just lag on the sofa and browse YouTube for hours we decided to block the video service from his mobile. It appears to be quite easy to block video services using squid but a bit harder to find the streaming server IPs. I have now found a solution which appears to work.

First we want to redirect the pass-through packages from the son’s mobile to the chain “funban”.

$IPTABLES -N funban
$IPTABLES -A FORWARD -m mac --mac-source 11:22:33:aa:bb:cc -j funban

Now we just have to build necessary rules to the chain.

#!/bin/bash
IPTABLES=/sbin/iptables
function block_ips {
 for THIS_IP in $1
 do
 # XXX.XXX.XXX.XXX/XX
 if [[ $THIS_IP =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+\/[0-9]+$ ]]; then
 $IPTABLES -A funban -d $THIS_IP -j DROP
 fi
 # XXX.XXX.XXX.XXX
 if [[ $THIS_IP =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
 $IPTABLES -A funban -d $THIS_IP -j DROP
 fi
 done
}

function accept_ips {
 for THIS_IP in $1
 do
 # XXX.XXX.XXX.XXX/XX
 if [[ $THIS_IP =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+\/[0-9]+$ ]]; then
 $IPTABLES -A funban -d $THIS_IP -j ACCEPT
 fi
 # XXX.XXX.XXX.XXX
 if [[ $THIS_IP =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
 $IPTABLES -A funban -d $THIS_IP -j ACCEPT
 fi
 done
}

function get_ips {
 echo "`dig ${1} A | grep -E '^[^;]' | grep -o -E '[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+'`"
}

# Flush funban chain
$IPTABLES -F funban

# Block all Google-related IPs. The "AS15169" is taken from
# http://networktools.nl/asinfo/google.com
block_ips "`whois -h whois.radb.net -- '-i origin AS15169' | grep ^route\:`"
# Add these IPs to make google search to work (NOTE: This is not sufficient and blocks Google searches)
accept_ips `get_ips www.google.com`

My firewall server runs this script hourly to make sure the changes in the IPs don’t open unexpected possibilities to our YouTube addict. The blockade will surely affect other Google services as well. We possibly have to add more accept_ips commands to the script.