0
0
Raspberry Piprogramming~10 mins

Securing Raspberry Pi (SSH keys, firewall)

Choose your learning style9 modes available
Introduction

Securing your Raspberry Pi helps keep it safe from hackers. Using SSH keys and a firewall protects your device when you connect to it remotely.

When you want to connect to your Raspberry Pi from another computer safely.
When you want to stop strangers from accessing your Raspberry Pi over the internet.
When you want to avoid typing your password every time you log in remotely.
When you want to control which devices can talk to your Raspberry Pi.
When you want to keep your Raspberry Pi safe while running projects connected to a network.
Syntax
Raspberry Pi
1. Generate SSH keys on your computer:
   ssh-keygen -t rsa -b 4096

2. Copy your public key to Raspberry Pi:
   ssh-copy-id pi@raspberrypi.local

3. Enable firewall (ufw) on Raspberry Pi:
   sudo apt install ufw
   sudo ufw allow ssh
   sudo ufw enable

4. Check firewall status:
   sudo ufw status

SSH keys replace passwords with a pair of secret and public keys for safer login.

Firewall (ufw) controls which connections are allowed to your Raspberry Pi.

Examples
This command creates a strong pair of SSH keys on your computer.
Raspberry Pi
ssh-keygen -t rsa -b 4096
This copies your public key to the Raspberry Pi so you can log in without a password.
Raspberry Pi
ssh-copy-id pi@raspberrypi.local
This allows SSH connections through the firewall.
Raspberry Pi
sudo ufw allow ssh
This turns on the firewall to protect your Raspberry Pi.
Raspberry Pi
sudo ufw enable
Sample Program

This script shows the main steps to secure your Raspberry Pi: create SSH keys, copy them, connect using keys, and set up a firewall.

Raspberry Pi
#!/bin/bash

# Step 1: Generate SSH key pair (run on your computer)
ssh-keygen -t rsa -b 4096 -f ~/.ssh/id_rpi_key -N ""

# Step 2: Copy public key to Raspberry Pi
ssh-copy-id -i ~/.ssh/id_rpi_key.pub pi@raspberrypi.local

# Step 3: Connect to Raspberry Pi using the new key and set up firewall
ssh -i ~/.ssh/id_rpi_key pi@raspberrypi.local 'sudo apt update && sudo apt install -y ufw && sudo ufw allow ssh && sudo ufw enable && sudo ufw status'
OutputSuccess
Important Notes

Always keep your private SSH key safe and never share it.

Use strong passphrases for SSH keys if you want extra security.

Check firewall rules regularly to avoid blocking needed connections.

Summary

Use SSH keys to log in without passwords and improve security.

Set up a firewall to control network access to your Raspberry Pi.

These steps help protect your Raspberry Pi from unauthorized access.