create account

Secure Your Linux Server with Fail2Ban by krnel

View this thread on: hive.blogpeakd.comecency.com
· @krnel · (edited)
$27.45
Secure Your Linux Server with Fail2Ban
### [Fail2Ban](http://www.fail2ban.org/wiki/index.php/Main_Page) monitors log files to determine if someone who is trying to gain access is a legitimate user. If they aren't, they get banned temporarily by their IP address. Policies can be setup in conjunction with a firewall to log failed access attempts and drop traffic for a period of time, preventing a would-be attacker from even attempting to access your services.

<center><img src="http://www.steemimg.com/images/2016/12/03/fail2ban-logo4341e.jpg" alt="fail2ban-logo4341e.jpg" border="0"></center>
<center><em>[source](http://codelog.climens.net/2011/02/13/using-fail2ban-with-nginx-in-debian/)</em></center>

This is a continuation from 3 previous parts:
- [Secure Your Linux Server with a Firewall](https://steemit.com/cybersecurity/@krnel/secure-your-linux-server-with-a-firewall)
- [Setting Up A Linux VPS Securely (Pt.2)](https://steemit.com/cybersecurity/@krnel/setting-up-a-linux-vps-securely-pt-2)
- [Setting Up A Linux VPS Securely (Pt.1)](https://steemit.com/witness-category/@krnel/setting-up-a-linux-vps-securely-pt-1-join-me-on-my-journey-to-become-a-witness)

---
# Installation

```sudo apt-get update```

```sudo apt-get install fail2ban```

```sudo apt-get install sendmail``` (optional)

Together: ```sudo apt-get install fail2ban sendmail```

Given the previous guide for UFW being done, turn it on and allow ssh as an example.

```
ufw enable
ufw allow ssh
```

---
# Configuration

Here is where the config is located:

```/etc/fail2ban/jail.conf```

We don't edit that file though. We make a copy and comment out the contents like so:

```awk '{ printf "# "; print; }' /etc/fail2ban/jail.conf | sudo tee /etc/fail2ban/jail.local```

This file ```jail.local``` will override the defaults in ```jail.conf```, so we just add any changes there instead.

Let's see how the original file looks:

```sudo nano /etc/fail2ban/jail.conf```

# Editing configuration

If you want to exempt your own IP from multiple login security, open:

```sudo nano /etc/fail2ban/jail.local```

and add somewhere in the the following (or you can uncomment each section by removing the #):

```
[DEFAULT]
ignoreip = 127.0.0.1/8 123.45.67.89
```

127... is for the local server itself, and then 123... is an example of your own IP. This applies to all jails for all programs. If you want to whitelist an IP per jail section, like ```ssh```, use the command: ```fail2ban-client set ssh addignoreip 123.45.67.89 ```

## Bans

If you want to change how long an IP is banned for, the time interval to check for login attempt failures, or the maximum login attempt limit, then add and change the ```bantime```, ```findtime``` and ```maxretry``` parameters.

## Emails

If you want to setup email delivery of alerts from Fail2ban:

```
# ACTIONS

destemail = yourEmail@domain.com
sendername = Fail2Ban
sender = admin@server.com
mta = sendmail
```

Then add:

```action = $(action_)s```

where you replace ```action_``` with either:

- ```action_mw``` for email alerts
or
- ```action_mwl``` for w/ relevant log lines

# Jail Configuration

Apart from those main settings, are the individual service settings, like for SSH. You can look through to see what services are filtered by default.

Failregexs - these are custom filters you can make with regular expression matches that scan log files for attempted intruders. I suggest you google more into this feature and regex to learn more if you want to. Regex is powerful.

This command will tell you if fail2ban is running:

```sudo fail2ban-client status```

Apart from ```status```, there is also the ```stop and``` ```start``` command on the service, or ```restart``` to reload the configuration alone.

And then reload the changes made in the config file with:

```sudo fail2ban-client reload```

# Done

That's it. Now if anyone tries to login to your ssh configured port, and fail to enter the password three times, their IP will be banned. If you didn't add your own IP to the configuration earlier, then you will also get banned if you fail to login after 3 attempts.

---
## Recap summary:

```sudo apt-get update```
```sudo apt-get -y install fail2ban sendmail```
```awk '{ printf "# "; print; }' /etc/fail2ban/jail.conf | sudo tee /etc/fail2ban/jail.local```
```sudo nano /etc/fail2ban/jail.local```

Add exemption for your IP (either add the lines or uncomment, and edit), and the email if you want to receive:

```
[DEFAULT]
ignoreip = 127.0.0.1/8 123.45.67.89
destemail = yourEmail@domain.com
sendername = Fail2Ban
sender = admin@server.com
mta = sendmail
```

#### Reload and Done

```sudo fail2ban-client reload```
```sudo fail2ban-client status```

You should see:

```
krnel@steembuntu:~$ sudo fail2ban-client status
Status
|- Number of jail:      1
`- Jail list:   sshd
```

If not, go back into the original ```/etc/fail2ban/jail.conf``` and add a line under the [ssh] section:

```enabled  = true```

Then do this again:

```sudo fail2ban-client reload```
```sudo fail2ban-client status```

That should do it. If not, try to troubleshoot with the below section:

---
---
### If that doesn't work... or for whatever reason you want only what you need in the file, put in all these values in a new config ```/etc/fail2ban/jail.local```:

```
[INCLUDES]
before = paths-debian.conf

[DEFAULT]
ignoreip = 127.0.0.1/8 123.45.67.89
ignorecommand =
bantime  = 600
findtime  = 600
maxretry = 5
backend = auto
usedns = warn
logencoding = auto
enabled = false
filter = %(__name__)s
```

Add your email if you want:

```
destemail = yourEmail@domain.com
sendername = Fail2Ban
sender = admin@server.com
mta = sendmail
```

```
protocol = tcp
chain = INPUT
port = 0:65535
banaction = iptables-multiport

action_ = %(banaction)s[name=%(__name__)s, bantime="%(bantime)s", port="%(port)s", protocol="%(protocol)s", chain="%(chain)s"]

action_mw = %(banaction)s[name=%(__name__)s, bantime="%(bantime)s", port="%(port)s", protocol="%(protocol)s", chain="%(chain)s"]
             %(mta)s-whois[name=%(__name__)s, dest="%(destemail)s", protocol="%(protocol)s", chain="%(chain)s"]

action_mwl = %(banaction)s[name=%(__name__)s, bantime="%(bantime)s", port="%(port)s", protocol="%(protocol)s", chain="%(chain)s"]
              %(mta)s-whois-lines[name=%(__name__)s, dest="%(destemail)s", logpath=%(logpath)s, chain="%(chain)s"]
action_xarf = %(banaction)s[name=%(__name__)s, bantime="%(bantime)s", port="%(port)s", protocol="%(protocol)s", chain="%(chain)s"]
              xarf-login-attack[service=%(__name__)s, sender="%(sender)s", logpath=%(logpath)s, port="%(port)s"]

action_cf_mwl = cloudflare[cfuser="%(cfemail)s", cftoken="%(cfapikey)s"]
                 %(mta)s-whois-lines[name=%(__name__)s, dest="%(destemail)s", logpath=%(logpath)s, chain="%(chain)s"]
                 
action_blocklist_de  = blocklist_de[email="%(sender)s", service=%(filter)s, apikey="%(blocklist_de_apikey)s"]

action_badips = badips.py[category="%(name)s", banaction="%(banaction)s"]

action = %(action_mw)s
```

```
[sshd]
enabled  = true
port    = ssh
logpath = %(sshd_log)s

[sshd-ddos]
# This jail corresponds to the standard configuration in Fail2ban.
# The mail-whois action send a notification e-mail with a whois request
# in the body.
port    = ssh
logpath = %(sshd_log)s
```
If you want to enable jailing on individual services, for example in the ```[ssh]``` section, add that section to the ```jail.local``` file and add or uncomment the section as well.

Uncomment any section you want to have fail2ban enabled on, or copy and paste it at the end with the other additions, if that's what you already did.

#### Reload and Done

```sudo fail2ban-client reload```
```sudo fail2ban-client status```

---

Ok. That's it. The last section was only required if you want a cleaner file, with less filters running. You will have to add the filters you need as you need them though, since they won't be enabled by default any longer, such as HTTP for a web server fail2ban protection.

I hope the tutorial was of use to you. 

----
#### Thank you for your time and attention! I appreciate the knowledge reaching more people. Take care. Peace.

<center><img src="http://i.imgur.com/LwhouOq.gif" /><img src="http://i.imgur.com/X7bllkJ.png" /> <strong>Payout Selected</strong></center>

---
[References: [1](http://www.fail2ban.org/wiki/index.php/MANUAL_0_8), [2](https://www.digitalocean.com/community/tutorials/how-to-protect-ssh-with-fail2ban-on-ubuntu-14-04), [3](https://www.linode.com/docs/security/using-fail2ban-for-security)]

---
If you appreciate and value the content, please consider:
Upvoting <img src="https://www.steemimg.com/images/2016/08/30/upvote91a69.png" alt="upvote91a69.png" /> ,&nbsp;&nbsp;&nbsp;&nbsp;Sharing <img src="https://www.steemimg.com/images/2016/08/30/share2195b.png" alt="share2195b.png" /> **and** &nbsp;&nbsp;Reblogging <img src="https://www.steemimg.com/images/2016/09/19/reblog33b5f.png" alt="reblog33b5f.png" /> **below**.

[![Follow](https://www.steemimg.com/images/2016/08/30/follow2be5e.png)](https://steemit.com/@krnel) me for more content to come!

---
@krnel
2016-12-04, 10am
👍  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , and 198 others
properties (23)
authorkrnel
permlinksecure-your-linux-server-with-fail2ban
categorycybersecurity
json_metadata{"tags":["cybersecurity","firewall","linux","howto","tutorial"],"users":["krnel"],"image":["http://www.steemimg.com/images/2016/12/03/fail2ban-logo4341e.jpg","http://i.imgur.com/LwhouOq.gif","http://i.imgur.com/X7bllkJ.png","https://www.steemimg.com/images/2016/08/30/upvote91a69.png","https://www.steemimg.com/images/2016/08/30/share2195b.png","https://www.steemimg.com/images/2016/09/19/reblog33b5f.png","https://www.steemimg.com/images/2016/08/30/follow2be5e.png"],"links":["http://www.fail2ban.org/wiki/index.php/Main_Page","http://codelog.climens.net/2011/02/13/using-fail2ban-with-nginx-in-debian/","https://steemit.com/cybersecurity/@krnel/secure-your-linux-server-with-a-firewall","https://steemit.com/cybersecurity/@krnel/setting-up-a-linux-vps-securely-pt-2","https://steemit.com/witness-category/@krnel/setting-up-a-linux-vps-securely-pt-1-join-me-on-my-journey-to-become-a-witness","http://www.fail2ban.org/wiki/index.php/MANUAL_0_8","https://www.digitalocean.com/community/tutorials/how-to-protect-ssh-with-fail2ban-on-ubuntu-14-04","https://www.linode.com/docs/security/using-fail2ban-for-security","https://steemit.com/@krnel"],"app":"steemit/0.1","format":"markdown"}
created2016-12-04 15:00:06
last_update2016-12-04 15:06:42
depth0
children8
last_payout2017-01-04 15:36:09
cashout_time1969-12-31 23:59:59
total_payout_value25.776 HBD
curator_payout_value1.675 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length9,102
author_reputation1,343,547,270,297,082
root_title"Secure Your Linux Server with Fail2Ban"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd0
post_id1,914,468
net_rshares61,502,361,898,532
author_curate_reward""
vote details (262)
@bilbo ·
I see a lot of agressive e.g. 2-3 failed attempt configurations that forgot to whitelist their own IP, so good job there and I just wanted to reiterate that point because it is very easy to hit 3 failed attempts.

What I did not see is what I consider the best part of fail 2 ban: with minimal knowledge of regex you can create custom filters, which means you can monitor any file for specific lines and leave it up to a simple fail2ban setting (in /etc/fail2ban/filter.d which is uneditable by the apache/nginx user) for deciding whether the offending IP has done enough to warrant a ban.

Protect drupal or wordpress installations without use of yet another plugin requiring several updates per year? Yes please.

Even more powerful, any time a web developer is sanitizing input they can simply log it when the code detects a condition they would never expect.  For instance, a log line might look like "SUSPICIOUS BEHAVIOR by [IP]: submitting data to a dropdown box that is not one of the dropdown items"  And the rest -- monitoring a user for how frequently they conduct a suspicious act and banning when appropriate -- is all handled by fail2ban.  Instead what I frequently see is a developer writing the entire logging, checking, banning, and cleanup sequence into every page load.  Just look at popular security plugins for wordpress/drupal.  If you have control of the server, fail2ban and a custom filter makes for a far better option with a fraction of the effort.
👍  ,
properties (23)
authorbilbo
permlinkre-krnel-secure-your-linux-server-with-fail2ban-20161204t170919702z
categorycybersecurity
json_metadata{"tags":["cybersecurity"]}
created2016-12-04 17:09:18
last_update2016-12-04 17:09:18
depth1
children1
last_payout2017-01-04 15:36:09
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length1,474
author_reputation24,103,890,446
root_title"Secure Your Linux Server with Fail2Ban"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id1,915,324
net_rshares81,499,213,821
author_curate_reward""
vote details (2)
@krnel ·
Thanks for the feedback and extra suggestions. Much appreciated :)
properties (22)
authorkrnel
permlinkre-bilbo-re-krnel-secure-your-linux-server-with-fail2ban-20161204t172303001z
categorycybersecurity
json_metadata{"tags":["cybersecurity"]}
created2016-12-04 17:23:03
last_update2016-12-04 17:23:03
depth2
children0
last_payout2017-01-04 15:36:09
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length66
author_reputation1,343,547,270,297,082
root_title"Secure Your Linux Server with Fail2Ban"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id1,915,425
net_rshares0
@elmetro ·
Hi,
Thanks for this post, fail2ban is up one my witness server now!
Just a little mistake, it is not `action = $(action_)s` but  `action = %(action_)s`
properties (22)
authorelmetro
permlinkre-krnel-secure-your-linux-server-with-fail2ban-20180411t093309324z
categorycybersecurity
json_metadata{"tags":["cybersecurity"],"app":"steemit/0.1"}
created2018-04-11 09:33:09
last_update2018-04-11 09:33:09
depth1
children0
last_payout2018-04-18 09:33:09
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length151
author_reputation2,378,652,793,261
root_title"Secure Your Linux Server with Fail2Ban"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id49,461,388
net_rshares0
@freecrypto ·
upvoted.
properties (22)
authorfreecrypto
permlinkre-krnel-secure-your-linux-server-with-fail2ban-20161204t150158747z
categorycybersecurity
json_metadata{"tags":["cybersecurity"]}
created2016-12-04 15:02:06
last_update2016-12-04 15:02:06
depth1
children0
last_payout2017-01-04 15:36:09
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length8
author_reputation239,976,093,022,435
root_title"Secure Your Linux Server with Fail2Ban"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id1,914,481
net_rshares0
@gutzofter ·
Very good. I knew there was a reason to follow you. As I move away from windows OS and into Linux, security has been at the top of my list.
👍  
properties (23)
authorgutzofter
permlinkre-krnel-secure-your-linux-server-with-fail2ban-20161204t175644869z
categorycybersecurity
json_metadata{"tags":["cybersecurity"]}
created2016-12-04 17:56:45
last_update2016-12-04 17:56:45
depth1
children0
last_payout2017-01-04 15:36:09
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length139
author_reputation7,621,537,677,018
root_title"Secure Your Linux Server with Fail2Ban"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id1,915,658
net_rshares81,754,927,894
author_curate_reward""
vote details (1)
@okrcasebob ·
Good post friend
👍  
properties (23)
authorokrcasebob
permlinkre-krnel-secure-your-linux-server-with-fail2ban-20161205t034409519z
categorycybersecurity
json_metadata{"tags":["cybersecurity"]}
created2016-12-05 03:44:09
last_update2016-12-05 03:44:09
depth1
children0
last_payout2017-01-04 15:36:09
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length16
author_reputation379,521,186
root_title"Secure Your Linux Server with Fail2Ban"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id1,919,672
net_rshares507,043,664
author_curate_reward""
vote details (1)
@raymonjohnstone ·
Beautiful man! I wrote about creating a lambda server the other day but avoided the server hardening stuff. This guide could be used in conjunction to do so.
👍  
properties (23)
authorraymonjohnstone
permlinkre-krnel-secure-your-linux-server-with-fail2ban-20161204t153821233z
categorycybersecurity
json_metadata{"tags":["cybersecurity"]}
created2016-12-04 15:38:21
last_update2016-12-04 15:38:21
depth1
children1
last_payout2017-01-04 15:36:09
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length157
author_reputation14,614,836,628,125
root_title"Secure Your Linux Server with Fail2Ban"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id1,914,717
net_rshares88,245,508,107
author_curate_reward""
vote details (1)
@krnel ·
Sweet!
👍  
properties (23)
authorkrnel
permlinkre-raymonjohnstone-re-krnel-secure-your-linux-server-with-fail2ban-20161204t154104281z
categorycybersecurity
json_metadata{"tags":["cybersecurity"]}
created2016-12-04 15:41:03
last_update2016-12-04 15:41:03
depth2
children0
last_payout2017-01-04 15:36:09
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length6
author_reputation1,343,547,270,297,082
root_title"Secure Your Linux Server with Fail2Ban"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id1,914,735
net_rshares6,131,804,907
author_curate_reward""
vote details (1)