Showing posts with label fail2ban. Show all posts
Showing posts with label fail2ban. Show all posts

Wednesday, May 16, 2012

Protecting WordPress from script fishing attacks with Fail2Ban

SkyHi @ Wednesday, May 16, 2012

I posted some previous ideas on this that were okay, but they turned out to be less-than-idea solutions. They work, but one of the blogs I watch over is a bit busy, and having Fail2Ban watching the Apache access.log was putting excessive load on the CPU.
So here’s a nicer approach, but it needs a bit more fiddling:
As /etc/fail2ban/filters.d/apache-phpmyadmin.conf
[Definition]
failregex =  [[]client []] (File does not exist|script ').*(phpMyAdmin|phpmyadmin|dbadmin|mysql|myadmin|w00t|muieblackcat|mysqladmin).*
ignoreregex =
As /etc/fail2ban/filters.d/apache-wp-login.conf
[Definition]
failregex =  [[]client []] WP login failed.*
ignoreregex =
As /etc/fail2ban/filters.d/apache-wp-timthumb.conf
[Definition]
failregex =  [[]client []] (File does not exist|script ').*(timthumb\.php).*
ignoreregex =
The relevant sections of /etc/fail2ban/jail.local should be something like these. This allows a few failed logins, but only one attempt to hit a phpMyAdmin directory or the TimThumb exploit. But maxretry and findtime can be whatever you want.
[apache-wp-login]
enabled = true
port    = http,https
filter  = apache-wp-login
logpath = /var/log/apache*/*error.log
maxretry = 3
findtime = 120

[apache-phpmyadmin]
action = %(action_mwl)s
enabled = true
port    = http,https
filter  = apache-phpmyadmin
logpath = /var/log/apache*/*error.log
maxretry = 1
findtime = 60

[apache-wp-timthumb]
action = %(action_mwl)s
enabled = true
port    = http,https
filter  = apache-wp-timthumb
logpath = /var/log/apache*/*error.log
maxretry = 1
findtime = 60
So now all of the jails are watching error.log, which hopefully gets significantly less traffic than access.log. But we need to make sure WordPress logs the information we need.
If pretty permalinks is turned on, WP handles 404s and does not output to a log. Add a 404.php to the active theme that looks like this, or if there is already one, just add the error_log line:


And add this to the functions.php in your theme too, to handle the login attempts:
 // Log login errors to Apache error log
 add_action('wp_login_failed', 'log_wp_login_fail'); // hook failed login

 function log_wp_login_fail($username) {
  error_log("WP login failed for username: $username");
 }
Restart Fail2Ban server to pickup the changes, start some logging, and do some testing.
sudo service fail2ban restart
tail -n 100 -f /var/log/fail2ban.log








REFERENCES
http://blog.somsip.com/2012/02/using-fail2ban-to-protect-wordpress/
http://blog.somsip.com/2012/01/protecting-wordpress-from-script-fishing-attacks-with-fail2ban-more/
http://blog.somsip.com/2011/12/protecting-wordpress-from-script-fishing-attacks-with-fail2ban/

Monday, September 26, 2011

Firewalling SSH brute force attacks with connection throttling

SkyHi @ Monday, September 26, 2011
Anyone who runs their own Linux server knows the annoyance of looking through the log files to see automated SSH brute force attacks trying to find a login to the machine. In the past, I’ve avoided this problem simply by running sshd on a non-traditional port, which makes all the automated scripts that attack port 22 fail.

I recently had to move sshd back to port 22, and I quickly tired of seeing 5k failed login attempts every day.

UPDATE: After some Googling, and after taking into account a lot of good advice from the comments, as well as from John and Smooge, here’s how I’ve rewritten my firewall to protect against brute force ssh attacks.

# set default policies
iptables -P INPUT DROP

# all pre-established clients
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

# new inbound ssh, protecting against brute-force attacks
iptables -A INPUT -p tcp -m tcp --dport 22 -m state --state NEW -m recent --set --name SSH
iptables -A INPUT -p tcp -m tcp --dport 22 -m state --state NEW -m recent --update --seconds 60 --hitcount 4 --rttl --name SSH -j DROP
iptables -A INPUT -p tcp -m tcp --dport 22 -m state --state NEW -j ACCEPT


The changes improve efficiency by moving all the RELATED and ESTABLISHED filtering to the beginning of the checks. Also, the order of the checks on the NEW ssh connections have been fixed based on the suggestions in the comments.

The blocked IPs are stored in /proc/net/ipt_recent/SSH.


This technique, known as “connection throttling”, can be applied to any service (web, mail, etc.) you wish to protect against DoS (and might also help in case of DDoS)

REFERENCES
http://spevack.wordpress.com/2011/09/21/firewalling-ssh-brute-force-attacks/

Thursday, August 11, 2011

Rate limiting login attempts with iptables

SkyHi @ Thursday, August 11, 2011
Rate limiting login attempts is an easy way to prevent some of the high speed password guessing attacks. However, it's hard to limit distributed attacks and many run at a low pace over weeks or months. I personally prefer to avoid using automated response tools like fail2ban. And this is for two reasons:

Legitimate users sometimes forget their passwords. I don't want to ban legitimate users from my server, forcing me to manually enable their accounts again (or worse, try to figure out which of the 100/1000 banned IP addresses is theirs).
An IP address is not a good identifier for a user. If you have multiple users behind a single IP (for example, a school that runs NAT on 500 student machines) a single user making a few bad guesses can land you in a world of pain. At the same time the majority of the password guessing attempts I see are distributed.

Therefore I don't consider fail2ban (and similar automated response tools) a very good approach to securing a server against brute force attacks. A simple IPTables rules set to cut down on the log spam (which I have on most of my linux servers) is something like this:

iptables -I INPUT -p tcp --dport 22 -i eth0 -m state --state NEW -m recent --set
iptables -I INPUT -p tcp --dport 22 -i eth0 -m state --state NEW -m recent --update --seconds 60 --hitcount 4 -j DROP


It prevents more than 4 connection attempts from a single IP to ssh in any 60 second period. The rest can be handled by ensuring passwords are reasonably strong. On high security servers forcing the users to use public key authentication is another way to stop guessing.

REFERENCES
http://serverfault.com/questions/216995/is-it-worth-the-effort-to-block-failed-login-attempts

Tuesday, June 21, 2011

Install fail2ban 0.84 on Centos 5.5

SkyHi @ Tuesday, June 21, 2011
Fail2ban is an intrusion prevention framework which scans the log files on your system (such as: var/log/secure) and spots repeated password failures.
Too many failures, and it will update your firewall to drop all traffic from the offending IP address. Pretty handy, and enough to stop the casual hacker with a dictionary attack.
Fail2ban is very flexible and can be configured to work with any service that writes to a logfile, but here’s the basics to get you up and protected in a few minutes.
1. Get the files
cd to /tmp for a nice place for them to land, then
wget http://sourceforge.net/projects/fail2ban/files/fail2ban-stable/fail2ban-0.8.4/fail2ban-0.8.4.tar.bz2/download

2. Extract them
tar -xf fail2ban-0.8.4.tar.bz2

3. Head to the new directory and install
cd fail2ban-0.8.4
then (you need to have python installed)…
python setup.py install
All installed ok?

4. Get it starting up automatically
cp files/redhat-initd /etc/init.d/fail2ban
chkconfig --add fail2ban
chkconfig fail2ban on

5. Config
You’ll need to turn some stuff on, and fiddle with settings to your liking in:
/etc/fail2ban/jail.conf
If you’re enabling SSH-iptables, then the path for SSH monitoring needs to be changed to /var/log/secure
You can determine the services being monitored, number of retries a user is allowed, as well as the ban time in this settings file.
Once you’re configured, start the service with:
service fail2ban start

6.
You can test the rules per service using:
fail2ban-regex /var/log/secure /etc/fail2ban/filter.d/sshd.conf
The defaults should work correctly for SSH but if they don't, check out this article for more options.


NOTE:  fail2Ban 0.8.4 doesn't ban VSFTPD failures
Once I realized that fail2ban was configured to ignore failed logins from my LAN IP's, I did manage to get banned. The following settings worked for me:

/etc/vsftpd/vsftpd.conf:
Code:
dual_log_enable=YES
use_localtime=YES

/etc/fail2ban/jail.conf:
Code:
[vsftpd-iptables]
enabled  = true
filter   = vsftpd
action   = iptables[name=VSFTPD, port=ftp, protocol=tcp]
           sendmail-whois[name=VSFTPD, dest=root@localhost, sender=fail2ban@pbx.dyndns.org]
logpath  = /var/log/vsftpd.log
maxretry = 3
bantime  = 1800

I left default settings for IP tables and for /etc/fail2ban/filter.d/vsftpd.conf



REFERENCES
http://www.md3v.com/install-fail2ban-on-centos-5-5
http://willgrant.org/install-fail2ban-on-centos-5-6/
http://pbxinaflash.com/forum/showthread.php?t=9847

Tuesday, June 15, 2010

How-to: Install fail2ban 0.8.4 in CentOS

SkyHi @ Tuesday, June 15, 2010
Hello all:



This is a collection of oddities and installation issues with fail2ban 0.8.4. I originally used a CentOS Optimized version that I had to remove the fail2ban that came with it initially because it appear to be a Debian version. In any event, I believe the tips apply.



Here are some of the instructions I followed for basic installation and configuration:



http://felipeferreira.net/?p=47

http://www.fail2ban.org/wiki/index.p...2FLinux_system



Here is the list of issues I found:

  1. Python Version: CentOs comes with a few versions of python. 2.4 and the standard one. If you get a SyntaxError: invalid syntax "bad interpreter" error warning upon restarting and shutting down fail2ban manually check the path in the fail2ban-client and fail2ban-server inside /usr/bin/folder. Do a whereis for python and adjust the path (very beginning of the file) accordingly.



    In my case I had to pointed to the 2.4. The reasons why are mystery to me...




    Quote:







    fail2ban-client -h

    File "/usr/bin/fail2ban-client", line 360

    @staticmethod

    ^

    SyntaxError: invalid syntax



    I found a way to work around this problem with CentOS. Apparently CentOS has multiple versions of Python installed. Modify /usr/bin/fail2ban-client and /usr/bin/fail2ban-server so that the first line on each reads as follows:



    #!/usr/local/bin/python2. <----(make sure YOUR path is the right one)

    (or wherever the direct executable for python2.4 is). By default it reads as #!/usr/bin/python, which is apparently an earlier version of python. If you don't know where python2.4 is located, you can find it by typing the following:

    whereis python2


    I also picked up reports python 2.6 may not work with fail2ban. So you know.


  2. Missing Filters or Action: Your jail.conf file (or jail.local if you duplicate) should have already "-iptables" entries in it. (example: [ssh-iptables]). if it does not then you installed the wrong version of fail2ban or it did not compile properly.



    Check also the /etc/fail2ban/filters.d as the filters referred in the jail.conf should be here. If not, same as before: wrong fail2ban server installation or an older version of it.


  3. Make sure that in the jail.conf (or jail.local if you duplicate) path to the check log is correct: In CentOS there is no auth.log: Use /var/log/secure instead. if you do not the system fails to extract the failed logins and nothing happens.


  4. Run the fail2ban-regex to check the /var/log/secure log against the filter: You should get matches as defined by the regular expressions in each filter and when done you should get matches like so (this is a brand new server...I only have 3 matches):



    In this example I am checking SSH:




    Code:

    fail2ban-regex /var/log/secure /etc/fail2ban/filter.d/sshd.conf

    and being




    Code:

    Failregex<br />|- Regular expressions:<br />|  [1] (?:error: PAM: )?Authentication failure for .* from <HOST>\s*$<br />|  [2] Failed [-/\w]+ for .* from <HOST>(?: port \d*)?(?: ssh\d*)?\s*$<br />|  [3] ROOT LOGIN REFUSED.* FROM <HOST>\s*$<br />|  [4] [iI](?:llegal|nvalid) user .* from <HOST>\s*$<br />|  [5] Invalid user .* from <HOST>\s*$<br />|  [6] User .+ from <HOST> not allowed because not listed in AllowUsers\s*$<br />|  [7] User .+ from <HOST> not allowed because none of user's groups are listed in AllowGroups\s*$<br />|  [8] Address <HOST> .* POSSIBLE BREAK-IN ATTEMPT\s*$<br />|  [9] authentication failure; logname=\S* uid=\S* euid=\S* tty=\S* ruser=\S* rhost=<HOST>(?:\s+user=.*)?\s*$<br />|<br />`- Number of matches:<br />   [1] 0 match(es)<br />   [2] 0 match(es)<br />   [3] 0 match(es)<br />   [4] 0 match(es)<br />   [5] 0 match(es)<br />   [6] 0 match(es)<br />   [7] 0 match(es)<br />   [8] 0 match(es)<br /><b><font color="Red">   [9] 3 match(es)<br /></font></b>

    However, if you get a "Sorry, no matches" result and everything else has been properly configured, then it is the problem us the regular expressions on the target filter configuration against is being compared. Following the SSH example above, that would be the /etc/fail2ban/filter.d/sshd.conf file.



    EDIT: Makes sure you actually have real rejections to get a match. That is, if you have just installed the server and not tried to manually trigger a ban then obviously there would be no matches as there is nothing to match to. Generate a ban on your own IP



    TIP: Temporarily change the ban duration time to something short like 15 to 30 seconds BEFORE you do this otherwise you may lock yourself out. If you do....use the console (ouch) FLUSH the iptables to get back in....easy



    Depending on your server these expressions will need to be tweaked. The ones that came out of the box did not work for me. Luckily I found one set for CentOS that did work for me and that I paste below. Again, for SSH only, but you can use it as base for the rest. DO CHECK though:




    Code:

    failregex = (?:error: PAM: )?Authentication failure for .* from <HOST>\s*$<br />            Failed [-/\w]+ for .* from <HOST>(?: port \d*)?(?: ssh\d*)?\s*$<br />            ROOT LOGIN REFUSED.* FROM <HOST>\s*$<br />            [iI](?:llegal|nvalid) user .* from <HOST>\s*$<br />            Invalid user .* from <HOST>\s*$<br />            User .+ from <HOST> not allowed because not listed in AllowUsers\s*$<br />            User .+ from <HOST> not allowed because none of user's groups are listed in AllowGroups\s*$<br />            Address <HOST> .* POSSIBLE BREAK-IN ATTEMPT\s*$<br />            authentication failure; logname=\S* uid=\S* euid=\S* tty=\S* ruser=\S* rhost=<HOST>(?:\s+user=.*)?\s*$

    Make sure you restart the fail2ban server after all these changes:






    Code:

    service fail2ban restart


REFERENCES
http://www.vps.net/forum/public-forums/tutorials-and-how-tos/1481-how-to-install-fail2ban-0-8-4-in-centos

Friday, April 23, 2010

fail2ban block failed login attempts

SkyHi @ Friday, April 23, 2010

Category:Configuration



From Fail2ban



Jump to: navigation, search

The subcategories below contain information about external software and their relation to Fail2ban. In particular, logging outputs and corresponding regular expressions are proposed and discussed in these pages. Feel free to contribute.

To add an application edit the URL to contain http://www.fail2ban.org/wiki/index.php/MyProgramName. Create a new page with the format:


MyProgramName is a program that does....

{{Logging_Outputs}}

MyProgramNamve version X.XX.XX.Y
<div style="padding: 1em;border: 1px dashed #2f6fab;color: black;background-color: #f9f9f9;line-height: 1.1em;">
* LogEntry
</div>

{{Failregex}}

<pre>
failregex =
< /pre>

[[Category:MyProgramCategory]]

MyProgramCategory can be a new category or an existing listed below. If you create a new category edit and add
[[Category:Configuration]]
to the bottom of it so it gets liked here.





Subcategories


This category has the following 7 subcategories, out of 7 total.




F



H




K



M




S



V



REFERENCE
http://www.fail2ban.org/wiki/index.php/Category:Configuration

Wednesday, August 19, 2009

fail2ban – Block w00t.w00t Scanners

SkyHi @ Wednesday, August 19, 2009
HowFlow — here i explain my solution to ban a host that scans my system with dfind/w00tw00t. this solution requires a preinstalled fail2ban.

Share it! Posted by Avatar idl0r about 1 year ago
View Profile

Add to: submit 'block w00tw00t scan-hosts with fail2ban' to del.icio.us submit 'block w00tw00t scan-hosts with fail2ban' to digg

NOTE: since fail2ban >=0.8.1 there is allready a the action file ’/etc/fail2ban/action.d/iptables-allports.conf’.
if you use a version >=0.8.1 you can skip point 1 and 2 and continue with 3.

You must create two new files in /etc/fail2ban.

1. create /etc/fail2ban/action.d/iptables-allports.conf

2. insert the text below



# Fail2Ban configuration file
#
# Author: Cyril Jaquier
# Modified: Yaroslav O. Halchenko
# made active on all ports from original iptables.conf
#
# $Revision: 658 $
#

[Definition]

# Option: actionstart
# Notes.: command executed once at the start of Fail2Ban.
# Values: CMD
#
actionstart = iptables -N fail2ban-
iptables -A fail2ban- -j RETURN
iptables -I INPUT -p -j fail2ban-

# Option: actionstop
# Notes.: command executed once at the end of Fail2Ban
# Values: CMD
#
actionstop = iptables -D INPUT -p -j fail2ban-
iptables -F fail2ban-
iptables -X fail2ban-

# Option: actioncheck
# Notes.: command executed once before each actionban command
# Values: CMD
#
actioncheck = iptables -n -L INPUT | grep -q fail2ban-

# Option: actionban
# Notes.: command executed when banning an IP. Take care that the
# command is executed with Fail2Ban user rights.
# Tags: IP address
# number of failures
#