Protect SSH services with fail2ban

If you’ll open SSH on a server to the open internet, you’ll notice a lot of bots trying to login. You certainly should setup certificate based login, but banning offending IPs is also an important security measure.

I’ve installed fail2ban on my Raspbian installations and want to explain the installation and configuration. Its quite easy and the benefits are huge!

sudo apt-get install fail2ban

Create a copy of the original configuration file so that it won’t be overwritten by any updates:

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

Search for a block for [default]. You should set:

bantime = 10m
findtime = 10m
maxretry = 5

These are the general settings. The settings for sshd should be a little bit stricter. Search a block for [sshd]. You should set:

enabled = true
maxretry = 3

You can enable and start fail2ban now using systemctl:

sudo systemctl enable fail2ban
sudo systemctl start fail2ban

Verify its up and running:

sudo systemctl status fail2ban.service
sudo fail2ban-client status
sudo fail2ban-client status sshd

If you end up being locked out, you can unlog an offending IP address using this command:

sudo fail2ban-client set sshd unbanip <offenders IP>

Banned connections will be dropped immediately by the firewall and should be visible with a “connection refused”.

Configure mail transport agent on Raspbian with external SMTP server

I want to get email notifications for actions on my Raspberry Pi using Raspbian. You could setup a separate mail server for that action but that seems to be a little bit overkill.

msmtp is a mail transfer agent which uses a configured smtp server for email transfer. This allows you to send emails via a configured smtp server (in my case from my webspace provider All-Inkl.com – by creating a new account using this link you’ll support the costs for running this blog).

Upgrade your raspbian:

sudo apt-get update && sudo apt-get upgrade

Install msmtp:

sudo apt-get install msmtp msmtp-mta mailutils

Get the location of the configuration files:

> msmtp --version
msmtp version 1.6.6
Platform: arm-unknown-linux-gnueabihf
TLS/SSL library: GnuTLS
Authentication library: GNU SASL
Supported authentication methods:
plain scram-sha-1 external gssapi cram-md5 digest-md5 login ntlm
IDN support: enabled
NLS: enabled, LOCALEDIR is /usr/share/locale
Keyring support: none
System configuration file name: /etc/msmtprc
User configuration file name: /home/pi/.msmtprc

Copyright (C) 2016 Martin Lambers and others.
This is free software.  You may redistribute copies of it under the terms of
the GNU General Public License <http://www.gnu.org/licenses/gpl.html>.
There is NO WARRANTY, to the extent permitted by law.

Configure the system configuration:

sudo vi /etc/msmtprc

The content of my configuration file (note the necessary changes for servers and email addresses):

# Set default values for all following accounts.
defaults

# Use the mail submission port 587 instead of the SMTP port 25.
port 465

# Always use TLS.
tls on
tls_starttls off

# Set a list of trusted CAs for TLS. The default is to use system settings, but
# you can select your own file.
tls_trust_file /etc/ssl/certs/ca-certificates.crt

# If you select your own file, you should also use the tls_crl_file command to
# check for revoked certificates, but unfortunately getting revocation lists and
# keeping them up to date is not straightforward.
#tls_crl_file ~/.tls-crls

# Mail account
# TODO: Use your own mail address
account user@domain.name

# Host name of the SMTP server
# TODO: Use the host of your own mail account
host <your Username provided by KAS>.kasserver.com

# As an alternative to tls_trust_file/tls_crl_file, you can use tls_fingerprint
# to pin a single certificate. You have to update the fingerprint when the
# server certificate changes, but an attacker cannot trick you into accepting
# a fraudulent certificate. Get the fingerprint with
# $ msmtp --serverinfo --tls --tls-certcheck=off --host=smtp.freemail.example
#tls_fingerprint 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33

# Envelope-from address
# TODO: Use your own mail address
from user@domain.name

# Authentication. The password is given using one of five methods, see below.
auth on

# TODO: Use your own user name fpr the mail account
user <The username of the email account you use for sending emails>

# Password method 1: Add the password to the system keyring, and let msmtp get
# it automatically. To set the keyring password using Gnome's libsecret:
# $ secret-tool store --label=msmtp \
#   host smtp.freemail.example \
#   service smtp \
#   user joe.smith

# Password method 2: Store the password in an encrypted file, and tell msmtp
# which command to use to decrypt it. This is usually used with GnuPG, as in
# this example. Usually gpg-agent will ask once for the decryption password.
#passwordeval gpg2 --no-tty -q -d ~/.msmtp-password.gpg

# Password method 3: Store the password directly in this file. Usually it is not
# a good idea to store passwords in plain text files. If you do it anyway, at
# least make sure that this file can only be read by yourself.
# TODO: Use the password of your own mail account
password <The password of the email account you use for sending emails>

# Password method 4: Store the password in ~/.netrc. This method is probably not
# relevant anymore.

# Password method 5: Do not specify a password. Msmtp will then prompt you for
# it. This means you need to be able to type into a terminal when msmtp runs.

# Set a default account
# TODO: Use your own mail address
account default: user@domain.name

# Map local users to mail addresses (for crontab)
aliases /etc/aliases

This file contains a username and password. Therefore limit its access to only root:

sudo chmod 600 /etc/msmtprc

Duplicate the config file to ~/.msmtprc if you want to provide email configuration for your user as well.

Now configure the recipients for your systems users by setting the recipients in /etc/aliases. Make sure, that you don’t have trailing spaces behind the email addresses:

root: user@domain.name
default: user@domain.name

Let your computer now that msmtp should be used as replacement for sendmail by adding this content to /etc/mail.rc

set sendmail="/usr/bin/msmtp -t"

Test your configuration by sending an email from the terminal:

echo "Content of your mail" | mail -s "Subject" user@domain.name

Monitor Fritz!Box connection statistics with Grafana, InfluxDB and Raspberry Pi

I’ve recently stumbled over an article in the german magazine C’T about visualisations of your Fritz!Box’s connection. The solution looked quite boring and outdated, since it used MRTG for the graph creation.

I’ve started searching for a better solution using Grafana, InfluxDB and my Raspberry Pi and found this great blog post. I’ve already explained how to install Grafana and InfluxDB in this post, so I’ll concentrate on the Fritz!Box related parts:

Start with the installation of fritzcollectd. It is a plugin for collectd.

sudo apt-get install -y python-pip
sudo apt-get install -y libxml2-dev libxslt1-dev
sudo pip install fritzcollectd

Now create a user account in the Fritz!Box for collectd. Go to System, Fritz!Box-user and create a new user with password, who has access from internet disabled. The important part is to enable “Fritz!Box settings”.

Additionally make sure that your Fritz!Box is configured to support connection queries using UPnP. You can configure this under “Home Network > Network > Networksettings”. Select “Allow access for applications” as well as “Statusinformation using UPnP”.

Next part is the installation and configuration of collectd:

sudo apt-get install -y collectd
sudo nano /etc/collectd/collectd.conf

Enable the python and network plugins by removing the hashtag

LoadPlugin python
[...]
LoadPlugin network

Scroll down till you’ll see the plugin configuration and configure the port and IP for collectd

<Plugin network>
    Server "127.0.0.1" "25826"
</Plugin>

Enable the python plugin and configure the module with the username and password of the user you’ve created. Make also sure to use the right address.

<Plugin python>
    Import "fritzcollectd"

    <Module fritzcollectd>
        Address "fritz.box"
        Port 49000
        User "user"
        Password "password"
        Hostname "FritzBox"
        Instance "1"
        Verbose "False"
    </Module>
</Plugin>

Since you’ve already got a running InfluxDB, you’ll just need to enable collectd as data source:

sudo nano /etc/influxdb/influxdb.conf

Search for the [collectd] part and replace it with

[[collectd]]
  enabled = true
  bind-address = "127.0.0.1:25826"
  database = "collectd"
  typesdb = "/usr/share/collectd/types.db"

Reboot collectd and influx to activate the changes made

sudo systemctl restart collectd
sudo systemctl restart influxdb

Login to your grafana installation and configure a new datasource. Make sure to set the collectd database. If you’re using credentials for the InfluxDB, you can add them now. If you’re not using authentication you can disable the “With credentials” checkbox.

Check if your configuration is working by clicking on “Save & Test”.

If everything worked, you can proceed to importing the Fritz!Box Dashboard from the Grafana.com dashboard. The ID is 713. Make sure to select the right InfluxDB during the import setup.

After clicking on import, you’ll should be able to see your new Dashboard. It might take a few minutes/hours until you’ve gathered enough data to properly display graphs.

Be aware though that if you start gathering this much data you’ll might end up with “insufficient memory” errors. You’ll might want to tweak your InfluxDB settings accordingly.

Auto mount NFS shares on Raspbian

I’m using influxdb on my Raspberry Pi in combination with a NFS mount. The NFS mount is on my Synology NAS and should store the database data of influxdb. Reason for this setup is that I fear that the SD card won’t survive the many write/read cycles caused by a database writing to it.

The shared folder on my Synology is configured to be accessible by various IPs in my network:

The problem with Raspbian is that I’ve tried to auto mount the NFS share on startup, so that the influxdb service can directly write to the NFS mount. 

I’ve used these settings in my /etc/fstab to mount the volume automatically:

<DS IP>:/volume1/databases /mnt/databases nfs auto,user,rw,nolock,nosuid 0 0

This doesn’t work properly since my influxdb is often dead after a restart, but if I check the mounted volumes I see the NFS volume mounted properly.

However, there’s a tool called autofs which already helped me with a similar problem on my Mac when I moved my iTunes library to the Synology share.

Install autofs using

sudo apt-get install autofs

Open the file /etc/auto.master and add something like this

/mnt    /etc/auto.databases     -nosuid,noowners

Now create a file called /etc/auto.databases with this content

databases       -fstype=nfs,user,nolock,nosuid,rw <DS IP>:/volume1/databases

Unmount the existing NFS share. Remove/comment out the line for the nfs mount in your /etc/fstab so that it doesn’t conflict with autofs. Restart autofs with

sudo service autofs restart

Now check the content of your mount point with e.g.

ls /mnt/databases

Autofs should now automatically mount the NFS share. This might take a while, which is a good sign that the mount is loaded. You can also verify with

mount

that your NFS share is mounted to e.g. /mnt/databases. If you’ll restart now, influxdb should be happy on restart. When it tries to start, autofs will see the access to the mounted folder and will mount the NFS share before influxdb can start up properly.

Howto install InfluxDB and Grafana on a Raspberry Pi 3

Inspired by a friend I’ve decided to install InfluxDB and Grafana on my Raspberry Pi 3. InfluxDB is a database optimized for storing time related data like measurements of my recently installed particle sensor. Grafana is used to create beautiful graphs to display the stored data.

The InfluxDB installation can be done in a few simple steps:

curl -sL https://repos.influxdata.com/influxdb.key | sudo apt-key add -

echo "deb https://repos.influxdata.com/debian stretch stable" | sudo tee /etc/apt/sources.list.d/influxdb.list

sudo apt update

sudo apt install influxdb  

sudo systemctl enable influxdb

sudo systemctl start influxdb 

influx

CREATE DATABASE topics

This will install the InfluxDB without a user and any rights. You can read up further on that topic. Ideally you should setup an user for authentication but since some IoT devices do not support this I’m not going to explain it here.

The Grafana installation is similar simple:

Please make sure that you’ll get the most current version from github and replace it in the wget command:

wget https://github.com/fg2it/grafana-on-raspberry/releases/download/v5.1.4/grafana_5.1.4_armhf.deb

sudo dpkg -i grafana_5.1.4_armhf.deb

sudo systemctl enable grafana-server 

sudo systemctl start grafana-server

First login to Grafana:

Now you’re ready to configure Grafana. Go to http://<ip-of-grafana-machine>:3000 and setup a new username and password for the webinterface. The default is admin/admin

Configure InfluxDB as datasource in Grafana:

You need to configure a datasource under http://<ip-of-grafana-machine>:3000/datasources

Enter as name the name of the database you’ve created earlier. In this case it was topic.

The type of the database is InfluxDB.

The HTTP connection URL is http://localhost:8086

Hit Save & Test, once you’ve configured everything to your liking. The connection to the database should work now.