Skip to content

Raspberry Pi Security Hardening Complete Guide

Secure your Raspberry Pi with this comprehensive hardening guide! Learn essential security practices, implement advanced protection measures, and create a robust defense against common threats. Perfect for production deployments, IoT projects, and security-conscious users.

Introduction

Security hardening is crucial for any Raspberry Pi deployment, especially those connected to networks or handling sensitive data. This guide covers everything from basic security practices to advanced hardening techniques, helping you create a secure and resilient system.

Benefits of Security Hardening

Proper security hardening provides:

  • Protection Against Attacks: Defense against common attack vectors and vulnerabilities
  • Data Integrity: Safeguarding sensitive information and system configurations
  • Network Security: Preventing unauthorized access and lateral movement
  • Compliance: Meeting security standards and regulatory requirements
  • Peace of Mind: Confidence in your system's security posture

Pre-Hardening Assessment

Check Current Security Status

# Check system information
uname -a
cat /etc/os-release

# List users and groups
cat /etc/passwd
groups

# Check running services
systemctl list-unit-files --state=enabled
sudo netstat -tuln

# Review file permissions
ls -la /etc/passwd /etc/shadow /etc/group

# Check for world-writable files
find / -type f -perm -002 2>/dev/null | head -20

Document Current Configuration

1
2
3
4
5
6
# Create security baseline
mkdir -p ~/security-audit
sudo cp /etc/passwd ~/security-audit/
sudo cp /etc/group ~/security-audit/
sudo systemctl list-unit-files > ~/security-audit/services.txt
sudo netstat -tuln > ~/security-audit/open-ports.txt

Essential Security Practices

1. Update System and Packages

1
2
3
4
5
6
7
8
9
# Update package database and system
sudo apt update && sudo apt upgrade -y

# Enable automatic security updates
sudo apt install unattended-upgrades
sudo dpkg-reconfigure -plow unattended-upgrades

# Configure automatic updates
sudo nano /etc/apt/apt.conf.d/50unattended-upgrades

Add configuration:

1
2
3
Unattended-Upgrade::Automatic-Reboot "false";
Unattended-Upgrade::Automatic-Reboot-Time "02:00";
Unattended-Upgrade::Remove-Unused-Dependencies "true";

2. User Account Security

Change Default Password

1
2
3
4
5
6
# Change password for current user
passwd

# Set strong password policy
sudo apt install libpam-pwquality
sudo nano /etc/security/pwquality.conf

Configure password requirements:

# Minimum password length
minlen = 12

# Require mixed case
ucredit = -1
lcredit = -1

# Require digits and special characters
dcredit = -1
ocredit = -1

# Remember previous passwords
remember = 5

# Check against dictionary words
dictcheck = 1

Create Dedicated Service Account

1
2
3
4
5
6
7
8
9
# Create service account with no shell
sudo adduser --system --no-create-home --shell /bin/false serviceuser

# Create admin account separate from pi user
sudo adduser adminuser
sudo usermod -aG sudo adminuser

# Remove pi user from sudo (if using different admin account)
sudo deluser pi sudo

Disable Unused Accounts

# List all accounts
cat /etc/passwd

# Disable unused system accounts
sudo usermod -s /bin/false games
sudo usermod -s /bin/false news
sudo usermod -s /bin/false uucp

# Lock unused accounts
sudo passwd -l games
sudo passwd -l news

3. SSH Security

SSH Key Authentication

1
2
3
4
5
6
7
8
# Generate SSH key pair on client machine
ssh-keygen -t ed25519 -b 4096 -f ~/.ssh/pi_key

# Copy public key to Raspberry Pi
ssh-copy-id -i ~/.ssh/pi_key.pub user@raspberry-pi-ip

# Test key-based authentication
ssh -i ~/.ssh/pi_key user@raspberry-pi-ip

Harden SSH Configuration

1
2
3
4
5
# Backup original config
sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.backup

# Edit SSH configuration
sudo nano /etc/ssh/sshd_config

Apply these security settings:

# Change default port
Port 2222

# Disable root login
PermitRootLogin no

# Use only key authentication
PasswordAuthentication no
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys

# Limit user access
AllowUsers adminuser serviceuser
DenyUsers pi

# Connection limits
MaxAuthTries 3
MaxSessions 2
ClientAliveInterval 300
ClientAliveCountMax 2

# Disable dangerous features
X11Forwarding no
AllowTcpForwarding no
GatewayPorts no
PermitTunnel no

# Use strong encryption
Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com,aes128-gcm@openssh.com
MACs hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com
KexAlgorithms curve25519-sha256@libssh.org,diffie-hellman-group16-sha512

Restart SSH service:

sudo systemctl restart ssh
sudo systemctl status ssh

Network Security

1. Firewall Configuration

UFW (Uncomplicated Firewall)

# Install and configure UFW
sudo apt install ufw

# Set default policies
sudo ufw default deny incoming
sudo ufw default allow outgoing

# Allow SSH on custom port
sudo ufw allow 2222/tcp

# Allow specific services only from local network
sudo ufw allow from 192.168.1.0/24 to any port 80
sudo ufw allow from 192.168.1.0/24 to any port 443

# Enable firewall
sudo ufw enable

# Check status
sudo ufw status verbose

Advanced iptables Rules

1
2
3
4
5
# Install iptables-persistent
sudo apt install iptables-persistent

# Create custom rules script
sudo nano /etc/iptables/rules.v4

Example iptables configuration:

*filter
:INPUT DROP [0:0]
:FORWARD DROP [0:0]
:OUTPUT ACCEPT [0:0]

# Allow loopback
-A INPUT -i lo -j ACCEPT

# Allow established connections
-A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT

# Allow SSH from specific network
-A INPUT -p tcp -s 192.168.1.0/24 --dport 2222 -j ACCEPT

# Rate limit SSH connections
-A INPUT -p tcp --dport 2222 -m conntrack --ctstate NEW -m recent --set
-A INPUT -p tcp --dport 2222 -m conntrack --ctstate NEW -m recent --update --seconds 60 --hitcount 4 -j DROP

# Allow ping from local network
-A INPUT -p icmp -s 192.168.1.0/24 -j ACCEPT

COMMIT

2. Network Monitoring

Install Monitoring Tools

1
2
3
4
5
6
# Install network monitoring tools
sudo apt install netstat-nat nmap tcpdump fail2ban

# Configure fail2ban
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
sudo nano /etc/fail2ban/jail.local

Configure fail2ban:

[DEFAULT]
bantime = 3600
findtime = 600
maxretry = 3
backend = systemd

[sshd]
enabled = true
port = 2222
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
bantime = 3600

3. Disable Unnecessary Services

# List enabled services
systemctl list-unit-files --state=enabled

# Disable unnecessary services
sudo systemctl disable bluetooth
sudo systemctl disable avahi-daemon
sudo systemctl disable triggerhappy
sudo systemctl disable dphys-swapfile  # If using ZRAM

# Stop services immediately
sudo systemctl stop bluetooth
sudo systemctl stop avahi-daemon

File System Security

1. File Permissions

Set Proper Permissions

# Secure important directories
sudo chmod 755 /etc
sudo chmod 644 /etc/passwd
sudo chmod 600 /etc/shadow
sudo chmod 600 /etc/gshadow
sudo chmod 644 /etc/group

# Secure SSH directory
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys
chmod 600 ~/.ssh/id_*
chmod 644 ~/.ssh/*.pub

# Remove world-writable permissions
sudo find / -type f -perm -002 -exec chmod o-w {} \; 2>/dev/null

Set File Attributes

# Install extended attributes tools
sudo apt install attr

# Make critical files immutable
sudo chattr +i /etc/passwd
sudo chattr +i /etc/shadow
sudo chattr +i /etc/group

# Check attributes
lsattr /etc/passwd /etc/shadow /etc/group

2. Mount Options Security

# Edit fstab for security options
sudo nano /etc/fstab

Add security mount options:

1
2
3
4
# Example secure mount options
/dev/mmcblk0p1 /boot/firmware vfat defaults,nodev,nosuid,noexec 0 2
tmpfs /tmp tmpfs defaults,rw,nosuid,nodev,noexec,relatime 0 0
tmpfs /var/tmp tmpfs defaults,rw,nosuid,nodev,noexec,relatime 0 0

3. Log Monitoring and Integrity

Configure System Logging

1
2
3
4
5
# Install rsyslog if not present
sudo apt install rsyslog

# Configure log rotation
sudo nano /etc/logrotate.conf

Set up log integrity checking:

1
2
3
4
5
6
7
8
9
# Install aide for file integrity
sudo apt install aide

# Initialize database
sudo aide --init
sudo mv /var/lib/aide/aide.db.new /var/lib/aide/aide.db

# Create daily check script
sudo nano /etc/cron.daily/aide-check

AIDE check script:

#!/bin/bash

AIDE_LOG="/var/log/aide.log"
DATE=$(date +%Y-%m-%d)

echo "AIDE Check - $DATE" >> $AIDE_LOG
/usr/bin/aide --check >> $AIDE_LOG 2>&1

if [ $? -ne 0 ]; then
    echo "AIDE detected changes!" | mail -s "AIDE Alert - $HOSTNAME" admin@example.com
fi

Make executable:

sudo chmod +x /etc/cron.daily/aide-check

Advanced Security Measures

1. AppArmor Configuration

# Install AppArmor
sudo apt install apparmor apparmor-utils

# Enable AppArmor
sudo systemctl enable apparmor
sudo systemctl start apparmor

# Check status
sudo aa-status

# Create custom profiles
sudo aa-genprof /usr/bin/application

2. Kernel Security

Kernel Parameters

# Edit kernel parameters
sudo nano /etc/sysctl.conf

Add security parameters:

# Network security
net.ipv4.ip_forward = 0
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.send_redirects = 0
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.conf.default.accept_source_route = 0
net.ipv4.conf.all.log_martians = 1
net.ipv4.icmp_echo_ignore_broadcasts = 1
net.ipv4.icmp_ignore_bogus_error_responses = 1
net.ipv4.tcp_syncookies = 1

# Memory protection
kernel.exec-shield = 1
kernel.randomize_va_space = 2

Apply changes:

sudo sysctl -p

3. Hardware Security

Disable Unused Interfaces

# Edit boot configuration
sudo nano /boot/firmware/config.txt

Disable unused hardware:

# Disable Bluetooth
dtoverlay=disable-bt

# Disable WiFi (if using Ethernet only)
dtoverlay=disable-wifi

# Disable audio (if not needed)
dtparam=audio=off

# Disable camera (if not needed)
start_x=0

Security Monitoring and Alerting

1. Intrusion Detection

Install and Configure Tripwire

# Install tripwire
sudo apt install tripwire

# Configure tripwire
sudo tripwire-setup-keyfiles

# Initialize database
sudo tripwire --init

# Create check script
sudo nano /etc/cron.daily/tripwire-check

2. Log Analysis

Install LogWatch

1
2
3
4
5
# Install logwatch
sudo apt install logwatch

# Configure logwatch
sudo nano /etc/logwatch/conf/logwatch.conf

Configure LogWatch:

# Email configuration
MailTo = admin@example.com
MailFrom = pi@hostname

# Detail level
Detail = Med

# Service filters
Service = sshd
Service = kernel
Service = fail2ban

3. Network Monitoring

Set Up Network Scanning Detection

# Create port scan detection script
sudo nano /usr/local/bin/portscan-detect.sh

Port scan detection script:

#!/bin/bash


LOGFILE="/var/log/portscan.log"
THRESHOLD=10

# Monitor for port scans
tail -f /var/log/kern.log | while read line; do
    if echo "$line" | grep -q "SYN flood"; then
        echo "$(date): Potential SYN flood detected" >> $LOGFILE
        echo "SYN flood detected on $HOSTNAME" | mail -s "Security Alert" admin@example.com
    fi
done

Regular Security Maintenance

1. Daily Tasks

# Create daily security script
sudo nano /etc/cron.daily/security-check

Daily security check script:

#!/bin/bash


REPORT="/tmp/daily-security-report.txt"
DATE=$(date +%Y-%m-%d)

echo "Daily Security Report - $DATE" > $REPORT
echo "================================" >> $REPORT

# Check for failed login attempts
echo "Failed Login Attempts:" >> $REPORT
grep "Failed password" /var/log/auth.log | tail -10 >> $REPORT

# Check for new users
echo -e "\nCurrent Users:" >> $REPORT
cut -d: -f1 /etc/passwd >> $REPORT

# Check listening ports
echo -e "\nListening Ports:" >> $REPORT
sudo netstat -tuln >> $REPORT

# Check firewall status
echo -e "\nFirewall Status:" >> $REPORT
sudo ufw status >> $REPORT

# Email report
mail -s "Daily Security Report - $HOSTNAME" admin@example.com < $REPORT

2. Weekly Tasks

# Create weekly security audit
sudo nano /etc/cron.weekly/security-audit

3. Monthly Tasks

# Create monthly security review
sudo nano /etc/cron.monthly/security-review

Security Testing and Validation

1. Vulnerability Scanning

1
2
3
4
5
6
7
8
# Install vulnerability scanners
sudo apt install nmap nikto

# Self-scan from another machine
nmap -sS -O -A your-pi-ip

# Web vulnerability scan (if running web services)
nikto -h http://your-pi-ip

2. Penetration Testing

1
2
3
4
5
# Install penetration testing tools
sudo apt install metasploit-framework

# Basic security assessment
sudo nmap -sV -sC -O your-pi-ip

Incident Response

1. Security Incident Checklist

When security incident detected:

  1. Isolate the system from network
  2. Document all findings
  3. Preserve logs and evidence
  4. Investigate the scope of compromise
  5. Remediate vulnerabilities
  6. Monitor for recurring issues

2. Recovery Procedures

# Emergency lockdown script
sudo nano /usr/local/bin/emergency-lockdown.sh

Emergency lockdown script:

#!/bin/bash


echo "EMERGENCY LOCKDOWN INITIATED"

# Block all incoming connections
sudo iptables -P INPUT DROP
sudo iptables -P FORWARD DROP

# Keep only essential outgoing
sudo iptables -A OUTPUT -p tcp --dport 22 -j ACCEPT
sudo iptables -A OUTPUT -p tcp --dport 53 -j ACCEPT
sudo iptables -A OUTPUT -p udp --dport 53 -j ACCEPT

# Log the event
echo "$(date): Emergency lockdown activated" >> /var/log/security.log

# Notify administrator
echo "Emergency lockdown activated on $HOSTNAME" | mail -s "SECURITY ALERT" admin@example.com

Compliance and Documentation

1. Security Documentation

1
2
3
4
5
6
7
# Create security documentation
mkdir -p ~/security-docs

# Document configuration
sudo cp /etc/ssh/sshd_config ~/security-docs/
sudo cp /etc/ufw/user.rules ~/security-docs/
sudo cp /etc/fail2ban/jail.local ~/security-docs/

2. Regular Audits

# Create audit checklist script
sudo nano /usr/local/bin/security-audit.sh

Best Practices Summary

Essential Security Practices

  1. Keep System Updated: Regular updates and security patches
  2. Strong Authentication: SSH keys, strong passwords, multi-factor authentication
  3. Network Segmentation: Firewalls, VLANs, access controls
  4. Monitoring: Continuous monitoring and alerting
  5. Backup and Recovery: Regular backups and tested recovery procedures
  6. Principle of Least Privilege: Minimal necessary permissions
  7. Defense in Depth: Multiple layers of security controls

Security Maintenance Schedule

Frequency Tasks
Daily Log review, failed login check, service status
Weekly Security updates, vulnerability scan, backup verification
Monthly Full system audit, password review, access review
Quarterly Penetration testing, disaster recovery testing
Annually Security policy review, compliance audit

Troubleshooting Security Issues

Common Problems and Solutions

SSH Connection Issues

# Check SSH service status
sudo systemctl status ssh

# Check SSH logs
sudo journalctl -u ssh

# Test SSH configuration
sudo sshd -t

# Reset SSH configuration (emergency)
sudo cp /etc/ssh/sshd_config.backup /etc/ssh/sshd_config
sudo systemctl restart ssh

Firewall Blocking Services

# Check UFW status
sudo ufw status verbose

# Temporarily disable firewall (emergency only)
sudo ufw disable

# Check iptables rules
sudo iptables -L -n

# Reset iptables (emergency)
sudo iptables -F
sudo iptables -X
sudo iptables -t nat -F
sudo iptables -t nat -X

Failed Login Investigation

1
2
3
4
5
6
7
8
9
# Check authentication logs
sudo grep "Failed password" /var/log/auth.log | tail -20

# Check fail2ban status
sudo fail2ban-client status
sudo fail2ban-client status sshd

# Unban IP address
sudo fail2ban-client set sshd unbanip IP-ADDRESS

Conclusion

Security hardening is an ongoing process that requires regular attention and updates. This comprehensive guide provides a solid foundation for securing your Raspberry Pi, but remember that security is not a one-time setup—it requires continuous monitoring, updating, and improvement.

The key to effective security is implementing defense in depth: multiple layers of security controls that work together to protect your system. Start with the essential practices and gradually implement more advanced measures based on your specific security requirements and threat model.

Remember to: - Regularly update and patch your system - Monitor logs and security alerts - Test your security controls periodically - Keep security documentation up to date - Have an incident response plan ready

By following these guidelines and maintaining good security hygiene, your Raspberry Pi will be well-protected against common threats and ready for production use.