This article covers a version of Ubuntu that is no longer supported. If you are currently operate a server running Ubuntu 12.04, we highly recommend upgrading or migrating to a supported version of Ubuntu:
Reason: Ubuntu 12.04 reached end of life (EOL) on April 28, 2017 and no longer receives security patches or updates. This guide is no longer maintained.
See Instead:
This guide might still be useful as a reference, but may not work on other Ubuntu releases. If available, we strongly recommend using a guide written for the version of Ubuntu you are using. You can use the search functionality at the top of the page to find a more recent version.
Servers do not exist in isolation, and those virtual private servers with only the most basic SSH configuration can be vulnerable to brute force attacks. fail2ban provides a way to automatically protect virtual servers from malicious behavior. The program works by scanning through log files and reacting to offending actions such as repeated failed login attempts.
Use apt-get to install Fail2Ban
sudo apt-get install fail2ban
The default fail2ban configuration file is location at /etc/fail2ban/jail.conf. The configuration work should not be done in that file, however, and we should instead make a local copy of it.
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
After the file is copied, you can make all of your changes within the new jail.local file. Many of possible services that may need protection are in the file already. Each is located in its own section, configured and turned off.
Open up the the new fail2ban configuration file:
sudo nano /etc/fail2ban/jail.local
The first section of defaults covers the basic rules that fail2ban will follow. If you want to set up more nuanced protection on your virtual server, you can customize the details in each section.
You can see the default section below.
[DEFAULT] # "ignoreip" can be an IP address, a CIDR mask or a DNS host ignoreip = 127.0.0.1/8 bantime = 600 maxretry = 3 # "backend" specifies the backend used to get files modification. Available # options are "gamin", "polling" and "auto". # yoh: For some reason Debian shipped python-gamin didn't work as expected # This issue left ToDo, so polling is default backend for now backend = auto # # Destination email address used solely for the interpolations in # jail.{conf,local} configuration files. destemail = root@localhost
Write your personal IP address into the ignoreip line. You can separate each address with a space. IgnoreIP allows you white list certain IP addresses and make sure that they are not locked out. Including your address will guarantee that you do not accidentally ban yourself from your own server.
The next step is to decide on a bantime, the number of seconds that a host would be blocked from the VPS if they are found to be in violation of any of the rules. This is especially useful in the case of bots, that once banned, will simply move on to the next target. The default is set for 10 minutes—you may raise this to an hour (or higher) if you like.
Maxretry is the amount of incorrect login attempts that a host may have before they get banned for the length of the ban time.
You can leave the backend as auto.
Destemail is the email that alerts get sent to. If you have a mail server set up on your droplet, Fail2Ban can email you when it bans an IP address.
The Actions section is located below the defaults. The beginning looks like this:
# # ACTIONS # # Default banning action (e.g. iptables, iptables-new, # iptables-multiport, shorewall, etc) It is used to define # action_* variables. Can be overridden globally or per # section within jail.local file banaction = iptables-multiport # email action. Since 0.8.1 upstream fail2ban uses sendmail # MTA for the mailing. Change mta configuration parameter to mail # if you want to revert to conventional 'mail'. mta = sendmail # Default protocol protocol = tcp [...]
Banaction describes the steps that fail2ban will take to ban a matching IP address. This is a shorter version of the file extension where the config if is located. The default ban action, "iptables-multiport", can be found at /etc/fail2ban/action.d/iptables-multiport.conf
MTA refers to email program that fail2ban will use to send emails to call attention to a malicious IP.
You can change the protocol from TCP to UDP in this line as well, depending on which one you want fail2ban to monitor.
The SSH details section is just a little further down in the config, and it is already set up and turned on. Although you should not be required to make any changes within this section, you can find the details about each line below.
[ssh] enabled = true port = ssh filter = sshd logpath = /var/log/auth.log maxretry = 6
Enabled simply refers to the fact that SSH protection is on. You can turn it off with the word "false".
The port designates the port that fail2ban monitors. If you have set up your virtual private server on a non-standard port, change the port to match the one you are using:
eg. port=30000
The filter, set by default to sshd, refers to the config file containing the rules that fail2ban uses to find matches. sshd refers to the /etc/fail2ban/filter.d/sshd.conf.
log path refers to the log location that fail2ban will track.
The max retry line within the SSH section has the same definition as the default option. However, if you have enabled multiple services and want to have specific values for each one, you can set the new max retry amount for SSH here.
After making any changes to the fail2ban config, always be sure to restart Fail2Ban:
sudo service fail2ban restart
You can see the rules that fail2ban puts in effect within the IP table:
sudo iptables -L
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
Cool article. “If you have a mail server set up on your droplet” - How would we go about enabling this on Ubuntu?
Droplets are what we call virtual servers so it would be the same instructions for any installation of Ubuntu.
“Write your personal IP address into the ignoreip line.” – Are you saying the IP address of my server, or the IP address I am likely to be connecting from?
The IP that you will be connecting from.
cp and nano commands need sudo.
Updated. Thank you
Does Fail2Ban start automatically when the server reboots?
Yes, it does start automatically.
This tutorial didn’t work for me until I changed ‘backend = auto’ to ‘backend = polling’ on my ubuntu 12.04 droplet.
“iptables -L” should be “sudo iptables -L”
can fail2ban work with ufw?
Yes it should be possible.
Fail2ban Actions: The directory /etc/fail2ban/action.d contains different scripts defining actions which will execute once a filter matches. Only one filter is allowed per service, but it is possible to specify several actions, on separate lines.
I would start there, but the default is to use iptables and since fail2ban is an automated solution you can easily use iptables without knowing how it works.
Goyal,
UFW and iptables-multiport are completely compatible, however UFW will not show you banned IP addresses. You can still manage your basic firewall with UFW.
If you need to see banned IP addresses you have multiple options. iptables --list -n | fgrep DROP or fail2ban-client status ssh
Either will show you currently banned IP addresses. the fail2ban-client will show you the IP addresses it is managing (via bantime limits).
Hope that helps.
Shouldn’t you sudo mv the .local file to .conf afterwards?
might want to edit the configs using sudoedit instead of nano, running sudo nano can set the nano history file to be owned by root which makes for some fun error messages down the road.
“Write your personal IP address into the ignoreip line.”
– any solution if you have dynamic IP, or does that simply defeat the purpose?
+Marius If you use DynDNS (http://dyn.com/dns/) you can get a hostname allocated to your dynamic address. Most routers have the functionality to update whenever the IP address changes.
I just followed these instructions, now in /var/log/fail2ban.log I’m seeing the following lines hundreds of times:
fail2ban.filter : WARNING Determined IP using DNS Reverse Lookup: na-200-38-75-72.static.avantel.net.mx = [‘200.38.75.72’] fail2ban.filter : WARNING Determined IP using DNS Reverse Lookup: demodigitool.gsl.com.mx = [‘200.38.75.72’]
What does that mean? Is this normal? I don’t recognize the IP address.
Thanks
Good Tutorial to get started securing my VM.
is this compatible with nginx by default? or we need to modified it first? I’ve googling and found several article about how to make file2ban works with nginx. I got several configuration and modification that I can’t understand >,< Help me please…??
For users on 12.10, it seems that fail2ban is now shipping with filters for most everything already built in.
I also have a dynamic ip, So I set up an acount with DynDNS… But how can I now SSH to my droplet using my DynDNS host name - so I can whitelist it in fail2ban? I configured my router’s DDNS settings successfully, however when I check my SSH access log after logging in it still shows my dynnamic IP and not my DynDNS hostname.
@cowsun.tech the ignoreip directive accepts a DNS hostname therefore you can put your DynDNS host in there.
@Kamal Nasser : Yeah I don’t know how to use the dyndns hostname I’ve setup to access my droplet. In the ssh access log it shows my same dynamic IP from my ISP not DynDNS’s, and after each subsequent login the welcome reads: Welcome to Ubuntu 12.04 LTS (GNU/Linux 3.2.0-23-virtual x86_64)
@cowsun.tech that’s because your IP rDNS resolves to your ISP.
@Kamal Nasser : thanks for clearing this up, so the suggestion up a little higher in a previous post was incorrect and there is no point of using DynDNS for the purpose of compensating for a dynamic IP from your ISP - http://www.dyncommunity.com/questions/6771/problem-with-nslookup.html Maybe I can stop wasting my time?
@cowsun.tech you still need to have your DynDNS host there so fail2ban whitelists your IP even if it’s dynamic.
On restart the message is “Restarting authentication failure monitor fail2ban” , meaning ‘Restart succeeded’ (not authentication failed).
@yangyun That is correct. It’s restarting fail2ban which is the authentication failure monitor. :]
To enable the alertmail you not only need to set the destemail, but also change the line action = %(action_)s
to either action = %(action_mw)s #(for ban & send an e-mail with whois report to the destemail) or action = %(action_mwl)s #(for ban & send an e-mail with whois report and relevant log lines to the destemail)
Can I install fail2ban after I install iRedMail ? Will it have conflic between the two ?
Tks
@germanab7: You can follow this official iRedMail entry on installing fail2ban: http://www.iredmail.org/wiki/index.php?title=Addition/Harden.iRedMail.with.Fail2ban
I’m thinking of implementing, but the whitelisting gives me a bit of pause. I do use Dyn on my laptop and on my main box which is fine, but what if i want to use SSH from my phone? Since I installed OpenVPN on my server, I guess I could also whitelist my DO IP and just make sure I am connected before trying SSH from a 3G connection. Thoughts on whether this would work or not? I don’t really feel like “experimenting” with this specific feature :) - I’d rather know before I go.
@deekin: It would certainly work. Whitelist your VPN’s public IP address and add it to fail2ban’s whitelist. Then you can login to the VPN and then SSH to your droplet.
Thank you Kamal! GJ on the techcrunch piece BTW - my pal sent it to me. Don’t spend it all on one place hehe - oh, and bring back receipts please.
Shouldn’t you sudo mv the .local file to .conf afterwards?
@deekin: No. Per the manual:
<pre>Every .conf file can be overridden with a file named .local. The .conf file is read first, then .local, with later settings overriding earlier ones. Thus, a .local file doesn’t have to include everything in the corresponding .conf file, only those settings that you wish to override.</pre>
Does fail2ban and UFW start self after a server reboot, or do I need to enable them?
Also, could I check if their both running by: sudo iptables -L sudo ufw status ?
@kevin_thulin: Both of them should start automatically. You can check if they’re running by running <pre>service ufw status service fail2ban status</pre>
Should “eg.” be included in the “eg. port=30000”? And should this be written instead of “port=ssh” or in addition to it?