July 14, 2019

Uncomplicated Firewall (UFW) on a Raspberry Pi

How to install and configure ufw on a Raspberry Pi to provide a firewall for running a simple blog over the internet

Uncomplicated Firewall (UFW) on a Raspberry Pi

Because no one likes getting hacked

When I'm going to expose a Raspberry Pi to the wild internet - I use a firewall to be sure that I've intentionally locked down everything on my network connections that I'm not going to be using.

For my Hello World project, I used ufw. This guide will show you how I set that up.

Install

Install ufw:

sudo apt install ufw

Configure

  1. Create a place for your configuration to live
  2. Give your configuration script executable rights
  3. We're going to deny all incoming by default, and then explicitally allow incoming for:
    • ssh
    • HTTPS
    • HTTP
      And allow all outgoing
mkdir -p ~/Documents/Toolkit/ufw
cd ~/Documents/Toolkit/ufw
touch setup_ufw.sh
chmod +x ./setup_ufw.sh

Now edit your setup_ufw.sh using your favorite editor

vi setup_ufw.sh

And paste and save this configuration to the setup_ufw.sh file:

#!/usr/bin/env bash
ufw default deny incoming
ufw default allow outgoing
ufw allow ssh
ufw allow 80/tcp
ufw allow 443/tcp
ufw enable

Now run your script as a superuser:

sudo ./setup_ufw.sh

Check Status

To check the status of your firewall at anytime:

sudo ufw status verbose

Done

Congratulations, your firewall is configured and running.


Turning ufw off

If you need to disable the ufw firewall at any time you can run:

sudo ufw disable

Obviously, if you're exposing your Raspberry Pi to the internet - you probably want to have this on.


Be careful if you're exposing ssh to the world

My internet comes into my house and is plugged into a router that sits inbetween the Raspberry Pi that hosts this blog and the internet. I do not expose any ports for ssh to this Pi. So, from the internet, you can only get to port 80 and port 443 for the blog. This means that in order to ssh to this Raspberry Pi, you have to be on my internal network.

If you're going to also forward a port for ssh to your Raspberry Pi (the default is port 22) so that you can ssh to it from over the internet; please make sure that you've locked down your Raspberry Pi appropriately. Including but not limited to removing the default user and disabling password login. This way, only somebody with your private ssh key can access your Raspberry Pi.

You would be surprised how fast a Raspberry Pi with the default username/password could get hacked if openly exposed to the internet. War stories anyone? Feel free to share in the comments section.


Credit:
Original Idea:
I first followed this guide but his guide is for setting up a blog on a different hosting platform. Alex no longer runs his blog on a Raspberry Pi - I don't have unstable internet problems, so I decided to provide a similar guide here.
Photos:
Brick Wall - Photo by Viktor Forgacs on Unsplash
Shield Vector - freepik.com