Skip to content

Secure Raspberry Pi(Linux)

trinib edited this page Nov 5, 2022 · 1 revision

Created by - @boseji boseji/Rapi-Secure.md

Protect your Network

pi@raspberrypi:~ $ sudo nano /etc/sysctl.conf

Though its apparently written in the file the Lines are still commented out. Un-commenting these lines would help to enhance security.

Modify the following lines.

...

# Uncomment the next two lines to enable Spoof protection (reverse-path filter)
# Turn on Source Address Verification in all interfaces to
# prevent some spoofing attacks
net.ipv4.conf.default.rp_filter=1
net.ipv4.conf.all.rp_filter=1

...

# Do not accept ICMP redirects (prevent MITM attacks)
net.ipv4.conf.all.accept_redirects = 0
net.ipv6.conf.all.accept_redirects = 0
# _or_
# Accept ICMP redirects only for gateways listed in our default
# gateway list (enabled by default)
# net.ipv4.conf.all.secure_redirects = 1
#
# Do not send ICMP redirects (we are not a router)
net.ipv4.conf.all.send_redirects = 0
#
# Do not accept IP source route packets (we are not a router)
net.ipv4.conf.all.accept_source_route = 0
net.ipv6.conf.all.accept_source_route = 0
...

Setup Firewall

Install Uncomplicated Fireall (UFW) easy option for Raspi users.

pi@raspberrypi:~ $ sudo apt -y install ufw

Once installed, You have to configure a tune the firewall to your own needs. However, deny any incoming connection by default as described below:

pi@raspberrypi:~ $ sudo ufw default deny incoming

You may for example allow ssh access only from your local network. The command below illustrate that. note that you have to change the xxx.yyy.zzz by your local network information.

pi@raspberrypi:~ $ sudo ufw allow from xxx.yyy.zzz.0/24 to any port 22 proto tcp

Enable All access from a particular IP - This is important while configuring the rules else one might get locked out if wrong rules are set. Typically the PC IP you are working on can be assigned this way. This will allow you to fix errors in the rules.

sudo ufw allow from xxx.yyy.zzz.0

Enable Logging

pi@raspberrypi:~ $ sudo ufw logging on

To check Public IP ports

Use the HideMy.Name service https://hidemy.name/en/ports/

They can tell about what ports are currently open on a particular IP.

This helps to determine if the network is externally vulnerable to any attacks.

Install Fail2Ban Article

The article "Keeping SSH Access Secure" provides some good suggestions. One method, not referenced in this article, is how you could rate-limit iptables rules to address this issue (from this source):

# block connections if the login fails 10 times in 1 hour on port 22
iptables -I INPUT -p tcp --dport 22 -m state --state NEW -m recent --set
iptables -I INPUT -p tcp --dport 22 -m state --state NEW -m recent --update --seconds 3600 --hitcount 10 -j DROP

This blocks connections if the login fails ten times in one hour on port 22.

Another easy answer would be to limit ssh access from the wlan network interface only. This works if you have no plans to ssh into your device from the Internet, effectively cuts out the attacks from the Internet. But of course, if your neighbors nerdy 13 year old wants to mess with your WiFi, you still could have some attacks.

So its just a matter of time before the attack is on another port, or user account, or network interface, therefore using Fail2Ban or something similar (an alternative is Droplan) may be in order. fail2ban reads the sshd log entries (and other log files) and bans the originating address when there are too many failures. Generally Fail2Ban is then used to update firewall rules to reject the IP addresses for a specified amount of time, although any arbitrary other action (e.g. sending an email) could also be configured. Out of the box Fail2Ban comes with filters for various services (apache, courier, ssh, etc.).

While Fail2Ban does provide additional protection, the use of two factor authentication (see "Two-Factor Authentication via Google Authenticator") or public/private key authentication mechanisms (see "HowTo: Configure SSH Public Key Authentication") as your primary defense provide the best protection overall.

Step 1: Install Fail2Ban

We will be installing a daemon called fail2ban that scans log files and automatically bans suspicious IP address using iptables. Install fail2ban with the following command:

# install the software
sudo apt-get install fail2ban

# copy the example configuration file and make it live
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local

fail2ban should start automatically after the install. You can check this via sudo service fail2ban status. You should see your iptables rules updated to something like:

# list the chain rules in service
$ sudo iptables -t filter --list
Chain INPUT (policy ACCEPT)
target     prot opt source               destination
fail2ban-ssh  tcp  --  anywhere             anywhere             multiport dports ssh

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

Chain fail2ban-ssh (1 references)
target     prot opt source               destination
RETURN     all  --  anywhere             anywhere

Step 2: Configure Fail2Ban

You can use fail2ban with any service that makes log files like Apache, FTP, etc. The configuration for different services can be found in /etc/fail2ban/jail.local. You can change this settings by adding appropriate lines in /etc/fail2ban/jail.local. For example, I want to permanently ban the suspicious IP address after 10 attempts. Apart from that, I want to ban access for this IP on all ports, so I changed default banaction to iptables-allports. So, part of my /etc/fail2ban/jail.local file looks like this:

[ssh]

enabled  = true
port     = ssh
filter   = sshd
logpath  = /var/log/auth.log
banaction = iptables-allports    ; ban retrys on any port
bantime  = 600                   ; ip address is banned for 10 minutes
maxretry = 10                    ; allow the ip address retry a max of 10 times

NOTE: If I want to permanently ban a suspicious IP address, I would set the ban time as follows: bantime = -1 ; ip address permanently banned.

If you have an active brute force attack underway on SSH, you can check out the /var/log/auth.log (use tailf /var/log/auth.log | grep 'sshd.*Failed'). You should see 10 login attempts, followed by at least a 10 minute pause, and then the attacks may begin again for 10 attempts.

When you did the necessary updates of the configuration files, make sure to restart service:

sudo service fail2ban restart

and check current bans with:

sudo iptables -L -n --line

However, I soon realized that all bans disappear from iptables after reboot. To deal with this issue, I added the following line to my /etc/fail2ban/action.d/iptables-allports.conf file to the actionstart:

cat /etc/fail2ban/ip.list-<name> | while read IP; do iptables -I fail2ban-<name> 1 -s $IP -j DROP; done

and following line to the actionban

echo '<ip>/24' >> /etc/fail2ban/ip.list-<name>

These commands log the banned IP addresses to the /etc/fail2ban/ip.list file and after restart the contest of this file is added to the iptables. Careful reader will notice that IP address are stored in ip.list file with suffix /24. In that way iptables will block the whole range from xxx.xxx.xxx.0 to xxx.xxx.xxx.255 :)

When you did the necessary updates of the configuration files, make sure to restart service:

sudo service fail2ban restart

Many users remotely connect to their RPi over SSH. While this is a great way to communicate with your device, it can become major security hole if you are using authentication with weak password. By using brute force attack someone can guess your password and gain access to your system.

There are several way to improve the security of your SSH connection.

Default installation of RPi will probably have an SSH daemon running. Basically, this means that the RPi is listening particular port the connections. If the remote host asks for the connection this will be logged to /var/log/auth.log.

If you are running a RPi for a couple of days connected to the internet, you are likely to see a number of attempts with different usernames and password that are logged to this file.

These are brute force attacks performed by automatic scripts which are using dictionaries that contain common usernames and passwords (like username: root, password: 1234). What can you do? At first, use strong password.

Secondly, disable remote root login. This can be done through the sshd config files:

sudo nano /etc/ssh/sshd_config

by changing the line PermitRootLogin to no.

In this config file you can change the default port for SSH (22) to something else (e.g. 2100).

# What ports, IPs and protocols we listen for
# Port 22 ; Older
Port 2100

This usually lowers the number of attempts. However, certain number of (un)successful attempts will be still present so you can make additional security measures.

One is key pair authentication.

Here is a great tutorial about key authentication setup.

In essence, the remote connection is based on key pair: public and private. The public key is stored on your Raspberry Pi and the private key on the computer from where you wish to connect to Raspberry Pi. Since the password is never transferred between remote host and the computer from where you are trying to access remote host, this way is much secure than password based authentication.

However, you must keep your private key at a safe place.

The keys can be generated on RPi with the ssh-keygen command or with Putty program.

Once you have set up a key based login, you should disable the password based authentication in sshd_config file by setting line PasswordAuthentication to no.

Dont forget to copy the Public keys to the ~/.ssh/authorized_keys file:

echo `cat ~/.ssh/uploaded_key.pub` >> ~/.ssh/authorized_keys

Read further on Raspberry Pi Networking Cookbook Online

Free book about network administration on Raspberry Pi

Computer expert or enthusiast, this cookbook will help you use your Raspberry Pi to enhance your existing network. From sharing media across devices to deploying your own web portal, you’ll be amazed at what can be achieved.

By Rick Golden

https://www.packtpub.com/mapt/book/hardware-and-creative/9781849694605

Watchdog for Unattended Reset !

The Broadcom BCM2835 SoC on the Raspberry Pi comes with a hardware-based watchdog timer that can do just that. You will find this specially useful if you have a Raspberry Pi in a remote location and the operating system hangs and there's no one around to reboot it.

Properly Enable Watchdog at Boot

There is one bug that needs fixing by editing the /boot/config.txt file of the Raspberry Pi boot. This would help enable the Watchdog

Command:

sudo nano /boot/config.txt

In the file add one line:

# at end of file
dtparam=watchdog=on

Now reboot sudo reboot

This would ensure that the watchdog is available.

Installing & Configuring the Watchdog

# Load the Watchdog module
sudo modprobe bcm2835-wdt

## Add it for Boot-up

# Edit the Modules file
sudo nano /etc/modules

# at end of the file Add the following line and save
bcm2835-wdt


# Install the Packages needed
sudo apt-get install -y watchdog chkconfig

# Turn On the Watch Dog
sudo chkconfig watchdog on

# Setup for Autorun
sudo ln /lib/systemd/system/watchdog.service /etc/systemd/system/multi-user.target.wants/watchdog.service

Configuration for the Watchdog is stored at /etc/watchdog.conf

Edit this configuration to:

...

#test-binary            =
#test-timeout           =

watchdog-device        = /dev/watchdog

# Defaults compiled into the binary
#temperature-device     =
#max-temperature        = 120

...

# This greatly decreases the chance that watchdog won't be scheduled before
# your machine is really loaded
realtime                = yes
priority                = 1

# Check if rsyslogd is still running by enabling the following line
#pidfile                = /var/run/rsyslogd.pid

...

#at end of file add


watchdog-timeout = 14
interval = 4
max-load-1 = 24

This configures the watchdog to reset if the pat (watchdog reset) is not given within 4 seconds.

Start the Service:

sudo chkconfig watchdog on
sudo /etc/init.d/watchdog start

# Or Restart it

sudo sudo /etc/init.d/watchdog restart

# Or Stop it

sudo sudo /etc/init.d/watchdog stop

Make sure to reboot the Raspberry Pi and check if the is really service running.

Check if Watchdog service

Typically we need to check the module and then the devices:

pi@raspberry $ sudo lsmod | grep wd
bcm2835_wdt             3225  1 

pi@raspberry $ ls -la /dev/watchdog*
crw------- 1 root root  10, 130 Sep 24 10:44 /dev/watchdog
crw------- 1 root root 253,   0 Sep 24 10:44 /dev/watchdog0

pi@raspberry $ sudo service watchdog status
  watchdog.service - watchdog daemon
   Loaded: loaded (/lib/systemd/system/watchdog.service; static)
   Active: active (running) since Mon 2017-04-17 10:14:17 IST; 6min ago
   
Apr 17 10:23:24 rpiha watchdog[992]: int=4s realtime=yes sync=no soft=no ml...=0
Apr 17 10:23:24 rpiha watchdog[992]: ping: no machine to check
Apr 17 10:23:24 rpiha watchdog[992]: file: no file to check
Apr 17 10:23:24 rpiha watchdog[992]: pidfile: no server process to check
Apr 17 10:23:24 rpiha watchdog[992]: interface: no interface to check
Apr 17 10:23:24 rpiha watchdog[992]: temperature: no sensors to check
Apr 17 10:23:24 rpiha watchdog[992]: test=none(0) repair=none(0) alive=/dev...no
Apr 17 10:23:24 rpiha watchdog[992]: watchdog now set to 14 seconds
Apr 17 10:23:24 rpiha watchdog[992]: hardware watchdog identity: Broadcom B...er
Apr 17 10:23:24 rpiha systemd[1]: Started watchdog daemon.
...

The values should be identical apart from dates, else there are some issues.

Testing out the Watchdog Reset

Type the following Commands (Never use these command this something called the Forkbomb only for testing):

:(){ :|:& };:

If the Raspberry Pi reboots then the watchdog is working.

Original Articles on Watchdog in Raspberry Pi

Secure Channel for Update

Install the secure channel to update your Raspberry Pi. This means that the apt-get or apt would support https:// protocol. This ensures that the updates being downloaded are from a encrypted connection and not tampered witht.

Here is the command:

sudo apt install apt-transport-https -y

That's it. This would enable https:// on source lists.

Hope the Keep adding more inputs to harden security on Raspberry Pi.