Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 37 ยท Deployment and Automation

Hardening Your Pi: Updates, Firewall and Safe Defaults

Secure a Raspberry Pi that is on a network: strong accounts, key-only SSH, automatic updates, a ufw firewall, fail2ban, minimal services and secrets handling, with an audit script model.

A Pi is a full Linux computer. The moment it joins a network, it can be probed, and once it is reachable from the internet, it will be, within minutes. Compromised Pis are used for spam, crypto mining and attacks on other machines. Most attacks are not clever: they try default passwords and old software. A short checklist, done once, blocks nearly all of them.

Everything here changes a real system, so the commands are read-only on this site. The runnable blocks are Python audit and rule-evaluation models, which you can use as the logic for your own checker.

1. Accounts and passwords

  • Use a unique username and a long password at first setup (Raspberry Pi Imager lets you set both). Old images with the user pi and a known password have been abused for years.
  • Remove accounts you do not use; lock them with sudo passwd -l name.
  • Do not log in as root; PermitRootLogin no in the SSH daemon.
  • Keep sudo for your admin user and require a password for it (the Pi OS default allows passwordless sudo for the first user; remove /etc/sudoers.d/010_pi-nopasswd if you want a password).

2. SSH properly

As in the SSH lesson: key authentication, no password logins, no root login. Add limits in /etc/ssh/sshd_config.d/10-hardening.conf:

TEXT
PasswordAuthentication no
PermitRootLogin no
MaxAuthTries 3
AllowUsers ana

Test with a second session, then sudo systemctl reload ssh. Moving SSH to another port stops some noise, but is not security by itself.

3. Keep software updated

Most breaches use known flaws that have been fixed for months. Turn on automatic security updates:

Terminal
sudo apt install unattended-upgrades
sudo dpkg-reconfigure -plow unattended-upgrades

It installs security patches nightly (see /etc/apt/apt.conf.d/50unattended-upgrades). Still run sudo apt update && sudo apt full-upgrade manually from time to time, and reboot after kernel updates. Python packages inside virtual environments are not covered: pip list --outdated shows them.

4. A firewall with ufw

A firewall refuses connections to ports you did not intend to offer. ufw ("uncomplicated firewall") is friendly:

Terminal
sudo apt install ufw
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow from 192.168.1.0/24 to any port 22 proto tcp   # SSH from LAN only
sudo ufw allow 80/tcp                                          # web server
sudo ufw enable
sudo ufw status numbered

Allow SSH before you enable the firewall, or you will cut yourself off. Rules are evaluated top to bottom and the first match decides, with the default policy as the last resort. This model evaluates connection attempts against a rule list, the same logic ufw uses:

Python Stand-in: evaluate firewall rules

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

5. Slow down guessers with fail2ban

fail2ban reads logs and temporarily bans addresses that fail logins repeatedly:

Terminal
sudo apt install fail2ban
sudo systemctl enable --now fail2ban
sudo fail2ban-client status sshd

Its default SSH protection is enough for most. With key-only logins the guesses cannot succeed anyway, but banning cuts log noise and load. The idea is a sliding window, which you can see here:

Python Stand-in: ban after repeated failures

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

6. Minimal services and ports

Every listening program is attack surface. Look at what runs:

Terminal
sudo ss -tulpn              # listening TCP/UDP ports and their programs
systemctl list-unit-files --state=enabled
sudo systemctl disable --now avahi-daemon   # if you do not use .local names

Disable Bluetooth, VNC, the desktop and other unused interfaces on a headless server. Bind your own apps to 127.0.0.1 unless they must be reachable, and put them behind nginx with HTTPS (Let's Encrypt certbot is free).

7. Secrets

Do not hard-code passwords or API keys in scripts that are shared or committed to Git. Put them in a file readable only by the service user and load them with systemd's EnvironmentFile=:

Terminal
sudo install -m 600 -o weather -g weather /dev/null /etc/weather.env
echo "API_TOKEN=abc123" | sudo tee /etc/weather.env > /dev/null

Add .env to .gitignore. If a secret ever leaks, replace it; deleting the commit is not enough.

An audit script

A routine check is more reliable than memory. This stand-in takes a dictionary of facts (what ss, ufw and sshd -T would report) and prints findings:

Python Stand-in: a security audit report

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A hardened Pi still needs physical care: anyone with the SD card can read its files. Do not store secrets you cannot afford to lose on a device that sits in a public place, or encrypt the data partition.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why must you allow SSH in ufw before enabling it?

    With a default deny-incoming policy, no allow rule for SSH means no remote login.
  2. 2. What does unattended-upgrades do?

    It applies security updates on a schedule without you running apt.
  3. 3. Which command lists programs listening on network ports?

    ss -tulpn prints TCP and UDP listeners with the owning process.
  4. 4. What is the safest place for an API token used by a systemd service?

    Restricted permissions and keeping it out of code limit who can read the secret.

Summary

  • Use unique accounts and strong or key-based authentication; no root over SSH.
  • Turn on automatic security updates and reboot after kernel changes.
  • Default-deny firewall (ufw), with SSH allowed first and only needed ports open.
  • fail2ban throttles guessers; close or bind to loopback anything you do not need.
  • Keep secrets out of code, check regularly with an audit.

Next: Logging, Monitoring and the Watchdog