Secure your Raspberry Pi – beginner guide

How to Secure Your Raspberry Pi for Internet Access

The moment your Raspberry Pi is reachable from the internet, whether it’s a home server, Pi-hole, Nextcloud or smart home hub, automated scanners come knocking. They sweep the internet around the clock for open SSH ports and try well-known usernames and passwords. This guide shows you how to lock down the Pi itself so those attempts go nowhere, covering access, SSH, the firewall and updates, in an order that won’t lock you out along the way. Individual services such as Nextcloud or a web server need their own upkeep on top of that.

I tested every command and config file in October 2026 against the packages in the current Raspberry Pi OS, on a test system running a real SSH server, two-factor login and Fail2Ban rather than on a Pi sitting openly on the internet. Wherever common advice locks you out or only looks secure, you’ll find a note at that step.

In short

The best protection is to open as few ports on your router as possible, ideally none, and to reach the Pi through a VPN such as Tailscale. Either way, allow key-based SSH logins only and put a firewall in front, adding Fail2Ban once SSH is reachable from the internet through port forwarding.

  • No open ports: use Tailscale or Raspberry Pi Connect instead of port forwarding. WireGuard needs just a single UDP port.
  • Put your SSH settings in a file of their own under /etc/ssh/sshd_config.d/, not in sshd_config. Otherwise a file written by Raspberry Pi Imager can quietly switch password logins back on.
  • Before restarting SSH, check the config with sudo sshd -t and keep your current session open until you can log in from a second window.

First decide: does your Pi need to be exposed at all?

Every port you forward to your Pi is open to the entire internet. For most use cases there are now ways to get in without opening a port, which leaves nothing for anyone outside to knock on:

OptionOpen port on your routerGood for
Tailscale (covered below)noneSSH and every service on the Pi, from your own devices
WireGuardone (UDP): on the router if it runs the VPN server itself, otherwise forwarded to the Pithe same as Tailscale, without a third-party service in between
Raspberry Pi Connectnonethe Pi’s terminal and desktop in your browser
Cloudflare Tunnelnoneweb services such as Nextcloud for other people, no app needed
Port forwardingyes, one per servicewhen other people’s devices need direct access without a VPN

My recommendation: for your own access on the go, use a VPN. Tailscale is the quickest to set up. Port forwarding only makes sense when other people need to reach a service without installing anything, and even then SSH shouldn’t be one of the forwarded ports. The SSH and firewall steps below are worth doing either way, and Fail2Ban matters most once SSH is reachable from the internet through port forwarding. If you use WireGuard or Raspberry Pi Connect instead of Tailscale, skip the Tailscale section. The firewall section covers what WireGuard needs.

The basics for every Pi

A tip before you start: if you want to see what these steps achieve, run Lynis once now and note the score, as described in Check your setup with Lynis. A second run at the end gives you the comparison.

Your own user and a strong password

The old default user pi with the password raspberry has been gone since April 2022. You now pick a username and password during setup, usually in Raspberry Pi Imager. Choose a password of at least 12 characters that you don’t use anywhere else. You can change it at any time with:

passwd

If you’re still running a very old install with a pi user, id pi will show it. In that case, create your own user with sudo rights, log in as that user, check that sudo works, and only then lock the old account:

sudo adduser yourname
sudo usermod -aG sudo yourname

# only after logging in successfully as yourname:
sudo passwd -l pi

For more on the old default credentials and how to reset a forgotten password, see our guide to Raspberry Pi default passwords.

Install updates automatically

Updates close known holes, and known holes are exactly what the scanners are looking for. The unattended-upgrades package installs updates from the Debian archive, including all security updates, in the background every day:

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

Answer “Yes” when it asks about automatic updates. One thing to know: out of the box it only handles packages from the Debian archive. The kernel, firmware and the other packages from the Raspberry Pi archive aren’t included, so keep updating those yourself with sudo apt update && sudo apt full-upgrade. Our guide on updating Raspberry Pi OS has the details.

Check what’s listening on your Pi

Only a service that waits for connections on a port can be attacked. This command lists every service accepting connections over TCP or UDP, along with its port and program name:

sudo ss -tulnp

Entries on 127.0.0.1 or [::1] are only reachable from the Pi itself. Anything on 0.0.0.0 or * is listening on the whole network. To see every running service, including ones without an open port, use systemctl list-units --type=service --state=running. If you don’t need a service, stop it and remove it from startup, here using Bluetooth as an example:

sudo systemctl disable --now bluetooth

Remote access without open ports: Tailscale (recommended)

Tailscale links your devices into a private network built on WireGuard. The Pi makes the connection outwards itself, so you don’t need to open a port on your router or set up dynamic DNS. It’s free for personal use: according to its pricing page (as of October 2026) that covers up to six users and as many of your own devices as you like. You’ll need an account, which you can create with a Google, Microsoft or GitHub login, for example.

On the Pi, the official script installs Tailscale and the second command signs the Pi in:

curl -fsSL https://tailscale.com/install.sh | sh
sudo tailscale up

tailscale up prints a link. Open it in your browser and sign in, and the Pi joins your Tailscale network. To see its address there (always in the 100.x.y.z range), run:

tailscale ip -4

Install the Tailscale app on your phone and laptop as well and sign in with the same account. From there you can reach the Pi at that address, for example with ssh yourname@100.x.y.z, whether you’re at home or out and about. If you’d rather not rely on a third-party service, you can build the same thing with your own WireGuard server.

Lock down SSH – in this order

SSH is the way in that attackers are after. The goal is that only someone holding the right key can log in, and passwords no longer count. Stick to the order below: if you turn off password logins before your key is on the Pi, you won’t get back in over SSH.

Step 1: Create a key and copy it to the Pi

On your computer, not on the Pi, generate a key pair, in PowerShell on Windows or in the terminal on Linux and macOS. Press Enter to accept the default location. A passphrase is a good idea: it protects the key if someone gets hold of your computer:

ssh-keygen -t ed25519

On Linux and macOS, ssh-copy-id copies the public key to the Pi. It asks for your password one last time:

ssh-copy-id yourname@raspberrypi.local

Windows doesn’t come with ssh-copy-id. In PowerShell, this command does the same job:

Get-Content "$env:USERPROFILE\.ssh\id_ed25519.pub" | ssh yourname@raspberrypi.local "mkdir -p ~/.ssh && chmod 700 ~/.ssh && tr -d '\r' >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys"

Replace yourname and raspberrypi.local with your username and the Pi’s hostname or IP address. Then log in with ssh yourname@raspberrypi.local. If SSH only asks for your key’s passphrase and not for the Pi’s password, it worked. The SSH guide covers this in more detail in its SSH key section.

Step 2: Turn off password logins in a file of their own

Most guides tell you to edit /etc/ssh/sshd_config. On Raspberry Pi OS that often doesn’t work. The SSH server reads every file in /etc/ssh/sshd_config.d/ first and uses the first value it finds for each setting. If you enabled SSH with a password in Raspberry Pi Imager, that folder contains 50-cloud-init.conf with PasswordAuthentication yes. That line then wins, and password logins stay open even if sshd_config says PasswordAuthentication no.

So create a file of your own. The 01- at the start of the name makes sure it’s read before the Imager file:

sudo nano /etc/ssh/sshd_config.d/01-hardening.conf

Add the following:

# Key-based logins only
PasswordAuthentication no

# No direct root login
PermitRootLogin no

# Drop the connection after 3 failed attempts
MaxAuthTries 3

Save with Ctrl+O and Enter, then exit nano with Ctrl+X.

Step 3: Check, restart, test

Check the configuration before restarting SSH. If sshd -t prints nothing, you’re good. The && makes sure SSH only restarts if the config is free of errors. If you see an error, fix the file first:

sudo sshd -t && sudo systemctl restart ssh
Keep your current session open

Restarting the SSH service doesn’t end existing connections. So leave your current window open and test the login from a second one. If anything goes wrong, you can undo the change from the first window. If you’re already locked out, see If you’ve locked yourself out.

In the second window, logging in with your key should work. An attempt without the key, on the other hand, should fail straight away with Permission denied (publickey):

ssh -o PubkeyAuthentication=no yourname@raspberrypi.local

You can also ask the SSH server on the Pi which values it’s actually using. You want to see passwordauthentication no and permitrootlogin no:

sudo sshd -T | grep -E 'passwordauthentication|permitrootlogin|maxauthtries'
Terminal: sudo sshd -T showing maxauthtries 3, permitrootlogin no and passwordauthentication no
What you want to see: the SSH server reports passwordauthentication no, even though Imager’s 50-cloud-init.conf with PasswordAuthentication yes is still there.

Set up a firewall with UFW

UFW (Uncomplicated Firewall) blocks every incoming connection you haven’t explicitly allowed. That includes services you use on your home network, so sort out two things before switching the firewall on.

Your home network: ip -4 addr show shows the Pi’s address. If it’s something like 192.168.1.23/24, your network is 192.168.1.0/24. Many routers use 192.168.0.x/24 instead. Use your own network in all the rules below.

Your services: sudo ss -tulnp lists every port on which the Pi accepts connections, for both TCP and UDP. Any service that other devices use needs its own rule in a moment.

Start with the default policy and SSH, here only from your home network and over Tailscale:

sudo apt install ufw

# Default: block incoming, allow outgoing
sudo ufw default deny incoming
sudo ufw default allow outgoing

# Allow SSH from your home network
sudo ufw allow from 192.168.1.0/24 to any port 22 proto tcp

# SSH over IPv6 on your home network (names like raspberrypi.local)
sudo ufw allow from fe80::/10 to any port 22 proto tcp

# Tailscale only: allow everything over Tailscale (your own devices)
sudo ufw allow in on tailscale0

You need the IPv6 rule because names like raspberrypi.local often resolve to an IPv6 address first. If the name still doesn’t work, connect using the Pi’s IPv4 address. The last rule makes every service on the Pi reachable over Tailscale. From your home network, though, each additional service needs a rule of its own. Three typical examples:

# Pi-hole: DNS (TCP and UDP) and web interface
sudo ufw allow from 192.168.1.0/24 to any port 53
sudo ufw allow from 192.168.1.0/24 to any port 80,443 proto tcp

# Home Assistant
sudo ufw allow from 192.168.1.0/24 to any port 8123 proto tcp
Don’t forget Pi-hole

If Pi-hole runs on the Pi and the rule for port 53 is missing, no device in your home can resolve a single website. If Pi-hole is also your DHCP server, you need sudo ufw allow 67/udp as well, without limiting it to your home network: devices asking for an address don’t have one yet.

Only now switch UFW on and check the rules. If UFW asks whether it may disrupt existing SSH connections, answer y, since the SSH rule is already there:

sudo ufw enable
sudo ufw status verbose
Terminal: sudo ufw status verbose with rules for SSH, Tailscale, Pi-hole and Home Assistant from the home network 192.168.1.0/24
All the rules from this section active: SSH and services from the home network only, everything over Tailscale.

Then test from a second window that SSH still works before you close the first one. If you run a WireGuard server on the Pi instead of Tailscale, it needs its port and its interface: sudo ufw allow 51820/udp (or your port) and sudo ufw allow in on wg0. If your VPN devices should also reach other devices on your home network through it, add sudo ufw route allow in on wg0. Raspberry Pi Connect only makes outgoing connections and doesn’t need a rule. If WireGuard runs on your router, your devices come in from the home network and the home network rule covers them. If you really do need SSH reachable from the internet through port forwarding, allow the port for everyone with sudo ufw allow 22/tcp. To remove a rule, repeat it with delete in front, for example sudo ufw delete allow from 192.168.1.0/24 to any port 8123 proto tcp.

Docker bypasses UFW

Ports you publish in Docker with -p or under ports: in a Compose file are reachable even if UFW doesn’t allow them. Docker adds its own firewall rules that take effect before UFW’s (Docker docs on UFW). If a container should only be reachable from the Pi itself, bind it to the local address, for example -p 127.0.0.1:8080:80. Our guide on how to install Docker on Raspberry Pi has more on this.

Fail2Ban against login attempts

Fail2Ban watches login attempts and bans an IP address for a while when it gets things wrong too often. If your Pi only accepts keys, nobody gets in that way regardless. Fail2Ban then mainly slows down the scanners that try unknown usernames, and keeps your log tidy. With its default settings, it doesn’t count failed attempts with the wrong key for a user that does exist on the Pi. If SSH is reachable from the internet through port forwarding, it’s still a must.

sudo apt install fail2ban
sudo nano /etc/fail2ban/jail.local

Put the rule for SSH in the new file. If you changed the SSH port, enter it under port:

[sshd]
enabled = true
port = 22
maxretry = 5
findtime = 600
bantime = 3600
ignoreip = 127.0.0.1/8 ::1 192.168.1.0/24

That means anyone who fails to log in five times within 600 seconds is banned for 3600 seconds, or one hour. ignoreip exempts your home network so you can’t ban yourself from the sofa. Unlike MaxAuthTries in the SSH config, which only limits attempts per connection, Fail2Ban counts an address’s failures across all its connections. Restart Fail2Ban and check its status:

sudo systemctl restart fail2ban
sudo fail2ban-client status sshd

Once an address has failed at least five times, it shows up under Banned IP list:

Terminal: sudo fail2ban-client status sshd showing 6 failed attempts and one banned IP address
Fail2Ban has banned an address after six failed attempts. In the test, the attacker was a second machine on the network, hence the private address.

If you’ve banned yourself, lift it with sudo fail2ban-client set sshd unbanip 192.168.1.50 (using the IP from Banned IP list). If the status command shows an error instead of the overview because Fail2Ban can’t find a log file for SSH, it isn’t reading login attempts from the system journal yet. That can happen on older versions of Raspberry Pi OS. In that case, add the line backend = systemd under [sshd] in jail.local and restart Fail2Ban.

Optional: change the SSH port

Moving SSH off port 22 mostly keeps simple scanners away and gives you a quieter log. It doesn’t add much real protection, because a port scan finds the new port in seconds. If you want to change it anyway, do it in this order, here using port 2222:

  1. Allow the new port in the firewall, using the same rules as above with 2222 instead of 22, for example sudo ufw allow from 192.168.1.0/24 to any port 2222 proto tcp and the same for the IPv6 rule. Over Tailscale, the new port is already allowed.
  2. Add the line Port 2222 to /etc/ssh/sshd_config.d/01-hardening.conf.
  3. Check with sudo sshd -t and restart SSH with sudo systemctl restart ssh, keeping your current session open.
  4. Connect from a second window with ssh -p 2222 yourname@raspberrypi.local.
  5. Set port = 2222 in Fail2Ban’s jail.local and restart Fail2Ban. Only then remove the old UFW rules for port 22 with sudo ufw delete ….

Going further: one-time codes or a YubiKey

If you want to go further, there are two options, and one is enough. A one-time code from an app like Google Authenticator adds a second factor on top of your key and costs nothing. A YubiKey instead replaces the key on your computer with one that lives on the device and can’t be copied. It’s more convenient, too, because you just tap it.

One-time codes with Google Authenticator

Install the package on the Pi and then set up the code. Run google-authenticator without sudo, as the user who logs in over SSH:

sudo apt install libpam-google-authenticator
google-authenticator

It asks these questions in turn:

  1. Time-based tokens: y. A QR code appears, which you scan with the app. Then type in the current code from the app to confirm.
  2. Write down the five emergency scratch codes and keep them somewhere other than your phone.
  3. Update your … file: y.
  4. Disallow multiple uses of the same token: y.
  5. Allow a time skew of up to 4 minutes: n, as long as the Pi’s clock is correct.
  6. Rate-limiting: y.
Every SSH user needs their own code

If more than one user logs in to the Pi over SSH, each of them has to run google-authenticator themselves before you restart SSH. Anyone without a code is locked out afterwards. That includes you if you accidentally ran google-authenticator with sudo: the code then belongs to root, not to you.

Now hook the module into the login process:

sudo nano /etc/pam.d/sshd

Add this line at the very top and put a # in front of the existing @include common-auth line:

auth required pam_google_authenticator.so

#@include common-auth

Without the #, SSH asks for your password as well, on top of the key and the code. With the #, logging in takes exactly the key and the code.

Finally, tell the SSH server to ask for the code after the key. Add two lines to your /etc/ssh/sshd_config.d/01-hardening.conf:

KbdInteractiveAuthentication yes
AuthenticationMethods publickey,keyboard-interactive

The first line is the important one. Raspberry Pi OS ships sshd_config with KbdInteractiveAuthentication no, and without your line the SSH server won’t start at all. sshd -t then reports:

Disabled method "keyboard-interactive" in AuthenticationMethods list "publickey,keyboard-interactive"
AuthenticationMethods cannot be satisfied by enabled authentication methods

So check first again and only restart if the config is clean, keeping your current session open:

sudo sshd -t && sudo systemctl restart ssh

The next time you log in from a second window, SSH checks your key first and then asks for a Verification code:. Enter the current code from the app. Without the key, SSH still refuses the login straight away.

Terminal: SSH login with a key asks for a verification code, then the Raspberry Pi shell prompt appears
Logging in with a key and a one-time code: SSH only asks for the verification code, not for a password.

YubiKey as a hardware key (FIDO2)

A YubiKey stores your private SSH key on the device itself. It can’t be read out, even if your computer is infected with malware. Every login needs the key plugged in and a quick touch. Nothing changes on the Pi: OpenSSH has supported these keys since version 8.2. On your computer you need an OpenSSH build that supports hardware keys, which on Windows means version 8.9 or later. ssh -V shows your version. On macOS, Yubico says you need OpenSSH from Homebrew, because the version Apple ships doesn’t support hardware keys. The commands follow the OpenSSH and Yubico documentation.

With the YubiKey plugged in, create the key on your computer and copy it to the Pi as in step 1 (on Windows, use the PowerShell command from above with the file name id_ed25519_sk.pub):

ssh-keygen -t ed25519-sk
ssh-copy-id -i ~/.ssh/id_ed25519_sk.pub yourname@raspberrypi.local

If you changed the SSH port, add -p 2222 to ssh-copy-id. Then log in: the YubiKey flashes and you tap it. Once that works, remove your old key from the Pi, or it will still get you in without the YubiKey. Open nano ~/.ssh/authorized_keys on the Pi and delete the line starting with ssh-ed25519, leaving the one that starts with sk-ssh-ed25519@openssh.com. The advantage over a one-time code is that there’s nothing to type in that someone could intercept.

Links marked with * are affiliate links, which makes them advertising. If you buy through one, I earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases. Learn more

Check your setup with Lynis

Lynis checks your system for hundreds of common weaknesses and suggests improvements. A run takes a few minutes:

sudo apt install lynis
sudo lynis audit system

At the end you get a Hardening index between 0 and 100, with a list of Suggestions above it. Don’t work through them blindly. Many are aimed at servers in data centres and don’t add much for a Pi on your home network. The index is most useful as a before-and-after comparison.

If you’ve locked yourself out

  • First window still open: undo your last change there, for example with sudo rm /etc/ssh/sshd_config.d/01-hardening.conf, and restart SSH. Password logins work again until you put a corrected file back.
  • Pi within reach: plug in a screen and keyboard, log in directly and fix the file. SSH keys and two-factor don’t apply to logins at the Pi itself.
  • No screen to hand: shut the Pi down, put the SD card in a Linux computer and delete or rename etc/ssh/sshd_config.d/01-hardening.conf on the rootfs partition. Windows can’t read that partition out of the box. Our guide to recovering data from a broken SD card shows how to get at it anyway.
  • Banned by Fail2Ban: wait an hour, or run sudo fail2ban-client set sshd unbanip with the banned IP in a session that’s still open or directly at the Pi.
  • Locked out by UFW: at the Pi, turn it off with sudo ufw disable, add the missing rule and switch UFW back on. Via the SD card, set ENABLED=no in etc/ufw/ufw.conf.
  • Undoing two-factor: in /etc/pam.d/sshd, delete the line auth required pam_google_authenticator.so and remove the # in front of @include common-auth. In 01-hardening.conf, delete the KbdInteractiveAuthentication yes and AuthenticationMethods … lines, then check and restart SSH.

Checklist

  • ✅ No ports open on the router (just WireGuard’s UDP port if you use it); remote access through a VPN
  • ✅ Your own user with a strong password
  • ✅ Security updates installed automatically, Raspberry Pi packages updated by hand regularly
  • ✅ Unneeded services turned off (sudo ss -tulnp)
  • ✅ SSH keys only, set in /etc/ssh/sshd_config.d/01-hardening.conf and checked with sudo sshd -T
  • ✅ UFW active, SSH allowed only from your home network and over the VPN, rules for every service you use
  • ✅ Fail2Ban running once SSH is reachable through port forwarding
  • ✅ Optional: a second factor with an authenticator app or YubiKey
  • ✅ Lynis run before and after

Frequently asked questions about securing your Raspberry Pi

How do I secure my Raspberry Pi for access from the internet?

The safest approach is to open as few ports on your router as possible and reach the Pi through a VPN: Tailscale needs no open port at all, WireGuard just one UDP port. On top of that, use your own user with a strong password, automatic updates, key-only SSH, the UFW firewall and, once SSH is reachable from the internet through port forwarding, Fail2Ban.

Is Tailscale better than port forwarding?

For your own access, yes. With Tailscale the Pi makes the connection outwards itself, so every port on your router stays closed. According to its pricing page (as of October 2026), Tailscale is free for personal use with up to six users and as many of your own devices as you like. You only need port forwarding if other people should reach a service without installing an app.

Why doesn’t PasswordAuthentication no in sshd_config work?

The SSH server uses the first value it finds for each setting and reads the files in /etc/ssh/sshd_config.d/ first. If Raspberry Pi Imager created 50-cloud-init.conf there with PasswordAuthentication yes, that file wins. Put your settings in a file of your own, such as 01-hardening.conf, and check what actually applies with sudo sshd -T.

Do I need Fail2Ban if I only allow SSH keys?

Nobody gets in without a key anyway. Fail2Ban still bans addresses after repeated failed attempts, which slows scanners down and keeps your log tidy. If SSH is reachable from the internet through port forwarding, you should set it up regardless.

Can I use a YubiKey to log in to my Raspberry Pi over SSH?

Yes. OpenSSH has supported FIDO2 keys since version 8.2. Create a key that stays on the YubiKey with ssh-keygen -t ed25519-sk on your computer and copy the public part to the Pi. To log in, the key has to be plugged in and touched. The Pi doesn’t need any extra configuration.

Similar Posts