Skip to content

Instantly share code, notes, and snippets.

@GitHeld
Forked from boseji/Rapi-Secure.md
Created January 31, 2023 23:01
Show Gist options
  • Save GitHeld/eb0bc93e8ab3c574486cb6b0f4d03773 to your computer and use it in GitHub Desktop.
Save GitHeld/eb0bc93e8ab3c574486cb6b0f4d03773 to your computer and use it in GitHub Desktop.
Securing the Raspberry Pi

Securing you Linux Computer (Raspberry Pi)

This was inspired by the concise works of jeff's Skinner Box

Primary Article to begin with:

Lets make sure that we have all the sheilds up!

Protect your Network

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

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

Modify the following lines.

...
# Do not accept ICMP redirects (prevent MITM attacks)
net.ipv4.conf.all.accept_redirects = 0
net.ipv6.conf.all.accept_redirects = 0
# _or_
# Accept IC

# 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 determin 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).

This usually lowers the number of attempts. However, certain number of (un)successfull 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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment