Creating a Firewall

Now it’s time to set up a firewall to limit and block unwanted inbound traffic to your Pi. This step is optional, but we strongly recommend that you use the example below to block traffic to ports that are not commonly used. It’s a good way to deter would-be intruders! You can always modify the rules or disable the firewall later.

Here’s how to create a firewall on your Pi:

Check your Pi’s default firewall rules by entering the following command:

Examine the output. If you haven’t implemented any firewall rules yet, you should see an empty ruleset, as shown below:

Create a file to hold your firewall rules by entering the following command:

Now it’s time to create some firewall rules. We’ve created some basic rules to get you started. Copy and paste the rules shown below in to the iptables.firewall.rules file you just created.

Edit the rules as necessary. By default, the rules will allow traffic to the following services and ports: HTTP (80), HTTPS (443), SSH (22), and ping. I also added SMTP, Pop and IMAP as we need those later. All other ports will be blocked.

Save the changes to the firewall rules file by pressing Control-X, and then Y.

Activate the firewall rules by entering the following command:

Recheck your Pi’s firewall rules by entering the following command:

Examine the output. The new ruleset should look like the one shown below:

Now you need to ensure that the firewall rules are activated every time you restart your Pi.

Start by creating a new script with the following command:

Copy and paste the following lines in to the file you just created:

Press Control-X and then press Y to save the script. Set the script’s permissions by entering the following command:

That’s it! Your firewall rules are in place and protecting your Pi. Remember, you’ll need to edit the firewall rules later if you install other software or services.

Installing and Configuring Fail2Ban

Fail2Ban is an application that prevents dictionary attacks on your server. When Fail2Ban detects multiple failed login attempts from the same IP address, it creates temporary firewall rules that block traffic from the attacker’s IP address. Attempted logins can be monitored on a variety of protocols, including SSH, HTTP, and SMTP. By default, Fail2Ban monitors SSH only.

Here’s how to install and configure Fail2Ban. Install Fail2Ban by entering the following command:

Fail2Ban is now installed and running on your Pi. It will monitor your log files for failed login attempts. After an IP address has exceeded the maximum number of authentication attempts, it will be blocked at the network level and the event will be logged in /var/log/fail2ban.log.