Skip to content

Latest commit

 

History

History
1024 lines (646 loc) · 54.4 KB

README.md

File metadata and controls

1024 lines (646 loc) · 54.4 KB

Raspberry Pi: Pi-hole Ad-Blocking + Unbound DNS + WireGuard VPN

This project is centered around getting a Raspberry Pi set up on a simple home network in order to block ads and naughty DNS requests, secure the DNS requests of all devices on the network, and provide a VPN solution for when any of these devices are outside of the network and would like to take advantage of the security (and speed) benefits of the network remotely.

Ad-blocking VPN with local DNS resolution

There are several guides written about this or similar setups, but in practice, there was always something missing or assumptions were made about certain steps in the process. This guide is meant to shed some light on those steps, simplify the process of getting set up, and explain my findings in order to help anyone else trying to do the same.

This is what worked for me, your miles may vary.

Buy Me a Coffee?

When I first started tinkering with my Raspberry Pi, I had no idea how much time I would invest in getting it up and running. I'm happy to share my findings with the community here for free, but if you'd like to say thanks, a free coffee (or beer) is always welcome.

ko-fi

Translations

Available in other languages: French (coming soon)

Prerequisites

While I won't have time to troubleshoot other setups, I'm sharing what I had to work with here. For this setup, I currently use:

  • Raspberry Pi 4 Model B (with 4GB of RAM)
  • Raspberry Pi OS Lite (latest version)
  • 64GB MicroSD card (4GB might be enough, but I'd stick with at least 8GB), in this case a SanDisk Ultra MicroSD XC
  • Mac running macOS (for prepping, backing up, and restoring the SD card)
  • The free ApplePi-Baker app for macOS
  • USB SD card reader (I use this simple Anker 2-in-1 card reader)
  • Keyboard (and optional mouse) for initial Raspberry Pi setup (it's possible to use an Apple Magic Keyboard connected via a USB Lightning cable)
  • HDMI cable and monitor/TV for initial Raspberry Pi setup
  • Wireless/wired router (with the option to open ports) such as the Eero 6 Pro

Note: I originally used a cheap wireless mouse that has its own USB Bluetooth dongle, but had errors when booting my Raspberry Pi with it attached. After some research, it seems this may conflict with the Pi's onboard Bluetooth chip, and it was causing issues (dhcpcd was throwing errors as well). During my most recent install from scratch, I removed it completely and everything went smoothly. I don't think you really need a mouse at all if you're running OS Lite...

That said, this process should work on any Raspberry Pi 3 and above, and there are Windows/Linux tools to handle the SD card management.

Installing Raspberry Pi OS on the Raspberry Pi

There are many operating systems available to run on the Raspberry Pi, but we'll be using the latest version of Raspberry Pi OS for this tutorial. There are also several different ways to install Raspberry Pi OS on your Raspberry Pi, though the official Raspberry Pi Imager is the most often used. N00BS (New Out Of the Box Software) is still available if you look hard enough, but not recommended.

Installing Raspberry Pi OS with Raspberry Pi Imager

This is the simplest way to get Raspbian installed on your Raspberry Pi. Official installation instructions are available from the Raspberry Pi website.

Step 1: Download Raspberry Pi Imager

From the official Raspberry Pi Downloads page, download Raspberry Pi Imager for your OS (Windows, macOS, and Ubuntu apps are available).

Step 2: Write the Image to Your SD Card

Next, open the Raspberry Pi Imager app and insert the microSD card into your computer. then choose an operating system to install. We'll stick with Raspberry Pi OS Lite for a headless Raspberry Pi in this case (you'll want the 64-bit version if you're using a Raspberry Pi 3, 4, or 400). Then choose your microSD card from the second button's modal, at which point the WRITE button will be available.

Raspberry Pi Imager

Before writing the OS to the microSD card, click the gear icon in the bottom right of the window to include advanced settings for your OS. You'll first be prompted:

Would you like to prefill the wifi password from the system keychain?

I declined this option as I'll be adding this Raspberry Pi to a wired network. Next, check out the Advanced Options. From here you can enable SSH, set a username and password, configure the wireless LAN, and add locale settings. This will speed up your OS setup time, but all of these options can be done from the Raspberry Pi Configuration Tool later as well.

Advanced Options

Save these options (either for this session only, or to always use) and then click the WRITE. The process takes just a few minutes to format the microSD card and write the files, and maybe a minute or two more to verify them (you may have to enter your computer's username/password to continue).

Finalizing Write

And that's it! Remove the microSD card from your computer when prompted, and insert it into your Raspberry Pi before booting it up to a fresh install of Raspberry Pi OS.

Note: If you setup a hostname, username/password, and enabled SSH in the Advanced Options, skip to the Verify You Can SSH into the Raspberry Pi step.

Initial Setup of Raspbian

To login to your freshly baked Raspberry Pi, use the default username/password pair of pi and raspberry (or the username/password combination you set in Raspberry Pi Imager's advanced settings). Steps to to change your password (and username) will be covered later.

Prepping Raspberry Pi OS for SSH

Enabling SSH on the Raspberry Pi allows us to SSH into it from any device on the network, thus no longer needing the mouse, keyboard, HDMI cable, and screen. You'll need to know the IP address of your Raspberry Pi to continue.

Setting Up a Static IP Address

First, we need the IP address and MAC address of the Raspberry Pi. It's highly recommended that you set up a static IP address on your network for your Raspberry Pi so that you can easily SSH into it, and later, point other services directly to it.

To get the current IP address of your Raspberry Pi, run:

ifconfig

And you'll see some output that should include both eth0 details and wlan0 details. The former is your ethernet (wired) network interface, while the latter is your wireless (wifi) network interface. Depending on how you'll be connecting your Raspberry Pi to your network, you'll need to focus on one or the other.

If your Raspberry Pi is wired into your network via an ethernet cable, take a look at the eth0 interface and find the following line:

inet 192.168.x.x netmask 255.255.255.0 broadcast 192.168.x.255

Where 192.168.x.x is the IP address of the Raspberry Pi (I've obfuscated this for privacy reasons). If you see a line that starts with inet6, then your device is configured to use IPv6 as well:

inet6 feXX::XXXX:XXX:XXXX:XXXX prefixlen 64 scopeid 0x20<link>

The Raspberry Pi's MAC address is just below the inet line(s):

ether ab:cd:ef:12:34:gh txqueuelen 1000 (Ethernet)

Where ab:cd:ef:12:34:gh would be the unique MAC address of the eth0 interface on this Raspberry Pi. In order to force your network's router to give the Raspberry Pi a static IP address (the same IP every time it connects), you'll need to modify the /etc/dhcpcd.conf file on the Raspberry Pi directly, or edit the settings of your router and add a DHCP Reservation (as I have below):

Description: Raspberry Pi
Reserve Address By: MAC Address
MAC Address: ab:cd:ef:12:34:gh
IPv4 Address: 192.168.x.x

Once you've created a static IP address of your choosing (matching your router's existing subnet schema), save your changes and restart your router.

Enabling SSH on the Raspberry Pi

Note: You can skip this step if you enabled SSH in Raspberry Pi Imager's advanced settings. Just restart your Pi with sudo reboot and continue with setup.

Now we'll open the Raspberry Pi's Configuration Tool:

sudo raspi-config

Raspberry Pi Software Configuration Tool Under the Interfacing Options group, go to SSH and enable it. Raspberry Pi Software Configuration Tool You should be prompted to restart your Raspberry Pi. If you aren't, exit the Configuration Tool and type:

sudo reboot

Note: On reboot, if you notice any failures and end up in "Emergency Mode", make sure you've disconnected any Bluetooth USB modules (like the one I use for a Bluetooth mouse during installation). There seems to be an issue around these modules which causes errors during bootup. After login, under "Emergency Mode", type systemctl default or exit to reboot into "Default Mode."

Verify You Can SSH into the Raspberry Pi

Now that you've enabled SSH on the Raspberry Pi and given it a static IP address, you should be able to do all of the following setup from another device by connecting via SSH.

On your system's console (I'm using the Terminal app for macOS) type:

Where pi is the username on your Raspberry Pi and 192.168.x.x is the static IP address you just set up. If your system supports mDNS (Macs do by default), you should be able to use raspberrypi.local (or whatever hostname you chose in Raspberry Pi Imager's advanced settings) in place of your IP address:

Then type the default password of raspberry (or your custom password) to login. You should now be greeted with the Raspbian console.

Note: If you get an error that says the host identification has changed, you’ll need to remove the old entry (the one with the same static IP address) from your hosts file first (on a Mac, that file is ~/.ssh/known_hosts), then try again.

Change Your Password

Using default passwords is obviously not a great idea, so if you haven't set a different username and/or password in Raspberry Pi Imager's advanced settings ahead of time, your first task after you SSH into your newly setup Raspberry Pi should be to change the password using:

passwd

Enter your current password (raspberry is the default) and then type and retype a new password.

Optional: Change pi Username

If you'd rather not stick with the default username of pi, changing your Raspbian username is unfortunately not as easy as you'd think, which is why it's recommended to choose a custom username/password combination using Raspberry Pi Imager. Since you're currently logged in as user pi and you can't change the username of the current user, you have to get creative with how you go about this. You could create a new user, logout of the pi user, login as the new user, and then as root you can change the username of pi and its home directory. But now you have a second user.

You can also follow along with these instructions on adding a temporary user and using it to change pi's username, but I can't vouch for this method as I skipped it altogether.

Password-less SSH Access

It's possible to configure the Raspberry Pi to allow a computer to access it without providing a password each time you try to connect. If you enabled SSH through Raspberry Pi Imager's advanced settings, you have the option to "Use password authentication" (as we did above) or to "Allow public-key authentication only" (which I haven't investigated fully).

In your Mac's Terminal app, generate SSH key pairs with:

ssh-keygen -t rsa -b 4096

and enter a password for the SSH key (store this somewhere secure, you may need it at a later time). If you already have SSH key(s), give this pair a different name (such as id_rsa_pi) or use your existing key. Now that the public and private keys have been generated on your Mac, you'll need to copy the public key to your Raspberry Pi using:

ssh-copy-id [email protected]

where pi is the username you use on the Raspberry Pi and the 192.168.x.x is the static IP address of the Raspberry Pi. You'll need to enter the password for the pi user to confirm the copy. From now on, you won't have to enter a password to SSH into your Raspberry Pi.

Keep Client SSH Keys in macOS Keychain

Using an SSH agent, you can store your SSH key(s) in your Mac's Keychain for easy (and secure) access. Add your newly created SSH key pair to the macOS Keychain with:

ssh-add -K ~/.ssh/id_rsa_pi

where id_rsa_pi is the name you used to create the SSH key pair. Enter your macOS password to confirm. In order to prevent macOS from forgetting your SSH keys on restart, you can add it to your ~/.ssh/config file based on these instructions. Your ~/.ssh/config file should look something like this:

Host *
    UseKeychain yes
    AddKeysToAgent yes
    IdentityFile ~/.ssh/id_rsa
    IdentityFile ~/.ssh/id_rsa_pi

Now once again, SSH into your Raspberry Pi using the Terminal application by typing ssh [email protected] where 192.168.x.x is the static IP address of your Raspberry Pi, and you shouldn’t have to enter a password again from this device! Repeat these steps on other devices to generate and share their SSH key(s) with the Raspberry Pi.

Optional: Additional Raspbian Configuration

Here are some additional steps I prefer to take upon setting up my Raspberry Pi. First, open the Configuration Tool via your SSH session:

sudo raspi-config

Raspberry Pi Localisation Options

  • Under Network Options, change the Hostname to something other than raspberrypi (most of the devices on my network are named after Transformers).
  • Under Localisation Options, go to the Change Locale options and add en-US.UTF-8 (or whatever your locale is) to your selected locales, then select it as the default locale (do not remove the default en-GB.UTF-8 as it seems to cause issues)
  • Under Localisation Options, change the timezone to match yours (unless you already did this in the Raspberry Pi Imager Advanced settings)

Update Raspbian and Packages

Once you've got everything up and running, you'll want to update all the Raspbian packages and upgrade any that need it using APT (Advanced Packaging Tool) by running:

sudo apt update

to update packages and then:

sudo apt-get upgrade -y

to upgrade any packages you have installed to their latest versions. This may take a while, so you may want to go grab a coffee, beer, tea...

Note: If at any point during an apt update your package cache file is corrupted, remove your apt lists and refresh them using:

sudo rm -r /var/lib/apt/lists/
sudo mkdir -p /var/lib/apt/lists/partial
sudo apt-get update

Backup and Restore a Raspberry Pi

Throughout the process of setting things up, you may want to have a backup of your Raspberry Pi so you don’t have to start from scratch if you make a mistake like I have (several times). You may even want to clone your Raspberry Pi after each successful step so you can return to it if the next step goes wrong. For instance, I was sure to create a backup of my Raspberry Pi after initial setup, after I had Pi-hole working, after I added Unbound, and after I got WireGuard setup. That way if I made any changes that broke my setup, I could always revert the previous working installation.

Backup the Raspberry Pi SD Card

There are many ways to do this, but if you're on a Mac the aforementioned ApplePi-Baker app is fantastic and handles backing up your Raspberry Pi's SD card, not to mention restoring from several different formats as well. ApplePi-Baker macOS App At any point you want to backup your Raspberry Pi's configuration, first shut down the device with:

sudo halt

or the more verbose:

sudo shutdown -h now

and then unplug your Raspberry Pi (or get a Pi Switch to make life easier). Remove the SD card from the Raspberry Pi and insert it into a supported SD card reader (like the Anker 2-in-1 card reader I mentioned earlier), and connect to your Mac.

When you open the ApplePi-Baker app, you should be able to select the SD card from the Select a Disk options (make sure you select the right disk), then choose the Backup option. In the file choose window, select IMG from the Format selections at the bottom of the window, and then give the backup file a name. This should take some time, be prepared to wait.

ApplePi-Baker Backup Process

Note: The IMG format allows ApplePi-Baker to shrink the Linux partition on backup and expand it on restore, saving you from having to backup the entire size of the SD card rather than just the actual contents.

Using the macOS Terminal

Another way to backup your SD card on a Mac is to open Terminal and type:

diskutil list

to see a list of drives attached to your Mac. To create a Disk Image of the SD card:

sudo dd if=/dev/rdisk2 of=~/RaspberryPiBackup.dmg

where /dev/rdisk2 is the path to your SD card’s disk (with an added r) and ~/RaspberryPiBackup.dmg is the path and filename on your Mac to save the Disk Image. Enter your Mac user’s password when prompted. This may take a while depending on the size of your SD card and what you have installed on it.

Note: If you see any input/output errors, try using Disk Utility instead.

Using the macOS Disk Utility

Open the macOS Disk Utility application, and choose View > Show All Devices. Right click on the device name of the SD card (not the individual partition(s)!) and choose the Image from ‘DEVICE NAME’ option. Give the file a name and choose a location to save it. Choose the DVD/CD master option for Format, and no Encryption. Disk Utility will create a .CDR file with your SD card’s files.

Note: Both the Disk Utility and Terminal methods failed for me, both creating input/output errors. Maybe it was my SD card or my card reader, but then using ApplePi-Baker gave me no issues, so I didn't bother to investigate further.

Restoring a Raspberry Pi from Backup

If you’ve made a backup of your Raspberry Pi’s SD card previously, you can restore it any time and overwrite your current configuration. Using the ApplePi-Baker app on macOS, this is a simple task.

First, shut down your Raspberry Pi:

sudo halt

and remove the SD card from your Raspberry Pi. Using a supported SD card reader, insert the SD card from your Raspberry Pi into your Mac. Launch the ApplePi-Baker app and select the correct SD card disk, then choose the Restore option. ApplePi-Baker will expand the backup file and overwrite the complete contents of your SD card with the backup file's contents, so make sure you really want to do this.

Using the macOS Terminal to Restore

You can also use the macOS Terminal application to this by typing:

diskutil list

to see a list of drives attached to your Mac. You'll need to unmount the SD card to proceed (your Mac can still see the files, but you won't see the mounted disk(s) anymore):

diskutil unmountDisk /dev/disk2

where /dev/disk2 is the path to your SD card’s disk. Restore the SD card from backup using:

sudo dd if=~/RaspberryPiBackup.dmg of=/dev/disk2

where /dev/disk2 is the path to your SD card’s disk and ~/RaspberryPiBackup.dmg is the path and filename on your Mac to save the Disk Image. This may take a while depending on the size of your SD card backup

Note: If you backed up the SD card as a .CDR, you can rename it to .ISO and restore it to any SD card with the free Etcher application for macOS.

Setting Up Pi-hole

Pi-hole provides ad-blocking at the network level, meaning you not only stop ads from making it to any of the devices on your network, but you also block the unnecessary network requests for those ads and thus reduce bandwidth usage. Pi-hole pairs nicely with a VPN (Virtual Private Network) so that you can connect remotely and still take advantage of ad-blocking from anywhere outside your network.

Pi-hole Dashboard

First, you'll need to install Pi-hole from the Raspberry Pi's command line using either the one-step automated install (piping to bash is controversial as it prevents you from reading code that will run on your system):

sudo curl -sSL https://install.pi-hole.net | bash

Or manually downloading the installer and running it locally on your Raspberry Pi using these two commands:

wget -O basic-install.sh https://install.pi-hole.net
sudo bash basic-install.sh

Note: If you receive the error Script called with non-root privileges using the one-step install, try the two-step instead.

During setup, select OK for the first few screens, then select either eth0 for ethernet (wired) or wlan0 for wireless (wifi) on the Choose An Interface screen. Next, select any Upstream DNS Provider since we’ll be using our own Unbound server later. Choose any Block Lists you want to use, or leave them all checked by default. Choose both IPv4 and IPv6 on the Select Protocols screen. Use the current network settings on the next screen, assuming you gave your Raspberry Pi a static IP address earlier. Then decide if you want to install the Web Interface for Pi-hole (and lighthttpd to serve it), which you'll typically want to keep an eye on your traffic and blocked queries (and to make additional configuration changes) in a web browser.

Lastly, decide how you want to log queries and what privacy level you want for FTL (Faster Than Light). Setup will continue on the console, and the Pi-hole DNS service will be up and running after several minutes.

Using Pi-hole’s Web Interface

After Pi-hole’s setup is complete, a default Web Interface password will be shown on the final screen, as well as on the console itself. You can change the password using:

pihole -a -p

Now you can access the Pi-hole Web Interface in your browser by going to http://raspberrypi.local/admin (if your device supports mDNS) or http://192.168.x.x/admin, where 192.168.x.x is the static IP of your Raspberry Pi (you can also use http://pi.hole/admin once you point your router to use Pi-hole as your DNS service in the next step). Go to Login, then enter your password and check the “Remember me for 7 days” checkbox before logging in. You won’t see much on the Dashboard yet since nothing on your network is using Pi-hole, but that should change momentarily.

Note: If there are errors receiving data and/or you see Lost Connection to API on your Admin Console dashboard, you may need to restart your Raspberry Pi. This can be done from the Pi-hole Admin Console under Settings.

Pi-hole Login

Use Pi-hole as Your DNS Server

To make sure Pi-hole is working, you can set a single device to use it as its DNS service or you can point your network’s router to it instead to force (almost) every device on your network to use Pi-hole as its DNS service. Most routers have a setting for Primary and Secondary DNS, and you'll want to point the Primary DNS Server to the static IP address of your Raspberry Pi (192.168.x.x) and the Secondary DNS Server to a 3rd party DNS service like Google (8.8.8.8) or Cloudflare (1.1.1.1) in case your Pi-hole server goes down for some reason and you don’t want to lose all connectivity to the outside world (like when you're fiddling around with your Raspberry Pi in the upcoming steps).

Restart your router and watch as the Pi-hole Dashboard (now available on your internal network at http://pi.hole/admin) fills up with blocked queries!

Note: If at any point your Raspberry Pi loses its connection with the outside world and you want to set a temporary DNS server to resolve it, run:

echo "nameserver 8.8.8.8" | sudo tee /etc/resolv.conf > /dev/null

to temporarily set the device's DNS server to Google until you can figure out what you did. This will reset on reboot.

Setup Unbound as Your DNS Service

Unbound is a validating, recursive, caching DNS resolver. It is designed to be fast and lean and incorporates modern features based on open standards.

Setting up Unbound DNS with your Pi-hole installation allows us to operate our own tiny, recursive DNS server instead of relying on (and sending data to) the big players like Google or Cloudflare. Installation is fairly straighforward.

To install Unbound on the Raspberry Pi:

sudo apt install unbound

Note: If you've installed Pi-hole first and then Unbound as I have here, you might see some errors during installation of the latter, specifically Job for unbound.service failed because the control process exited with error code. After some research, I decided to continue on with the Pi-hole guide to setting up Unbound, which seemed to work fine. I'm not sure what causes the errors, but I've decided not to investigate further at this time.

Optional: You can download the current root hints (list of primary root servers which are serving the root domain) file and move it into the Unbound file path, but this is only necessary if you are not installing Unbound from a package manager. Using the above command to install Unbound includes the root.hints file automatically. See the Pi-hole documentation on Unbound for more.

wget -O root.hints https://www.internic.net/domain/named.root

Then move the root.hints file to the Unbound configuration directory:

sudo mv root.hints /var/lib/unbound/

Configure Unbound DNS

Unbound includes a lot of different configuration options that you can adjust and try out. Feel free to scan the Unbound configuration file documentation for details about each option.

To get started, edit the Unbound configuration file for Pi-hole:

sudo nano /etc/unbound/unbound.conf.d/pi-hole.conf

and remove the contents of the file (there is likely nothing there yet) before copying and pasting the contents of the sample pi-hole.conf configuration file in this repository. When you're done, exit and save the file.

Unbound Configuration File

Configuration Details

The default port for Unbound is 53 but we're changing it to 5353 here. Feel free to change it to whatever you like, but you'll need to remember it later when we tell Pi-hole where to send upstream DNS requests:

port: 5353

For daily use, it's best not to increase the verbosity of the logging. If you're debugging a problem, feel free to up it from 1. For more information, see the Pi-hole documentation on Adding Logging to Unbound.

verbosity: 1

Here we're refusing connections to all interfaces and then we're allowing anything from this device (your Raspberry Pi) and anything from our local subnet (be sure to change 192.168.x.0 to whatever your local subnet is):

# IPs authorized to access the DNS Server
access-control: 0.0.0.0/0 refuse
access-control: 127.0.0.1 allow
access-control: 192.168.x.0/24 allow

If your router creates a "Guest Network" with a separate SSID and DHCP range, devices connecting to that wireless network will not be able to connect to the internet unless you grant access to that subnet. Uncomment one of the lines below or add your own based on your guest network's DHCP range:

# If you have a guest network with a separate DHCP range
#access-control: 172.16.1.0/24 allow
#access-control: 10.0.0.0/24 allow

Note: Devices connected to an AirPort guest network will not be able to use Pi-hole since your Raspberry Pi is on a separate DHCP range. They also will not have access to a DNS resolver, so they won't be able to connect to much of anything unless each device is set to manually connect to an outside DNS server, such as 1.1.1.1.

You can adjust the cache settings if you like. Instead of the default of not caching, here we set the minimum TTL (Time To Live) to 1 hour, afterwards the DNS will do another lookup of the cached data:

# Time To Live (in seconds) for DNS cache. Set cache-min-ttl to 0 remove caching (default).
# Max cache default is 86400 (1 day).
cache-min-ttl: 3600
cache-max-ttl: 86400

When Pi-hole was doing DNS, it created this custom record for http://pi.hole so we could easily reach the Web Interface without typing in the static IP address of the Raspberry Pi. Now that Unbound is our DNS, we'll need to create this custom record in the Unbound configuration file. Be sure to replace 192.168.x.x with the static IP address of your Raspberry Pi:

# Create DNS record for Pi-hole Web Interface
private-domain: "pi.hole"
local-zone: "pi.hole" static
local-data: "pi.hole IN A 192.168.x.x"

Once the configuration file is saved, start the Unbound DNS server:

sudo service unbound start

And test to make sure the Unbound DNS is running (be sure to use the port you set above):

dig pi-hole.net @127.0.0.1 -p 5353

Which should return some information, including a QUESTION SECTION and an ANSWER SECTION that includes pi-hole.net and an IP address.

Testing DNSSEC Validation

Run the following command:

dig sigfail.verteiltesysteme.net @127.0.0.1 -p 5353

Which should return a status of SERVFAIL and no ANSWER SECTION:

;; ->>HEADER<<- opcode: QUERY, status: SERVFAIL, id: xxxxx

And then run this command:

dig sigok.verteiltesysteme.net @127.0.0.1 -p 5353

Which should return a status of NOERROR and an ANSWER SECTION:

;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: xxxx

Allow Pi-hole to Use Unbound DNS

Now that your Unbound recursive DNS resolver is running locally, we'll force Pi-hole to use it for DNS rather than an outside source like Google (8.8.8.8) or Cloudflare (1.1.1.1) and keep all of our network traffic contained. Any traffic on your network will be sent to Pi-hole, which in turn will use Unbound for DNS resolution before blocking the appropriate domains and returning data.

First, open the Pi-hole Web Interface in a web browser on your local network: http://pi.hole/admin

Then go to Settings > DNS and uncheck any third party Upstream DNS Servers you had selected during setup. To the Custom 1 (IPv4) Upstream DNS Servers input, add:

127.0.0.1#5353

Where 127.0.0.1 points the Pi-hole server (the Raspberry Pi) to itself on port 5353. If you changed the port in your Unbound configuration file, use that port here instead.

Pi-hole DNS Settings

On the same page, uncheck Never forward non-FQDNs and Never forward reverse lookups for private IP ranges to ensure that Pi-hole can access local hostnames.

Next, leave Use DNSSEC unchecked as Pi-hole is going to be using your Unbound DNS, which already enables DNSSEC (Domain Name System Security Extensions).

Lastly, check Use Conditional Forwarding and enter your local network in CIDR notation (typically 192.168.1.0/24 in our case), your router’s IP address (typically something like x.x.x.1 on your subnet), along with your Local Domain Name (optional and can be set on your router, usually under the DHCP settings, to something like home).

Pi-hole Advanced DNS Settings

When you're done, don't forget to save your settings.

Disable openresolv for Unbound

Debian Bullseye releases automatically install a package called openresolv with a certain configuration that will cause unexpected behaviour for Pi-hole and Unbound. For more information, see the Pi-hole documentation on Unbound.

Check to see if this service is enabled for your OS:

systemctl is-active unbound-resolvconf.service

If the command returns active, disable the service using the following:

sudo systemctl disable --now unbound-resolvconf.service

Then restart Unbound:

sudo service unbound restart

Verify DNSSEC Signatures

To ensure that Unbound is configured correctly, visit this DNSSEC Resolver Test in a web browser using a device that's currently within your network and using your Raspberry Pi as a DNS server. Use the Start test button and this website will let you know whether or not Unbound is validating DNSSEC signatures.

Setting Up a VPN with WireGuard

WireGuard is an extremely simple yet fast and modern VPN that utilizes state-of-the-art cryptography. It aims to be faster, simpler, leaner, and more useful than IPSec while avoiding the massive headache. It intends to be considerably more performant than OpenVPN.

Installing WireGuard

With the latest release of Raspberry Pi OS (Bullseye), installation of WireGuard and WireGuard Tools is as simple as running:

sudo apt-get install wireguard wireguard-tools

Intiial Configuration

To get started, we'll need to be the root user on your Raspberry Pi to continue with the WireGuard configuration:

sudo -i

Then we'll switch to the directory where we'll store the WireGuard keys (if the directory doesn't exist, this command will create one since we're now the root user):

cd /etc/wireguard

Set permissions on the entire directory with the umask command so that only the root user can read or write data here:

umask 077

Next, generate the server’s private & public keys in a single command:

wg genkey | tee server.key | wg pubkey > server.pub

Then generate a client’s private & public keys (where "client_name" is the name of the device that you will be connecting from outside your network with):

wg genkey | tee client_name.key | wg pubkey > client_name.pub

Though completely optional, it's also recommended to generate a Pre-Shared Key (PSK) for each client in addition to the keys above for an extra layer of security.

wg genpsk > client_name.psk

Run the above command with other client names to setup as many VPN devices as you need. To confirm the keys were generated and have the correct file permissions:

ls -la

Finally, output your new WireGuard keys to the console and save them (somewhere safe, otherwise be sure and delete them when we're done here) for the next steps:

cat server.key
cat server.pub
cat client_name.key
cat client_name.pub
cat client_name.psk

Lastly, exit root before continuing.

Enable IP Forwarding

To enable IP forwarding, you'll need to uncomment the net.ipv4.ip_forward=1 line from your /etc/sysctl.conf file:

sudo nano /etc/sysctl.conf

Or you can type the following command to handle this for you:

sudo perl -pi -e 's/#{1,}?net.ipv4.ip_forward ?= ?(0|1)/net.ipv4.ip_forward = 1/g' /etc/sysctl.conf

Finally, reboot your Raspberry Pi:

sudo reboot

After reboot, verify that IP forwarding is enabled by running:

sysctl net.ipv4.ip_forward

You should see net.ipv4.ip_forward = 1 as a result, otherwise add the above command to your /etc/sysctl.conf file.

Configure WireGuard Server

Create and edit the WireGuard configuration file:

sudo nano /etc/wireguard/wg0.conf

and replace the contents with the WireGuard wg0.conf from this repository.

WireGuard Configuration File

Configuration Details

This is the WireGuard interface, which will create a virtual subnet of 10.100.0.0 and assign itself an internal IP address of 10.100.0.1. You can change this if you'd like, but you'll also need to change the internal IP of VPN clients as well.

[Interface]
Address = 10.100.0.1/24

The default port for WireGuard is 51820, which you can change if you'd like. You'll also need to open up this port on your router, otherwise incoming VPN traffic from outside your network will not make it to WireGuard. Information on how to do this is later in the guide.

# WireGuard port, change to anything that doesn’t conflict
ListenPort = 47111

Note: Some public wifi networks will block all ports other than 80 (TCP), 443 (TCP), and 53 (UDP) for HTTP, HTTPS, and DNS respectively. If you are connected to a public wifi network that does this, you will not be able to connect to your WireGuard VPN. One way around this is to set your WireGuard ListenPort to 53 and create a forward on your network's router on port 53, thus circumventing the issue with blocked ports. Do this at your own risk, and definitely, do not enable Pi-hole's Listen on all interfaces, permit all origins DNS option if you are forwarding port 53 on your router.

Normally we would replace 192.168.x.x with the static IP address of your Raspberry Pi, but we want Unbound to handle DNS and providing a value here would force WireGuard to use openresolv, which we do not want.

# Normally static IP of Raspberry Pi, but we don't want
# resolv.conf to be touched by WireGuard
#DNS = 192.168.x.x

Replace <server.key> with the output of your cat server.key command earlier:

PrivateKey = <server.key>
Setup WireGuard Client Connections

The next section of the WireGuard configuration file is for clients that connect to the VPN. For each client (device), you'll need to add another [Peer] section here and also create a separate client configuration file (details for that are next).

Replace <client_name.pub> with the output of your cat client_name.pub command earlier, as well as <client_name.psk> with the output of cat client_name.psk:

[Peer]
PublicKey = <client_name.pub>
PresharedKey = <client_name.psk>

Using the virtual subnet created by WireGuard, give this device an internal IP address of 10.100.0.2:

AllowedIPs = 10.100.0.2/32

Once your WireGuard configuration file is complete, exit the nano editor and save your changes.

Configure a WireGuard Client

Now that WireGuard is configured, we'll need to create a client configuration file for each VPN client we want to connect to the network. First, create and edit your first client configuration file:

sudo nano /etc/wireguard/client_name.conf

Name this file based on what client it's for and replace the contents with the WireGuard client peer1.conf from this repository.

Configuration Details

Use the same virtual IP address that you used in the wg0.conf file earlier for this client:

[Interface]
Address = 10.100.0.2/32

Once again, leave the DNS entry commented out so that Unbound can handle our DNS requests:

# Normally static IP of Raspberry Pi, but we don't want
# resolv.conf to be touched by WireGuard
#DNS = 192.168.x.x

Replace <client_name.key> with the output of your cat client_name.key command earlier:

PrivateKey = <client_name.key>

Replace <server.pub> with the output of your cat server.pub command earlier:

[Peer]
PublicKey = <server.pub>

The Endpoint here refers to the public IP address and port number for incoming traffic to your network's router from the outside world. This is necessary so that devices outside your network know where to go to connect to your internal network's VPN. Your public IP address is available by visiting IP Leak, and the ListenPort should be set to the same port you set in your WireGuard's wg0.conf file (the default port is 51820).

So you can edit this line:

Endpoint = YOUR-PUBLIC-IP/DDNS:ListenPort

To include your public IP address and the WireGuard port you set previously:

Endpoint = 11.22.33.44:51820

For this use case, we're using a full tunnel rather than a split tunnel (which allows some network traffic to come through outside of the VPN).

# For full tunnel use 0.0.0.0/0 (with ", ::/0" for IPv6) and for
# split tunnel use 192.168.1.0/24 or whatever your router’s subnet is
AllowedIPs = 0.0.0.0/0

Optional: Setup Dynamic DNS for Your Public IP address

If your ISP does not provide you with a static IP address (most don’t), and your IP changes for some reason (cable modem reboot, connectivity issues, etc.), your home network may be unreachable from the outside until you update it in your configuration files. The solution is to use a DDNS (Dynamic DNS) service where you choose a readable domain name and can automatically notify the service when your public IP address changes.

So instead of worry about whether your public IP address is 98.10.200.11 or 98.10.200.42, you can instead point a domain name like username.us.to at your public IP address and have the DDNS service update the domain record when your public IP address changes.

There are plenty of DDNS services out there, but I’m using Afraid.org’s Free DNS service because it doesn’t nag you to login every 30 days, even on the completely free plan (it does however mark your account as "dormant" after 6 months without a login, but it's easy to resume your account without upgrading).

Get a Free DNS Subdomain

First, create a Free DNS account at https://freedns.afraid.org/.

After account creation, verify your account using the link you’ll receive in your email. Then go to Add Subdomain and enter a Subdomain (a username, your name, company name, etc.) and choose a Domain (there are many to choose from besides what’s listed, follow the instructions to find the rest). Leave Type set to an A record, TTL is set to 3600 for free accounts, and Wildcard functionality is only for paid accounts.

Free DNS Add Subdomain

Your public IP address should be automatically filled in, but you can visit IP Leak in a browser to get your public IP address if you need to.

Enter the CAPTCHA text and hit Save to continue. You should now have a shiny new subdomain pointing to your network’s public IP address! But what if your public IP address changes at some point?

Automatically Update Your Public IP Address

Having a domain name pointed to your public IP address is useless if that IP address changes in the future, which is why DDNS services exist in the first place. We'll need to update our Free DNS record if our network's public IP address changes, which is fairly simple to do.

While logged in at Free DNS, go to the Dynamic DNS page and look for your new subdomain record. Right click the Direct URL link associated with your subdomain record and choose Copy Link. We'll use this to update your subdomain record directly from the Raspberry Pi.

Free DNS Domain Record

On the Raspberry Pi, create a cronjob that runs every 5 minutes (replacing the XXXXX with the unique identifier in your Direct URL):

crontab -l | { cat; echo "*/5 * * * * curl https://freedns.afraid.org/dynamic/update.php?XXXXX”; } | crontab -

You’ll see no crontab for ... on the console, you can safely ignore that. You can change the timing from 5 minutes to 20 minutes (or whatever you'd like) by adjusting the */5 * * * * part to */20 * * * *.

Note: If the above command doesn't work, you can manually edit your crontab with crontab -e and choose an editor (nano is usually the default) and then copy and paste the */5 * * * * curl https://freedns.afraid.org/dynamic/update.php?XXXXX cron job into the file, saving it and exiting before continuing.

Verify that you’ve added the cronjob correctly with:

crontab -l

Once you've finished, restart the cron service with:

sudo service cron restart

Now your DDNS subdomain will always point to the correct public IP address of your network, and VPN clients will be able to reach your network remotely regardless of whether your public IP address changes.

Using a Dynamic Subdomain Instead of a Public IP address

Go back to your WireGuard client configuration file and use your new DDNS subdomain with the ListenPort you set earlier and never worry about your public IP address changing! In the /etc/wireguard/peer1.conf file, edit the Endpoint:

Endpoint = username.us.to:51820

using the subdomain you chose on Free DNS and the ListenPort you set in your /etc/wireguard/wg0.conf file.

Setting Up Your Phone to Use the VPN

Unlike IPSec or IKEv2, WireGuard isn’t built into the Android or iOS operating system (yet), so you’ll have to download the WireGuard app to each device to connect to your VPN. Here are some of the VPN clients available:

Export Client Configuration with a QR Code

Rather than manually enter all the WireGuard configuration details into your phone, we can create a QR code directly on the Raspberry Pi console that your phone's native WireGuard app can scan and automatically fill out the details for you.

First, install the QR encoder on the Raspberry Pi:

sudo apt install qrencode

Become the root user in order to read the WireGuard client config:

sudo -i

Create a QR code from the VPN client configuration we set up earlier (where <client_name> is the name of the file you created):

qrencode -t ansiutf8 < /etc/wireguard/<client_name>.conf

Note: You may have to adjust the size of your terminal/console window to properly show the QR code generated

Then exit to return to your pi user.

Import Client Configuration Using the QR Code

Open the WireGuard app on your phone, tap Add a tunnel and select the Create from QR code option. Scan the QR code with your phone’s camera, give the tunnel a name, and allow WireGuard to add VPN configurations to your phone's operating system.

Now you can enable or disable VPN access directly through the WireGuard app!

Finish WireGuard Installation

On your Raspberry Pi, there are a few more steps needed to complete the setup of the WireGuard VPN. First, allow WireGuard to start on boot:

sudo systemctl enable wg-quick@wg0

Run a "soft reload" of the systemd manager:

sudo systemctl daemon-reload

And then start WireGuard using the systemd manager:

sudo systemctl start wg-quick@wg0

You can also start WireGuard directly using:

sudo wg-quick up wg0

If WireGuard is setup correctly, there will be no output. To check and see if the WireGuard interface was created successfully:

ifconfig wg0

You should see that 10.9.0.1 internal IP address we created in the wg0.conf file, along with some other flags. For more detailed information about the WireGuard server and client(s), run:

sudo wg

You should see interface wg0 and a peer:

interface: wg0
  public key: XXXXXXXXXXXXXXXXXXXXX
  private key: (hidden)
  listening port: 47111

peer: XXXXXXXXXXXXXXXXXXXXX
  preshared key: (hidden)
  allowed ips: 10.100.0.2/32

Adding Additional Clients

Follow the steps above to add peers to WireGuard using the wg0.conf configuration file and a new peer configuartion file. Once these changes have been made, restart WireGuard for the changes to take effect:

sudo systemctl restart wg-quick@wg0

Open WireGuard VPN Port on Your Router

Without this step, you will not be able to reach your VPN from outside of the network. None of the write-ups I found mentioned this step, most likely assuming you would already know to do this (I didn't).

In order to reach your VPN from outside your network, you'll have to set up a UDP-specific port forward on your network's router that passes traffic on that port to an internal IP address of your choosing. Generally speaking, this might look like:

Description: WireGuard VPN
Public UDP Ports: 47111
Private IP Address: 192.168.x.x
Private UDP Ports: 47111

Where 192.168.x.x is the internal static IP address of the Raspberry Pi running WireGuard, and 47111 is whatever you set the ListenPort to in your /etc/wireguard/wg0.conf file. Each router has different settings available, but the above is from my Apple Time Capsule's AirPort Utility in macOS.

Note: I'm passing just UDP traffic on this port, as WireGuard uses UDP and not TCP.

Once you've added this port forwarding on your network's router, restart the device and now you should be able to connect to your WireGuard VPN from outside your network and enjoy the benefits of network-level ad-blocking from anywhere, at any time!

Checking for DNS Leaks

When connected to your VPN from outside the network, you can check to see if there are any leaks in your DNS lookups using the DNS Leak Test service. For more information, read What is a DNS leak and why should I care?

References

There are several write-ups out there on how to do this, as well as install scripts to do it for you. Since the Raspberry Pi was meant to be a learning tool, I used this opportunity to figure things out on my own with the help of documentation from both software creators and the community. If it weren't for the latter, I doubt I would've been able to do this on my own. Thanks to everyone who has taken the time to share their knowledge, and experience, in setting up a Raspberry Pi.

To-Do