How to install fail2ban on a Raspberry Pi

Fail2ban scans log files and bans IPs that show malicious signs, such as too many password failures, seeking for exploits, etc. More information can be found at http://www.fail2ban.org/wiki/index.php/Main_Page

Install and configure fail2ban

  • Install the fail2ban package:


    sudo apt-get update ; sudo apt-get install fail2ban

  • Open the configuration file for editing:


    sudo vi /etc/fail2ban/jail.local

    …and paste the content below (assuming you private IP addresses are in the range 192.168.0.*):

    # SSH
    # 3 failed retry: Ban for 15 minutes
    [ssh]
    enabled = true
    port = ssh
    filter = sshd
    action = iptables[name=SSH, port=ssh, protocol=tcp]
    mail-whois-lines[name=%(__name__)s, dest=%(destemail)s, logpath=%(logpath)s]
    logpath = /var/log/auth.log
    maxretry = 3
    bantime = 900
    ignoreip = 192.168.0.0/16

    [ssh-ddos]
    enabled = true
    port = ssh
    filter = sshd-ddos
    action = iptables[name=SSH, port=ssh, protocol=tcp]
    logpath = /var/log/auth.log
    maxretry = 10
    ignoreip = 192.168.0.0/16

  • Restart the fail2ban service:

    sudo /etc/init.d/fail2ban restart

  • Check the log file to ensure it is working:

    sudo tail -f /var/log/fail2ban.log

How to connect to your Raspberry Pi using SSH key pairs

Using an SSH key to log on to your Raspberry Pi has a number of advantages over the tradition password-only method. Amongst others:

  • A password is not transmitted over the network, preventing interception by eavesdropping.
  • The risk posed by brute force password attack is reduced considerably.
  • Automatic login is possible without having to continuously enter your password (if you use an SSH agent such as Pageant).

In the instructions below, we will create a key pair. One of the keys is known as a public key, and the other a private key. The private key must be closely guarded, but the public key can be distributed freely.

As stated, the private key must be kept secure, so that only you have access to it, and typically it will be strored in encrypted form, requiring a passphrase to open it. In the scenario I present below, the private key will be stored on your PC in encrypted form. A piece of software called Pageant is used to manage this key (and any others you have), and will challenge you for a passphrase when you try to open the key. Once the key is open in Pageant, you will not need to enter the passphrase again unless you exit Pageant or close the key.

The public key will be copied to the Raspberry Pi, and saved in a directory owned by the user “pi”. This directory (/home/pi/.ssh) will be protected by permissions to prevent unauthorised users from placing their own public keys here and thus gaining access with their own key pairs.

With the two keys in place, and Pageant acting as the SSH agent for the private key, Putty software can be used to connect to the Raspberry Pi as user “pi” over SSH.

In order to create the keys in the first place, there are many ways we can do this, but here we will use yet another piece of software, called Puttygen.

Create the keys using PuTTYgen

  • Download PuTTYgen to your PC from http://the.earth.li/~sgtatham/putty/latest/x86/puttygen.exe
  • Run the PuTTYgen.exe file you just downloaded to display the “PuTTY Key Generator” window.
  • Select SSH-2 RSA as the “Type of key to generate” and leave the “Number of bits in a generated key” set to 2048.
  • Click “Generate” and then move the cursor around the blank grey area of the “Key” pane to randomly generate a unique key. On completion, you will see information about the key.
  • Don’t touch the “Key fingerprint” or “Key comment” fields, but enter a passphrase in the “Key passphrase” and “Confirm passphrase” fields. This will encrypt the key on the PC disk and prevent unauthorised access.
  • Click “Save public key” and you will be prompted for the name and location of the public key. Let’s call it “MyPi.pub”, and save it somewhere sensible on your PC.
  • Click “Save private key” and you will be prompted for the name and location of the public key. Let’s call it “MyPi.ppk”, and save it to the same location as your public key.
  • You can now close PuTTYgen.

Copy the public key to your Raspberry Pi

  • Use PuTTY (available from http://the.earth.li/~sgtatham/putty/latest/x86/putty.exe) to log on to your Raspberry Pi as user “pi”
  • Create a directory for the public key and move into it:

    mkdir -p ~/.ssh
    cd ~/.ssh
  • Open the authorized_keys file for editing (assuming it doesn’t already exist):

    sudo vi ~/.ssh/authorized_keys

    …and copy and paste the content of the MyPi.pub key into it. It has to be EXACTLY the same as the original, otherwise it won’t work. You can add multiple keys to the authorized_keys file if necessary, but each one will be on a new line in the file. Save and exit the file.
  • Secure the keys file with:

    sudo chmod 644 ~/.ssh/authorized_keys
    sudo chown pi:pi ~/.ssh/authorized_keys
    sudo chmod 700 ~/.ssh

Test that the key pair works

  • Open the sshd configuration file for editing with:

    sudo vi /etc/ssh/sshd_config

    …and add to the end of the file:

    UsePAM no
    PermitRootLogin no
    AllowUsers pi
    RSAAuthentication yes
    PubkeyAuthentication yes
    AuthorizedKeysFile .ssh/authorized_keys
    PasswordAuthentication yes
  • Restart the ssh service with:
    sudo service ssh restart
  • Exit your PuTTY session, and download the Pageant software from http://the.earth.li/~sgtatham/putty/latest/x86/pageant.exe
  • Run the Pageant software you just downloaded, and click “Add Key”. Select the private key file you just created (“MyPi.ppk”) and enter your passphrase when prompted.
  • Now open PuTTY again and try to connect to the Raspberry Pi as user “pi”. You shouldn’t be prompted for a password. If you are, the keys are not matched, or there is a problem with the /etc/ssh/sshd_config file.
  • If all is well, you can continue on to the final step

Disable password authentication on the Raspberry Pi

Now that we have confirmed that we can connect to the Raspberry Pi using keys, we can turn off password authentication altogether for added security.

  • Open the sshd configuration file for editing with:

    sudo vi /etc/ssh/sshd_config

    …and change:

    PasswordAuthentication yes

    …to:

    PasswordAuthentication no
  • Restart the ssh service with:
    sudo service ssh restart
  • Exit your PuTTY session, and then open a new PuTTY session. You should connect immediately without being challenged for authentication.

When you have finished working on the Raspberry Pi

Remember to close down Pageant when you have finished working on the Raspberry Pi, otherwise other users with access to your PC willl be able to connect to your Raspberry Pi without being challenged.

How to install the Raspbian OS on a Raspberry Pi

What you need

As well as a Raspberry Pi Model B Revision 2 board (which includes an ethernet port and more RAM than the Model A), you will also need an SD card (minimum of 4Gb) and a power supply with corresponding Micro USB power cable. Don’t skimp on the power supply, stability problems with a Raspberry Pi can more often than not be attributed to a poor supply. 700mAh is the minimum you should be looking at, but 1A is the realistic minimum. If you intend to communicate with your Raspberry Pi over WiFi, you will need a USB dongle. Alternatively, for a cheaper option, you can communicate directly with your router or network hub via an ethernet cable. A USB keyboard and HDMI monitor will be required for the initial setup, but can be removed afterward, as we will be running the Raspberry Pi “headless”.

Getting the Operating System for the Raspberry Pi onto an SD card

  1. Download Win32DiskImager from http://sourceforge.net/projects/win32diskimager/
  2. Download Raspbian from http://downloads.raspberrypi.org/raspbian_latest
  3. Extract the Raspbian image file from the downloaded .zip file, so you now have a file called something like “2014-01-07-wheezy-raspbian.img” (the version you download may be later than this one).
  4. Insert an SD card (at least 4Gb, but this will only leave around 500Mb for your data) into the SD card reader on your PC and check which drive letter it was assigned (for example G:).
  5. Extract the Win32DiskImager executable from the zip file and run the Win32DiskImager utility; you may need to run the utility as Administrator (right-click on the file, and select “Run as Administrator”).
  6. Select the Raspbian image file you extracted above.
  7. Select the drive letter of the SD card in the “Device” box. Be careful to select the correct drive; if you get the wrong one you may destroy the data on your computer’s hard disk!
  8. Click “Write” and wait patiently for the write to complete – it will take several minutes.
  9. Exit Win32DiskImager and eject the SD card.
  10. You can now insert the SD card into the SD card slot on your Raspberry Pi.

Connecting the Raspberry Pi

  1. With the SD card inserted in the Raspberry Pi, connect it to your TV input using an HDMI cable.
  2. Plug in a USB keyboard (and mouse, if you have one handy).
  3. Turn on your TV and select the appropriate source input.
  4. Connect the Raspberry Pi to your power source (there is no “on/off” switch on the Raspberry Pi).

First time boot

When the first-time boot menu appears (also accessible later with the command sudo raspi-config), set the following options:

  • Expand the file system (so that we can make full use of the space on the SD card).
  • For the sake of security, change the default password for user “pi”, and make sure you can remember it.
  • Select the correct internationalization options (locale “en_GB.UTF8”, and timezone “London” in my case)
  • Select “Advanced Options” and set the following:
    • Memory Split = 16 (The Raspberry Pi Type B only has 512Mb of RAM, which is shared between the CPU and the GPU. We will not be running the desktop, so we can reduce the memory allocation for graphics and leave it free for the system to make use of).
    • Hostname = pi-rsync (or whatever you want to call it).
    • SSH = Enable (otherwise we will not be able to run the Raspberry Pi “headless”.
    • Update = Update this tool to the latest version
  • Select “Overclock” and set it to “Turbo” mode (more information is available at http://www.raspberrypi.org/archives/tag/overclocking – make sure you read it first so that you know the implications).
  • Select Finish
  • Reboot the Raspberry Pi

Configure wi-fi and ethernet

  • When the Raspberry Pi has rebooted, shut it down again, safely, with the following command:

    sudo shutdown -h now

  • Power down completely by disconnecting the power source
  • Insert your USB WiFi dongle in a spare USB port on your Raspberry Pi (you may need to unplug your mouse to do do this).
  • Power up the Raspberry Pi.
  • Log in as user “pi” and supply the new password you created earlier.
  • To make a backup of the default network interfaces configuration file, issue the command:

    sudo cp -p /etc/network/interfaces /etc/network/interfaces.eth0

  • Edit the network interfaces configuration file by issuing the command

    sudo vi /etc/network/interfaces

  • …and replace the entire content of the file with the following. You will need to replace the <SSID> and <password> with the correct information for your wireless base station.


    auto lo
    iface lo inet loopback
    iface eth0 inet dhcp
    allow-hotplug wlan0
    auto wlan0
    iface wlan0 inet dhcp
    wpa-ssid "<SSID>"
    wpa-psk "<password>"

  • Save the changes you made and exit the vi editor.
  • Back up the file you just edited by issuing the command

    sudo cp -p /etc/network/interfaces /etc/network/interfaces.wlan0

  • Do you want to communicate with the Raspberry Pi via ethernet or WiFi? For the former, enter the command:

    sudo cp -p /etc/network/interfaces.eth0 /etc/network/interfaces…and for the latter, enter:

    sudo cp -p /etc/network/interfaces.wlan0 /etc/network/interfaces

  • shutdown the Raspberry Pi with the command:

    sudo shutdown -h now

  • Power down completely by disconnecting the power source
  • If you chose to communicate via ethernet, remove the WiFi dongle, and connect a network cable between the Raspberry Pi and your router.
  • Power up your Raspberry Pi, and log in again as user “pi”
  • You will need to know your IP address. Find this out by entering the command:

    ifconfig
    Look for the IP address displayed alongside “inet address:”, which may be in the “eth0” or “wlan0” section, depending on how you are connecting. In my case, the IP address is “192.168.0.105”.

Tighten up the security on OpenSSH

  • Connect to your Raspberry Pi using Putty from your PC, and log in as user “pi”.
  • Issue the following commands:


    sudo cp /etc/ssh/sshd_config ~
    sudo vi /etc/ssh/sshd_config

  • Change the “PermitRootLogin” directive to read:

    PermitRootLogin no

  • To restrict SSH access to user “pi”, add this directive to the end of the file:


    AllowUsers pi

    If you also want to allow www-data to access via SSH, use the following directive instead:

    AllowUsers pi www-data

  • Restart ssh by running the command:

    sudo service ssh restart

  • At this point, you may want to configure ssh key access, fail2ban, and iptables for added security, but they are not absolutely necessary.

Update the OS packages

  • Issue the following command as user “pi”:

    sudo apt-get update ; sudo apt-get upgrade

The upgrade part of the command could take a long time, the first time it is run. You should repeat this process every so often to stay up-to-date.

Install ramlog to prolong the life of your SD card

Update: Note that http://www.tremende.com, the usual location for downloading the ramlog package, no longer exists so the link in the “wget” command below takes you to a copy saved on Dropbox.

SD cards typically have a lifetime of up to 100,000 writes, so we want to minimise the number of times we write to the card. In the following instructions we use a piece of software called ramlog. Instead of being written directly to the card, log data is written to ramlog, and transferred to the card, every so often, en masse.

  • Issue the following commands as user “pi”:


    sudo apt-get install lsof
    cd ~ ; wget https://dl.dropboxusercontent.com/u/17167615/PiPackages/ramlog_2.0.0_all.deb
    sudo dpkg -i ramlog_2.0.0_all.deb
    sudo vi /etc/default/ramlog

  • Change the maximum memory size setting as follows:

    TMPFS_RAMFS_SIZE=40m

  • Reboot the Raspberry Pi with the following command:

    sudo reboot

  • The Raspberry Pi will reboot, and you will need to restart your Putty session. You can check the status of ramlog with the following command:

    sudo /etc/init.d/ramlog status