Welcome to Part II of the Quick Secure Setup Series.  Be sure to check out Quick, Secure Setup Part I first, although this can be taken on its own if you’d just like to configure UFW with Fail2ban correctly.

At the end of Part I we quickly setup a basic iptables config just to get the firewall up and doing its job.  The problem with iptables, isn’t actually a problem with iptables itself, but rather the administrator running it.  Iptables is a great firewall and like any great firewall there is a lot you can configure it to do.  The more configuration options open to the user, the more complicated a piece of software can get.  What I’ve witnessed is a well intentioned user will configure and run iptables on Day 1 of their server, just as we did in Part 1, but as time moves on and they need to run more applications or find themselves with something not working just right that seems to behave fine once iptables is stopped, then iptables either gets turned off or mis-configured with larger holes than what is needed.  Unless you are a linux administrator of some sort you probably are going to learn just enough of iptables to get it running on that initial setup.  After that you don’t really touch a firewall on a day to day basis so by the time you have this new application installed that isn’t playing nice with your current iptables you don’t want to take the steep learning curve plunge to figure out the correct  configuration you would need.  Therein would lie your chink in the security chain.

Starting with UFW for the first time check the UFW Ubuntu Wiki.  The introduction on this page explains perfectly why one would want to use UFW over iptables.

The Linux kernel in Ubuntu provides a packet filtering system called netfilter, and the traditional interface for manipulating netfilter are the iptables suite of commands. iptables provide a complete firewall solution that is both highly configurable and highly flexible.

Becoming proficient in iptables takes time, and getting started with netfilter firewalling using only iptables can be a daunting task. As a result, many frontends for iptables have been created over the years, each trying to achieve a different result and targeting a different audience.

The Uncomplicated Firewall (ufw) is a frontend for iptables and is particularly well-suited for host-based firewalls. ufw provides a framework for managing netfilter, as well as a command-line interface for manipulating the firewall. ufw aims to provide an easy to use interface for people unfamiliar with firewall concepts, while at the same time simplifies complicated iptables commands to help an adminstrator who knows what he or she is doing.

You may also find useful the Ubuntu Community page on UFW.  There are helpful links at the bottom of that page to continue reading.  Some quick google searches will get you moved to UFW quite easily.  Remember you are using the same backend as iptables just using a less complicated front-end to get the rules going.  So if you flush your current iptables and put in some basic ufw rules for your ssh, apache, and in my case NTP your ufw status output could look like this:

activeTo      Action   From
--------      ------   ----
OpenSSH       LIMIT    Anywhere
Apache Full   ALLOW    Anywhere
123           ALLOW    Anywhere

Now recall we changed our OpenSSH port in Part I, so to keep UFW simple I’ve edited the openssh-server file in /etc/ufw/applications.d to reflect our custom port. For any custom ports you find yourself opening or blocking consider creating an application profile for it, it’ll be easier to read your rules and if you don’t touch them for months, easier to remember when you have to re-visit them. You can easily see your apps and their configuration with ufw app list and ufw app info OpenSSH. Once you have your basic UFW configuration in place you should install fail2ban: aptitude install fail2ban.

Fail2ban is a very simple yet very useful application that simply looks at the log files you tell it about, parses them for certain errors or failures and then inserts a firewall rule to block the IP that caused that error or failure.  Trust me when I tell you that you want this.  Every server I’ve ever put on the internet gets scanned by scripts looking for open ports, trying ssh or ftp logins, attempting urls for various mysql, php, remote access URL’s, etcetera etcetera etcetera….  Here is a small example of ports that were scanned on my server:

Service: ms-sql-s (tcp/1433) ([UFW BLOCK])
Service: ssh (tcp/22) ([UFW BLOCK])
Service: sip (udp/5060) ([UFW BLOCK])
Service: 3389 (tcp/3389) ([UFW BLOCK])
Service: 27977 (tcp/27977) ([UFW BLOCK])
Service: radmin-port (tcp/4899) ([UFW BLOCK])
Service: 5900 (tcp/5900) ([UFW BLOCK])
Service: http-alt (tcp/8080) ([UFW BLOCK])
Service: loc-srv (tcp/135) ([UFW BLOCK])
Service: mysql (tcp/3306) ([UFW BLOCK])
Service: ms-sql-m (udp/1434) ([UFW BLOCK])
Service: 49153 (udp/49153) ([UFW BLOCK])
Service: 1022 (tcp/1022) ([UFW BLOCK])
Service: socks (tcp/1080) ([UFW BLOCK])

On the web server side various URL’s for web administration are always attempted like: /phpMyAdmin, /myadmin, /mysql, etcetera. Without Fail2ban in place these scripts can run until they’ve exhausted every login attempt they want, or every URL in their list. WITH Fail2ban we can give them 3-5 attempts and then realize they are a script kiddie and ban their IP from the server for X amount of time.

Out of the box Fail2ban works with iptables rules, however these don’t play nice with our simpler UFW commands so we need to make a couple edits to have Fail2ban block the IP’s with UFW.

First lets go into /etc/fail2ban/jail.conf and change a few default ban actions for ssh and apache to use ufw actions we will create:

enabled = true
banaction = ufw-ssh
port = 2992
filter = sshd
logpath = /var/log/auth.log
maxretry = 3

enabled = true
port = http,https
banaction = ufw-apache
filter = apache-auth
logpath = /var/log/apache*/error*.log
maxretry = 4

enabled = true
port = http,https
banaction = ufw-apache
filter = apache-nohome
logpath = /var/log/apache*/error*.log
maxretry = 3

enabled = true
port = http,https
banaction = ufw-apache
filter = apache-noscript
logpath = /var/log/apache*/error*.log
maxretry = 6

enabled = true
port = http,https
banaction = ufw-apache
filter = apache-overflows
logpath = /var/log/apache*/error*.log
maxretry = 2

In this file we are enabling the sections we want fail2ban to monitor and take action on. You’ll want to make sure your logpath points to your apache error logs and take note of the filter names as each of those corresponds to a file within the filter.d directory. All the filters are simply a regular expression to pattern match some error condition in the logfile, once matched fail2ban will execute the banaction. So if you look at the apache-auth filter, it will match for any user authentication failures to your websites. The only filter I’ve modified is the apache-nohome I’ve edited to match for any file not found error, not just checking for home directory attacks as the default.
The original regex was:
failregex = [[]client []] File does not exist: .*/~.*
and my modified version for any file not found errors is:
failregex = [[]client []] File does not exist: *
BE CAREFUL if you chose to also make this change. There are many things that will cause file not found errors that may not be attacks at all. Search bots looking for robots.txt, normal users can trigger on favicon.ico if you don’t have, etc. So if you make that change check your logs frequently and fix any valid file not found errors. The reason I turned this on is the constant attempts at bogus URL’s as I mentioned above where the scripts look for web GUI admin pages.

Now we simply need to create the valid banaction files we specified in our jail.conf. First is /etc/fail2ban/action.d/ufw-ssh.conf:

actionstart =
actionstop =
actioncheck =
actionban = ufw insert 1 deny from <ip> to any app OpenSSH
actionunban = ufw delete deny from <ip> to any app OpenSSH

and /etc/fail2ban/action.d/ufw-apache.conf:

actionstart =
actionstop =
actioncheck =
actionban = ufw insert 2 deny from <ip> to any app "Apache Full"
actionunban = ufw delete deny from <ip> to any app "Apache Full"

As you may see the ufw command here is quite simple. The actionban says to deny the offending IP for the specified application. The only gotcha here is we have to specify the line the rule is being inserted into as the order matters. Our original rules allow these apps so we must ensure that any denies to these apps come BEFORE the allow rule. As rules are processed in order if we have the allow first the offender will continue to hit our server as it will never hit the deny rule. So we make sure the denies get inserted before the allow lines and all is well. The great thing about UFW rules is that you can almost read them and understand what they are doing, as opposed to the standard iptables banaction which could look like this:

actionban = iptables -I fail2ban-<name> 1 -s <ip> -j DROP
actionunban = iptables -D fail2ban-<name> -s <ip> -j DROP

As you can see UFW provides for much more readability without that learning curve hit you’d have to go through to get a good grip on the iptables rules.

If you have logwatch configured as in Part I then you’ll see the bans that took place in the logwatch email for the day prior. For example the fail2ban section in one of my logwatch emails had this:

--------------------- fail2ban-messages Begin ------------------------
Banned services with Fail2Ban:                 Bans:Unbans
apache-filenotfound:                            [ 3:3 ] (   1:1 (  1:1                                    1:1
---------------------- fail2ban-messages End -------------------------

As I mentioned earlier, for the first week with this configuration you should check your apache error log and make sure those file not found errors were scripts looking for /phpmyadmin or some other page that truly doesn’t exist and not a normal user getting file not found errors because of favicon.ico or something else.

That’s it! ufw status will show you any of the rules in effect on your system. After these first two parts are executed you’ll have a server configured securely with nothing unnecessary open to the internet, and those ports that are open now are blocking some bad guys from messing with them too much. For Quick Secure Setup Part III, the last in the series, we’ll tighten everything up even more and end up with server security that is second to none.

  56 Responses to “UFW with Fail2ban – Quick Secure Setup Part II”

  1. Great lesson/tutorial or how should I call it…

    Great style of writing, I love it!

    Hope, that part III will be out soon… ;)

    P.s.: What about forum on: … Is it under construction?

    • Indeed, Part III should hit early June.
      Yes forum is a work in progress… I’m still debating various things regarding its construction and use.
      Any suggestions for articles let me know!

  2. Looks good, I have been looking for a way to secure a server with fail2ban and UFW. This article helped out a lot! I tried denyhosts, but it kept locking me out, and I couldn’t figure out why. This seems to be an easier solution, and to unblock, just delete the firewall rule from UFW.
    Does fail2ban permanently leave those rules enabled? If not, is there a way to set this?

    • No it does not permanently leave the rules enabled and I don’t recommend doing that. It is very rare I’ll see the same IP more than 6 hours apart. You’ll notice in /etc/fail2ban/action.d where we setup the action there is an actionunban. This is what is runs to remove the rule so you don’t have to delete them from UFW yourself. Now when does it do this? That is defined in your jail in /etc/fail2ban/jail.conf. You’ll notice in the [Default] section a bantime = value. This is the bantime in seconds before the actionunban is run. You can override the default value by specifying a bantime in each section you enable. So in our [SSH] section you can add bantime = 21600 to ban them for 6 hours. I see little need to ban longer than that in most cases.

      Finally if you are testing and find you can easily lock yourself out also in the [Default] section take note of the ignoreip = line. Go to and get your IP and add it there, separate multiple IP’s you add there by spaces. Hope this helps you out.

      • Yes that helps out a lot! Thank you for this write up and your quick reply. I ended up just setting mine to ban for an hour since the server is hosting ssh on another port anyways.
        Thanks again!

  3. [...] to me and I’ve been running VSFTPD for the past 10 years.  If you supplement it with a nice fail2ban configuration and further secure it with apparmor you’ll be in incredible [...]

  4. Greetings …

    Thanks for a great blog! I have three suggests for this post.

    First, instead of editing the original install files, I would suggest putting your changes into jail.local. Settings in *.local override *.conf. So that if and when updates coming with your package management system, like apt, then your changes will get overwritten.

    Another would be to add UFW bans, if an IP does a port scan or something, with file and add a jail.

    enabled = true
    port = all
    filter = ufw-block
    #banaction = ufw-all
    banaction = sendmail-whois[name=fail2ban-ufw-block]
    #logpath = /var/log/messages
    logpath = /var/log/ufw.log

    # Fail2Ban configuration file
    # Author: C.Lee Taylor
    # Use for UFW in message
    # Matches lines such as:
    # Feb 4 08:51:06 localhost kernel: [UFW BLOCK] IN=eth0 OUT= MAC=fe:fd:b2:4f:9d:2f:88:43:e1:a3:fa:7f:08:00 SRC= DST= LEN=60 TOS=0×00 PREC=0×00 TTL=50 ID=43644 DF PROTO=TCP SPT=3412 DPT=23 WINDOW=5840 RES=0×00 SYN URGP=0
    failregex = kernel: \[UFW BLOCK\] IN=.* SRC=

    Last would be to add a fail2ban repeat offender ban, which can be found on the fail2ban homepage wiki.


    • Few qestion to the comment of LeeT:
      1 – [ufw-block] is a jail block wich can go to jail.local right ?
      2 – ufw-all line is a mistake ? in this jail block ?
      3 – tag missing from the failregex right ?

      using Fail2Ban v0.8.11

    • Hello, after reading this amazing post i am as well glad to share my familiarity here
      with friends.

    • If some one wishes expert view on the topic of blogging then i advise him/her to visit
      this webpage, Keep up the nice work.

    • Home organization is simpler when don’t have a lot of extra things in the mix.
      For instance, they are help in answering your phone call and
      help in diverting back your mails and other
      stuff. A clean home leads to a clean mind, so follow these tips for a new approach to home organization.

  5. Good tutorial, but I would add this at the end

    service fail2ban restart

    And there is not apache-filenotfound in ubuntu 10.04

  6. I also noticed that when I restart fail2ban, the ufw rules added by fail2ban are deleted…

    Should it be like that?

  7. This part does not seem to work for me

    actionstart =
    actionstop =
    actioncheck =
    actionban = ufw insert 2 deny from to any app "Apache Full"
    actionunban = ufw delete deny from to any app "Apache Full"

    Can it be changed by changing the 2 by 1 without affecting the setup? Why are you using 2?

    actionstart =
    actionstop =
    actioncheck =
    actionban = ufw insert 1 deny from to any app "Apache Full"
    actionunban = ufw delete deny from to any app "Apache Full"

  8. I know why, it is because I had my ufw status like that

    root@plato:/etc/ufw/applications.d# ufw status
    Status: active

    To Action From
    – —— —-
    80 ALLOW Anywhere
    22 LIMIT Anywhere

    So the first rule was allow port 80…

  9. Woh I like your articles , saved to bookmarks ! .

  10. Hi,

    Cant get it to work in 12.04. Is there something I miss ??? I dont quite understand :
    actionban = iptables -I fail2ban- 1 -s -j DROP
    actionunban = iptables -D fail2ban- -s -j DROP

    Are those lines in /etc/fail2ban/action.d should be changed???

  11. Hmm.. maybe Im wrong… is this has to do something with password authentication?
    I am trying to login into my ssh via putty and doing it 6 times it doesnt block the ip. Should it be so?

  12. My coder is trying to convince me to move to .net from PHP.

    I have always disliked the idea because of the expenses. But he’s tryiong none the less. I’ve been using WordPress
    on a variety of websites for about a year and am anxious about switching
    to another platform. I have heard excellent things about blogengine.
    net. Is there a way I can transfer all my wordpress
    posts into it? Any kind of help would be greatly appreciated!

  13. Unquestionably believe that which you said. Your favorite reason appeared to be on the internet
    the easiest thing to be aware of. I say to you, I definitely get annoyed while people consider worries that they plainly don’t know about. You managed to hit the nail upon the top as well as defined out the whole thing without having side-effects , people can take a signal. Will probably be back to get more. Thanks

    my blog – zastaw na nieruchomości

  14. For hottest news you have to go to see world-wide-web
    and on the web I found this site as a most excellent site for most up-to-date updates.

    Thank you for currently taking a time period to evaluation my profile.
    You are welcome to take a look at my very own
    website also for extra facts and beneficial ideas; remanufactured ink cartridge

  15. 88888 We are undecided if they are sufficient to prevent a pedicab driver, but we haven’t still positioned so much of our self esteem inside their arms.. Using the net TutorialsLet’s facial area it, some of us please don’t provide the time or finances to make use of hair dressers, louis vuitton quilted handbags makeup artists and stylists on even an occasional basis.
    Cheap Louis Vuitton Bags Online Outlet

  16. 88888 We’re unsure if they are a sufficient amount of to prevent a pedicab driver, but we have not still put a great deal of our self esteem inside their fingers.. On the internet TutorialsLet’s deal with it, a great number of of us do not have the time or bucks to utilise hair dressers, louis vuitton garment bag luggage makeup artists and stylists on even an occasional basis.
    Cheap Louis Vuitton Bags Online Outlet

  17. 88888 We’re not sure if they’re sufficient to stop a pedicab driver, but we’ve not however put a lot of our self esteem within their arms.. On-line TutorialsLet’s face it, a great many of us please don’t provide the time or dough to try hair dressers, artsy gm louis vuitton bagshop louis vuitton belts makeup artists and stylists on even an occasional foundation.
    Christian Louboutin Sandals

  18. 88888 We’re unsure when they are adequate to prevent a pedicab driver, but we have not however positioned so much of our self-worth in their hands.. By going online TutorialsLet’s confront it, a good number of of us you shouldn’t have the time or bucks to implement hair dressers, white louis vuitton boat shoes makeup artists and stylists on even an occasional foundation.
    Cheap Louis Vuitton Bags Sale

  19. 88888 We’re undecided if they are ample to prevent a pedicab driver, but we’ve not still put a lot of our self esteem in their arms.. On line TutorialsLet’s face it, a great many of us really don’t have the time or income to apply hair dressers, louis vuitton document holder makeup artists and stylists on even an occasional basis.
    nike free run shoes women sale

  20. 9999 On this earth model, each and every product has develop into extravagant. In the meantime, he is also doing the job with all the sweatshop, louis vuitton belt replica run by Chinese bosses, authentic discount louis vuitton that manufacture the counterfeit goods for his profits pressure.
    cheap bears jerseys

  21. 9999 On this earth create, every last item has change into extravagant. Meanwhile, he is also operating with the sweatshop, louis vuitton second hand operate by Chinese bosses, lv clutch that manufacture the counterfeit items for his sales and profits force.
    christian louboutin clearance online

  22. I do not even understand how I finished up here, but I thought this publish was good. I do not recognize who you might be but definitely you’re going to a well-known blogger if you happen to aren’t already. Cheers!|

  23. Hai, looks nice, but a question.

    Why didn’t you put fail2ban with the CHAIN parameter the correct UFW CHAIN.

  24. thank you for this tutorial, it’s very interesting.

    I’m just wondering if somebody can help me with my configuration:
    I’m trying to avoid bruteforce attack on my owncloud installation; the problem is that my owncloud server is behind another web proxy, so whenever the log register an

    {“app”:”core”,”message”:”Login failed: user ‘root’ , wrong password, IP:″,”level”:2,”time”:”2014-05-13T11:06:49+00:00″}

    it will register ALWAYS the ip of the internal web proxy.

    How can I avoid to ban my own proxy server? Is it possible?

    thank you

  25. Several lines are the exact maximum to get a you sentence or two. As you speak you create number because of volume, strengthen, inflection together with actions. As you produce you need to do it simply by underlining, italicizing, Making money together with producing strong. Thinking about all run idea undoubtedly would have excited Carson’s offensive range, doubts it all got best-known. I didn’t show from any of the individuals earlier,” Private coach Elijah Asante explained. “It was just a case of planning to work on somethings and extremely give attention to each of our working video game.

  26. >> would do anything for you, whether you were definitely one spanning the or possibly a person who already experienced sums of money and easily vital your larg. This individual merely astonishing. Not to mention admiration is a huge element in my situation. Consider operate styles utilizing people lounging around you, which will create a feeling of comprehending. Along, you can produce a work environment that is good for just anyone. As an example, you could commit to build a transmission to say those occasions if somebody wants quiet to pay attention..

  27. A number of people that happen to be solely with Thanksgiving. The always striving overall economy, the requirement is a plus. Cherry Path Pursuit Ministries solely expects serving more than 5 various,1000 dishes with Thanksgiving, depending the actual Six-hundred dishes it’ll residence offer, the actual 900 food stuff packing containers it’ll distributed, and then the a lot of dishes it’ll truly a goal company, reported spokesperson Ashley Shaffer..

  28. 29) V. Commentary, ivi, p. 237.

  29. You’re so interesting! I do not believe I’ve truly read through a single thing like this before. So wonderful to discover somebody with genuine thoughts on this issue. Seriously.. thanks for starting this up. This site is something that’s needed on the web, someone with a bit of originality!

  30. Fastidious answers in return of this query with firm arguments and telling all regarding that.

  31. En cuanto al tipo que operan dentro del aire hacia arriba abierta, lo que necesitan es mucho más robustez y el calor, por lo tanto el Moncler concentrarse mucho en esta pasantía. Pero MONCLER chaquetas para su

  32. Getting inside from suppliers artist LV and also Gucci handbags, it is possible to have a very bag which usually makes it possible to bring the basics any way you like. They will seem simply refreshing and also female sufficient reason for their particular sophisticated information and also look body-friendly sense offer you a extremely attractive seem. Together with large rooms and also superior seems, they may be extremely high-class and also hassle-free. These kinds of handbags certainly are a amazing solution to bring the requirements.

  33. Though have to it be Little? frankly, make a large aluminum bookshelf can be a safe. Allow it to be take a look tasteful not to mention creative, might be deliver people today various capacity to customize it is actually looks, nevertheless at some point deliver people today to be able to get a new system and find the condition of productiveness they really want. Apple, you will have completed isn’t just elements, as well as some issues that I cannot specifically prefer.

    • I drop a leave a response whenever I especially enjoy a post on a website or I have something to add to the conversation. Usually it is caused by the passion communicated
      in the post I read. And on this post UFW with Fail2ban – Quick Secure Setup Part II » VigilCode Blog.
      I was moved enough to drop a thought ;) I do have a few questions for you if
      you do not mind. Is it simply me or does it seem like a
      few of these remarks look as if they are left by brain dead individuals?
      :-P And, if you are posting on additional online social sites,
      I’d like to keep up with everything fresh you have to post.
      Would you make a list every one of all your public pages
      like your linkedin profile, Facebook page or twitter feed?

  34. Buy Quality SunglassesUVA not to mention UVB uv rays can be harming in the little brown eyes. A lot of exposure adds to the danger of cataracts after some time. The intense light moreover enables you to scrunch up your eyes, which can create facial lines near the eyes. An important element of active habits is useful prioritization. Excellent leaders method together with get the capacity in setting first off, and also showing priority for. People stop the attraction with working functions on their to do list in accordance with the region on the deadline day, instead sort to carry out email lists while using incredible importance of the position..

  35. Entrepreneurs Suggestions for SuccessThis content string includes numerous browsing materials that can help you are aware of that you do not must have a P The school level so it will be major. Any collection insures number of enterprisers which lasted major devoid of classy business enterprise methods. What’s more, it insures this North american Wish as well as permits readily available identical..

  36. I carry my wow gold when ever before situation allows. I love them given that they are nice.

  37. My spouse and i certainly would like some sort of MacBook Air for $999 when compared with the ipad tablet 64GB with regard to $699
    new nike free

  38. I blog quite often and I really appreciate your content.
    The article has truly peaked my interest. I will take a note of your blog and keep checking
    for new details about once a week. I opted in for your
    Feed as well.

    My page: buy spanish fly

  39. I’ve been exploring for a little for any high quality articles
    or blog posts in this kind of space . Exploring in Yahoo
    I ultimately stumbled upon this website. Reading
    this info So i am satisfied to exhibit that I’ve a very just right uncanny feeling I came upon exactly what I needed.

    I so much unquestionably will make certain to do not disregard this
    site and give it a glance regularly.

  40. It was hard to find your website in google.
    I found it on 12 position, you have to build a lot of
    quality backlinks , it will help you to increase traffic.
    I know how to help you, just type in google – k2 seo tips

  41. Carry out the following to discover more on babyliss well before you’re left out.
    cheaper arsenal #4 mertesacker red soccer club jersey online

  42. UFW with Fail2ban – Quick Secure Setup Part II » VigilCode Blog womens ugg

  43. A fascinating discussion is definitely worth comment.
    I do think that you ought to write more about this issue, it might not be a taboo subject but generally people don’t discuss these topics.
    To the next! All the best!!

  44. Very good post. I absolutely appreciate this website. Thanks!

  45. Quality articles or reviews is the secret to be
    a focus for the visitors to visit the web site, that’s what this web page is

  46. UFW with Fail2ban – Quick Secure Setup Part II » VigilCode Blog
    Burberry Long Sleeve Tee T-Shirt

 Leave a Reply



You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

© 2011 VigilCode Suffusion theme by Sayontan Sinha