Parental control with a Raspberry Pi, Squid and SquidGuard

Recently we bought an iPod for my daughter 9 years old, we are confronted with the harsh reality : children grow fast and the access to new technologies must be enclosed. hence the need for a control system for Internet access.

raspberry pi parental control

Without wishing to become a dictator or otherwise rely entirely on a parental control tool, still had to find a solution. The first is to explain the risks, that things are not to be seen, mais rien ne vaut un bon contrôle informatique en plus 🙂

  1. For performance issues, I used a minimalistic distribution which had just to be installed. You can find all the information on this page. If necessary, update your distribution
    apt-get update && apt-get upgrade -y
  2. Install Squid and SquidGuard
    apt-get install -y squid3 squidguard

    Remember that a user proxy has been created. It will be helpful to correctly position all rights for the software.

  3. Saving the configuration of Squid (in case of error)
    cp /etc/squid3/squid.conf /etc/squid3/squid.conf.origin
  4. Generate a lighter configuration by removing many (but useful) Comment lines.
    cat /etc/squid3/squid.conf.origin | egrep -v -e '^[[:blank:]]*#|^$' > /etc/squid3/squid.conf
  5. Add your network at the end of the list of ACLs. At home I am locally on the 192.168.1.x. So I added the following line
    acl LocalNet src 192.168.1.0/24
  6. Allow machines on the network to connect to the proxy. Add the red line. The link is done with the name. Here LocalNet.
    http_access allow localhost
    http_access allow LocalNet
    http_access deny all

You can now configure your browser or OS to use the HTTP proxy with the Raspberry Pi ip and port (by default) 3128.

You can change the setting from your cache : location, size, etc. The purpose is primarily to filter Internet access but also to improve navigation. At home I created a dedicated directory, with the type tmpfs of 500Mb. Not to used too much the SD card, I get this folder in memory. The cache must not use 100% of this space (80% is the best so 400Mb).

  1. Create the directory /cache
    mkdir /cache
  2. In the file /etc/fstab add the line
    tmpfs /cache tmpfs defaults,noatime,nosuid,size=500m 0 0
  3. In the file /etc/squid3/squid.conf add the following line to the end of file
    cache_dir ufs /cache 400 16 256
  4. It's time to generate the cache and restart Squid
    service squid3 stop
    squid3 -z
    service squid3 start

Configure SquidGuard

  1. Télécharger les blacklists. Filtering access by SquidGuard is based on domain lists, URLs or keywords. University of Toulouse maintains updated lists used from SquidGuard.
    wget http://dsi.ut-capitole.fr/blacklists/download/blacklists.tar.gz
    tar -zxvf blacklists.tar.gz
  2. Install the lists in the directory accessible by SquidGuard. Do not forget to change the rights for SuidGuard can access
    mv blacklists /var/lib/squidguard/db/
    chown -R proxy:proxy /var/lib/squidguard/db/
  3. Change the SquidGuard configuration in the file /etc/squidguard/squidGuard.conf In example below, all listed access to porn sites will be blocked for all users except devices whose IP group parents. Unauthorized access are logged into a file pornaccesses.
    dbhome /var/lib/squidguard/db
    logdir /var/log/squidguard
    
    src parents {
            ip 192.168.1.10 192.168.1.18 192.168.1.30
    }
    dest porn {
            domainlist blacklists/porn/domains
            urllist blacklists/porn/urls
            log pornaccesses
    }
    
    acl {
            parents {
                    pass all
            }
            default {
                    pass !porn all
                    redirect http://localhost/block.html
            }
    }
    
  4. Embed blacklists in SquidGuard. You'll need to run this command each time the SquidGuard configuration changes (/etc/squidguard/squidGuard.conf). Be patient, it's a little bit long with our tiny machines.
    squidGuard -C all
    chown -R proxy:proxy /var/lib/squidguard/db/
  5. Add the following line at the end of the Squid configuration file /etc/squid3/squid.conf
    url_rewrite_program /usr/bin/squidGuard -c /etc/squidguard/squidGuard.conf
  6. You can test the configuration of SquidGuard and Squid and generate the cache directories
    service squid3 stop
    squid3 -z
  7. Start Squid
    service squid3 restart

That makes SquidGuard installed and configured to block adult sites

raspberry pi squid squidguard filtering

You see that the error is not the good one. Indeed, in case of an error, the configuration redirects the user to the page block.html. As we do not installed it, this generates an error. If you want to customize the message, I advise you to’install Nginx and create the page block.html with the layout that you want. Here is what I have at home :

raspberry pi proxy squid squidguard block screen

Install Webmin and calamaris for log analysis

  1. Install Webmin. I did that from the folder /root (yes I know that's bad …)
    mkdir webmin
    cd webmin/
    wget http://prdownloads.sourceforge.net/webadmin/webmin-1.760.tar.gz
    tar zxvf webmin-1.760.tar.gz
    cd webmin-1.760/
    ./setup.sh /usr/local/webmin
  2. Install the calamaris log Analyzer, very convenient for usage of the proxy information
    apt-get install calamaris

You can now connect to the ip of your Pi Raspberry on port 10000. You identify yourself with the id and password from step 1. Squid module is in the category Server. If you want to speed up the browsing, I suggest the theme Stress Free.

Another log analysis tool that I have installed is LightSquid (a demo is available here). It allows to have information per day / month / user, etc. Quite handy to see what's happening on the network.

Script automatically update blacklists

The lists are not fixed forever. They are kept up to date and regularly evolve (I do not know the exact frequency). It is therefore necessary to download and update SquidGuard. Here is a sample script that you can put in your cron table to run daily or weekly :

#!/bin/sh

cd /var/lib/squidguard/db
rm -rf blacklists
wget http://dsi.ut-capitole.fr/blacklists/download/blacklists.tar.gz
tar -zxvf blacklists.tar.gz
rm blacklists.tar.gz
squidGuard -C all
chown -R proxy:proxy /var/lib/squidguard/db/
service squid3 restart

I've created this script in /etc/cron.daily. The default execution time is 6:25, I have changed for 01:00 in the morning to make sure the update does not bother, because Squid is restarted.

Automatic URL for the proxy configuration

With your web server you can distribute the configuration of your proxy to your systems. A .pac file must be created :

  1. Create automatic configuration file. You create it in /usr/share/nginx/www and I have called proxy.pac. The content is a javascript function :
        function FindProxyForURL(url, host) {
            if (
                isInNet(myIpAddress(), "127.0.0.0", "255.0.0.0") ||
                isInNet(myIpAddress(), "192.168.0.0", "255.255.255.0")) {
                return "DIRECT";
            } else {
                if (shExpMatch(url, "http:*"))
                    return "PROXY 192.168.1.28:3128" ;
                if (shExpMatch(url, "https:*"))
                    return "PROXY 192.168.1.28:3128" ;
                return "DIRECT";
            }
        }
    

    This file gives the proxy HTTP and HTTPS. To localhost and the local network, the device can access it directly.

  2. Change the mime-types of .pac files. Add at the end of file /etc/nginx/mime.type
    application/x-ns-proxy-autoconfig .pac;
  3. Restart Nginx
    service nginx restart
  4. Set up your device to use automatic configuration to URL http://<ip of your raspberry>/proxy.pac
    No need to take every information.

Script for the generation of destinations based on blacklists

Here is a small script to generate the destinations based downloaded lists. It can help you to not have to type everything.

#!/bin/sh

SQUIDLIB=/var/lib/squidguard/db
SQUIDLIB_BLACKLISTS=$SQUIDLIB"/blacklists"

if [ -d $ SQUIDLIB_BLACKLISTS ]; then
	for folderName in `ls $SQUIDLIB_BLACKLISTS`; do
		if [ -d "$SQUIDLIB_BLACKLISTS/$folderName" ]; then
			echo "dest $folderName {"
			if [ -e "$SQUIDLIB_BLACKLISTS/$folderName/domains" ]; then
				echo "      domainlist blacklists/$folderName/domains"
			fi
			if [ -e "$SQUIDLIB_BLACKLISTS/$folderName/urls" ]; then
				echo "      urllist blacklists/$folderName/urls"
			fi
			echo "}"
		fi
	done
fi

Voilà ! I will now look at Apple Configurator to set up the proxy configuration without it being modified by the user. If some of you know an equivalent for Android, please share it in the comments.

You may also like...

  • Pingback: Raspberry Pi Home Server : Parental control with a Raspberry Pi, Squid and SquidGuard - Maison et Domotique()

  • Roman REY ARIAS

    Très sympa, on ne pense pas souvent que l’on va être confronté à ça et pourtant cela vient plus vite que prévu en général 🙂

    Je vais tester tout ça 🙂

  • kix

    J’ai actuellement ce système installé sur une machine Ubuntu et j’aurai aimé savoir quel est le niveau de performance d’une telle solution sur un Raspberry. Bien entendu il s’agit aussi d’une installation dans le cadre familial.
    Merci 😉

  • Nous sommes 3 At home : 2 pc, 2 tablets, 2 telephones et un ipod. Tous passent par le proxy et pas de probleme. Coté performance personne ne trouve à redire donc c’est validé 😉

    • lecameleon99

      Hello. Quel version de raspberry tu utilises?
      Is your proxy also blocks unwanted pubs?

      • Hello. Raspberry Pi 2. Not blocking pub I have not looked how Squid could take care

        • lecameleon99

          Thanks for the reply.

  • superjey

    On openwrt I put a transparent proxy to avoid configure.
    By cons with squid + dansguardian I bypass it all as soon as I am in this gland https me. Did you check with your configuration proposed here ?

    And also, it will not block anything if the teenager goes through a kind app “singing” to go on 4chan

    • I can turn on the switch to HTTPS without error performance side but I have not seen a difference

      For now at 9 years I still have a little room. And then I have not locked the proxy configuration on the iPod so it's not 100% secure

  • Daniel Coquette

    Extra this tutorial. I have taken the easy installing IPFire on a B +.

  • Arcana

    Hello,

    I can not create a custom error page.
    Squidguard in the configuration file, I put “redirect adresse_rpi / block.html
    I fall back on the good block.html page I created but I want the displayed address is not that of my rpi but that of the blocked site. Could you help me please ?
    Thanks in advance

    • Hello,

      At home I redirected to a PHP page that analyzes the parameters. In the configuration I have this squidguard :

      redirect http://192.168.1.28/index.php?caddr=%a&cname=%n&user=%i&group=%s&target=%t&url=%u

      More information on the possible settings when redirecting : http://www.squidguard.org/Doc/redirect.html

      • Arcana

        Hello, could tell you the contents of your index.php page, I can not change the URL.
        Kind regards

        • <html>

          <head>

          <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

          </head>

          <body>

          <img style="margin:30px; display: block; margin-left: auto; margin-right: auto" src="http://192.168.1.28/stop.png"/>

          <h3 style="text-align: center">

          Le site <?php echo htmlspecialchars($_GET["url"]); ?> n'est pas autorisé

          </h3>

          <pre style="text-align: center">Source : <?php echo htmlspecialchars($_GET["caddr"]); ?></pre>

          <pre style="text-align: center">Target : <?php echo htmlspecialchars($_GET["target"]); ?></pre>

          <pre style="text-align: center">URL : <?php echo htmlspecialchars($_GET["url"]); ?></pre>

          </body>

          </html>

          • Arcana

            Hello, thank you for your quick reply.

            In my page I have
            l’IP source, etc … but in the address bar I address my
            page which is my local web server (192.168.1.X / index.php with
            settings). From what I see, you have the URL entered in the
            address bar but the content of 'index.php’ is displayed.
            How did you do ?

          • No idea … sorry

  • Abdullah Irfan

    Or you could use GateSentry on the RPI, just flash the image onto your sd card and you’re good to go: http://www.abdullahirfan.com/my-projects/gatesentry/

  • Pingback: Parental house with Raspberry Pi, Squid and SquidGuard - Gentil virus Open Source()

  • Jimmy Van den Bliek

    Je teste la solution pour ma petite famille, pour bloquer youtube notamment à certaines heures. Ca fonctionne très bien sauf que l’accès aux mails ne fonctionnent plus. J’explique un peu ma configuration. J’ai une Freebox sur laquelle j’interdit par défaut tous les accès internet à toutes les machines pour forcer le passage via le proxy. Donc seul le proxy à un accès internet. Dans la config Squid, j’ai enlevé tout ce qui concerne le blocage des ports. Sous IOS ou OSX (iMac et iPhone), I set the proxy but the connection to the email server is not possible. Here is my config squid:

    acl CONNECT method CONNECT
    acl home_network src 192.168.0.0/24
    acl parents src 192.168.0.51
    acl youtube_hours time M T W H F 17:00-20:30
    acl youtube dstdomain .youtube.com
    http_access deny CONNECT youtube !parents !youtube_hours
    deny_info http://localhost/block.php youtube
    http_access deny youtube !parents !youtube_hours
    http_access allow localhost manager
    http_access deny manager
    http_access allow localhost
    http_access allow home_network
    http_access deny all
    http_port 3128
    coredump_dir /var/spool/squid3
    refresh_pattern ^ftp: 1440 20% 10080
    refresh_pattern ^gopher: 1440 0% 1440
    refresh_pattern -i (/cgi-bin/|?) 0 0% 0
    refresh_pattern . 0 20% 4320
    cache_dir ufs /cache 400 16 256
    url_rewrite_program /usr/bin/squidGuard -c /etc/squidguard/squidGuard.conf

    Someone Does it`s faced this problem? Thank you

    • Hello
      The access to servers on other ports as 80 or 443 function ? Genre ftp or ssh. To see if ca specifically comes from email or ports. It would be strange that only the ports for mail being blocked.
      Have you watched the squid logs in / var / log / squid3 ?

      • Jimmy Van den Bliek

        In fact anything that is not on ports 80 or 443 is blocked or at least does not pass through the proxy. I can see traffic on ports 80 and 443 in the logs but nothing on other ports. It is as if the proxy was ignored everything else and trying to jump. As I locked by default on all freebox Internet access and only the proxy server can access the Internet, everything else is blocked.

        For the moment, I opened again the Internet access for all devices and I manually put the proxy configuration for the port 80/443. It allows a minimum of control anyway.

        • There is in the configuration of squid the ability to manage the ports but I've never used.

  • Hugo Tofani

    Hello and thank you for this excellent tutorial, However, you do not speak by rewriting safesearch, do you have any information about it ?

    • Hello
      From what I have seen and understood, Google being full HTTPS and HTTP Squid in the rewrite to force SafeSearch does not look.
      If you want to test you can install squirm that can make the url rewriting with regex

  • Damian Raspachini

    Hello, I do apologise for not writing in french, but my skills is french are quite poor yet. I have a question about this magnificent guideline. Have you tried this setup as a transparent proxy? I have a 8 years old son, and I would like to force the proxy use in my LAN without setting up manually in each device. Could you kindly give me a hand with that? Recently I bought an usb to ethernet interface for my Pi in order to make a bridge between both interfaces.

    Thank you in advance.

    Best regards,

    • Hi. I did not define a transparent proxy, i change the configuration only on my daughter’s iPod (for now she has only that device)
      You can try to define a hotspot on the Raspberry Pi, add Squid on it and link the Pi to your home router via Ethernet link (and of course disable the router wifi if you have one) ?

  • Olly Lennox

    Hi There,

    Is there any chance you could upload a system image of your Raspberry Pi memory card? This guide is brilliant but I’m not the most technical and it sounds like you already have it setup really well

    Thanks!