Securing Raspberry Pi

Securing Raspberry Pi

27 Sep 2018, 12:08pm TZ +05:30
linux, Raspberry Pi
Security

Secure Raspberry Pi

Using Raspberry Pi for your IoT experiments - a given. Like the white hair on my head.
Many don’t realize the real threat it poses these days to security. There have been many reports of IoT devices being hijacked. And then used for malicious purposes. Like peeping into your drawer. Even worst looking into your code. I don’t want people to know how many cockroaches and worms lie hidden in my old code. ;-)

Well, instead of loosing your night’s sleep read this.

I had published one gist some time back.
But, like my head it has grown white hairs(Obsolete).

Recently I started setting up my (now old) Raspberry Pi 3. Retracing the steps, helped to get some security insights. Creating a safer IoT gateway thats valid with today’s updates.

Linux Image : Raspbian #

Let’s first look at the Linux image used for this experiment.
Desktop Rasbian (Debian with spices) is a typical choice.
https://www.raspberrypi.org/downloads/raspbian/
That’s the location find the image to download.

Albeit confusing - Desktop there is two versions !

Let’s understand the distinctions:

  • Raspbian Stretch with desktop - Has desktop GUI, No bloatware
    This is what we use
    Should work with any Raspberry Pi 3 and above.

  • Raspbian Stretch Lite - Has only command line, No bloatware here
    Should work with any Raspberry Pi.
    Well, a word of caution against old Raspberry Pi’s out there - They burry the berries up in UK.
    It would have been nice if we could use this - Lean, Mean Machine!.

  • Raspbian Stretch with desktop and recommended software - Has desktop GUI, with lots of kinds toppings.
    Should work with any Raspberry Pi 3 and above.
    Not Recommended for IoT folks.

Once image downloaded, use a writing tool to flash it to a microSD Card.
I use Etcher : https://www.balena.io/etcher/
It’s an easy no fuss tool.

After this you can boot the Raspberry Pi with microSD Card. Then setup the pi account password to begin. It’s best if you got WiFi setup done. No problem, we would also look at that here.

Setting Up WiFi : even for Hidden SSID WiFi network #

It’s easy, just knowing the right files to edit.

Specifically the /etc/wpa_supplicant/wpa_supplicant.conf file.

Edit the WiFi Connection configuration #

Editing this file would help you setup the WiFi from Command line.

1
sudo nano /etc/wpa_supplicant/wpa_supplicant.conf

Modify the File as follows:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
country=IN

network={
	ssid="<WiFiAccessPointName>"
	psk="<WiFiPassword>"
	scan_ssid=1
	key_mgmt=WPA-PSK
	proto=RSN
	pairwise=CCMP
}

Note: Here we are looking at a WPA2 pre-shared key type WiFi network. Even with invisible network SSID, scan_ssid=1 can work out. Also note country=IN setting, to limit our Raspberry Pi WiFi to country specific bands.

Restart WiFi Services #

Just give this command:

1
sudo wpa_cli -i wlan0 reconfigure

This would reload WiFi configuration and start the network.

To Check you can use :

1
ping 8.8.8.8

That would ping the Google DNS and should work all the time.

Configuring pi account : authenticated sudo #

The pi account has access to sudo command. And it does not ask password. That’s not a good idea.

Let’s correct that:

1
sudo nano /etc/sudoers.d/010_pi-nopasswd

Modify it such that:

1
pi ALL=(ALL) PASSWD: ALL

This would make sure that using sudo command under pi user would ask for account password. Don’t forget to reboot the Raspberry Pi after these modifications.

Securing Raspberry Pi Network Interfaces #

Lets make sure that we have all the shields up! #

We would need to edit the network configuration to prevent intrusion.

1
sudo nano /etc/sysctl.conf

Modify the following lines (find them with the search in vi or grep) :

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
...

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

Save and then reboot your Raspberry Pi. Then above rules would get applied.

Note: With this setting avahi daemon would stop working. Means you would not be able to access the Raspberry Pi with hostname.local type of URI.

SSH Server for Head-less Raspberry Pi setup #

First we need to enable SSH. We can do this in two ways.

  • raspi-config tool

  • Or directly install the required packages :

1
sudo apt install -y openssh-server apt-transport-https

In beginning the setup is not secure and hence we quickly disable it:

1
sudo service ssh stop

You can also refer to my earlier article:
Security Hardening : SSH on Ubuntu
Might get some more idea about SSH setup. It might not be directly applicable here.

Securing the SSH Configuration on Raspberry Pi #

1
sudo nano /etc/ssh/sshd_config

Possibly its easier to get the full sshd_config file. Let’s look at how we modify the file in steps:

SSH Port Number #

First and easiest solutions one can suggest - changing the SSH port number. By default its 22, you might like to change it to some other number.

Its close to the top of the sshd_config file:

1
2
3
4
5
6
7
8
...
# possible, but leave them commented.  Uncommented options override the
# default value.

#Port 22
Port 1221
#AddressFamily any
...

I am bad at remembering things. I would leave it Port 22 for now. Please do go ahead, if you think it helps.

SSH Access Log #

Next in the sshd_config file - Let’s enable proper logging:

1
2
3
4
5
6
...
# Logging
SyslogFacility AUTH
#LogLevel INFO
LogLevel VERBOSE
...

SSH Authentication and timeout #

Next some changes to authentication and timeouts in sshd_config:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
...
# Authentication:

#LoginGraceTime 2m
#PermitRootLogin prohibit-password
PermitRootLogin no
#StrictModes yes
#MaxAuthTries 6
MaxAuthTries 3 
#MaxSessions 10
MaxSessions 2
AllowUsers pi

PubkeyAuthentication yes
...

One might enable StrictModes if one is too paranoid.

For multiple users you need to add them to AllowUsers.
Example: If you have users bob and alice also then it would be

1
AllowUsers pi bob alice

Similarly the DenyUser would bar user account from ssh.

SSH Host Keys #

Next we would configure the Key access in sshd_config:

1
2
3
4
...
# Expect .ssh/authorized_keys2 to be disregarded by default in future.
AuthorizedKeysFile	.ssh/authorized_keys /etc/ssh/global_authorized_keys
...

We add an additional file /etc/ssh/global_authorized_keys. This helps in case you have multiple users.

SSH Password Policies #

Next we have password policies in sshd_config:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
...
# To disable tunneled clear text passwords, change to no here!
#PasswordAuthentication yes
PasswordAuthentication no
PermitEmptyPasswords no

# Change to yes to enable challenge-response passwords (beware issues with
# some PAM modules and threads)
ChallengeResponseAuthentication no
...
# PAM authentication, then enable this but set PasswordAuthentication
# and ChallengeResponseAuthentication to 'no'.
#UsePAM yes
UsePAM no
...

SSH Gating Functions #

Finally some access gating configurations in sshd_config:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
...
#AllowAgentForwarding yes
AllowAgentForwarding no
#AllowTcpForwarding yes
AllowTcpForwarding no
GatewayPorts no
X11Forwarding yes
#X11DisplayOffset 10
#X11UseLocalhost yes
#PermitTTY yes
PrintMotd no
...

Full File #

The full sshd_config file. Make sure to rename the file to sshd_config in case you would like to replace the original file. Also check the permissions on the file. Else it would not be loaded during server start.

SSH Host Key generation #

I started key generation following the github tutorial. Eventually deviated and here is the result.

1
ssh-keygen -f .ssh/rpi_key -b 4096 -C "your_email@example.com"

This command would generate a rsa4096 in the .ssh directory. It would generate 2 files.

  • Private key - .ssh/rpi_key
  • Public key - .ssh/rpi_key.pub

Note: Execute this in the HOST PC not on the Raspberry Pi.

SSH Host Key Authorization #

Copy the public key .ssh/rpi_key.pub to a pen-drive. Then copy it over to your Raspberry Pi in a temporary location.

If you have copied to root of the pen-drive, then your copy method should be as follows:

1
2
3
4
cd
sudo mount /dev/sda1 /mnt
cp /mnt/rpi_key.pub .
sudo umount /mnt

You can remove the pen-drive after this. In the above sequence the file is copied to your user root directory.

Next we need to insert this as authorized key.

1
2
3
4
5
cd
chmod 644 rpi_key.pub
mkdir -p .ssh
cat rpi_key.pub > .ssh/authorized_keys
sudo cat rpi_key.pub > /etc/ssh/global_authorized_keys

The last line is optional. In my case pi would be the only for all purposes. Also I have one Host PC. Hence inserted the key to even the global level.

Restarting SSH Services #

1
sudo service ssh restart

That’s it you have comparatively secure SSH. #


# Watchdog for Raspberry Pi : Unattended Reset !

Using a watchdog is great for coming out of a Hang or stop situation.

Next we would look at how to enable and use the Raspberry Pi’s built in watchdog.

The name of the watchdog driver is bcm2835-wdt.

1 #

Fist we enable this feature at boot:

1
echo 'dtparam=watchdog=on' | sudo tee -a /boot/config.txt

2 #

Next enable loading of the module:

1
echo 'bcm2835-wdt' | sudo tee -a /etc/modules

3 #

Install the needed packages:

1
sudo apt-get install -y watchdog chkconfig

4 #

Edit the Watchdog configuration:

1
sudo nano /etc/watchdog.conf

Modify the file as:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
...

#test-timeout           =

watchdog-device        = /dev/watchdog

# Defaults compiled into the binary
...
# your machine is really loaded
realtime                = yes
priority                = 1
...

#at end of file add

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

With this setting the Watchdog would reset after 4 seconds.

5 #

Setup such that the Watchdog runs automatically at start-up:

1
2
sudo ln /lib/systemd/system/watchdog.service \
     /etc/systemd/system/multi-user.target.wants/watchdog.service

6 #

Start Watchdog service:

1
sudo chkconfig watchdog on

7 Check if Watchdog service #

1
sudo lsmod | grep wd



fail2ban : Protect from Brute-force attacks #

The package fail2ban has come a long way in support of multiple threat prevention. It not only protects upon SSH, also works on nginx, apache, mysql, mogodb .etc.

Let’s first install the package:

1
sudo apt install fail2ban

Copy the local configuration:

1
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local

Restart the service:

1
sudo service fail2ban restart

I am refraining from any modification in configuration of fail2ban. As, there are not updated resources on this.

You can still refer to the older version if you need.

External Network Port Check #

One can find out if they have missed fire-walling any ports on the network.

Just visit: https://hidemyna.me/en/ports/

Fill up your external IP and then run the test to see. This can help you find out if your Raspberry Pi can be accessed from outside. Typically your router would provide a way to isolate and bock ports. One can also do that using a firewall installed in your Raspberry Pi.

Epilog #

These are still only a few things one can do to secure the Raspberry Pi. As I find more tricks, this article would get updated.

A Piece of Disclaimer #

Though we are talking of securing Raspberry Pi, but method described in previous sections is still vulnerable.

One must use hardware key store or HSM modules like YubiHSM for better security.

At any point if the Private key is compromised in the above process due to weak password, no-password or direct Hacking the whole network security to the Linux is compromised.

WARNING: This free document / guide is for your convenience and its use is at your own risk. It is available as a reference only, and IS NOT INHERENTLY A SECURE WAY to connect to Linux. The author/providers cannot and do not guarantee the privacy of your data, its security and communication. There are potentially serious security issues with any computer connected to the Internet without the appropriate protection, ranging from viruses, worms and other programs that can damage the user’s computer both ways, to attacks on the computer by unauthorized or unwanted third parties. By following this guide, you acknowledge and knowingly accept the potentially serious risks of accessing your hardware unsecured over network. It is recommended that users take steps to protect their own computer system, such as installing current anti-virus software and maintaining appropriate firewall protection. You acknowledge and agree that YOUR USE OF THIS DOCUMENT & ABOVE PROCESS IS SOLELY AT YOUR OWN RISK.