# Stopping bruteforcing

## fisk

I've got TONS of:

```
<date> <time> <hostname> sshd[29605]: Failed password for invalid user <random username> from <unknown IP-address> port 43103 ssh2 

<date> <time> <hostname>  sshd[29607]: Invalid user <same random username> from <same unknown IP-address>

```

in my /var/log/messages

---

Is there any way to block that IP-address after ie. a certain amount of those within a certain time?

----------

## Roguelazer

Make a shell script that cron runs which parses the log file and bans repeat offenders? If you give me a few minutes, I'll come up with something in Ruby, but awk would probably be faster...

----------

## Shadus

 *fisk wrote:*   

> I've got TONS of:...<SNIP>...Is there any way to block that IP-address after ie. a certain amount of those within a certain time?

 

I personally like running ssh on a different port... say port 16.  Then have portsentry watch port 22 and anyone who connects to it that isn't one of a few ip addresses I might come from gets their route dropped.

Alternately, it wont stop in progress attacks for the most part but cron an hourly job to parse your logs out and maintain a list of ip addresses that connect and fail more than say... 10 times in 24h and drop their route. 

Could only accept connections from specific locations or specify a shared key to use.. bout the only solutions.

You'll get scanned alot, keep your passwords rotated fairly frequently, use good passwords (alphanumeric, non-alphanumeric, and nothing that has any disernable link to you or the host) and it's really not a big deal.

Brute forcing a "strong" password isn't feasible. Mix of upper/lower/numeric chars, plus non-alphanumeric chars, length >10, non-personal, non-dictionary...

edit: remeber to white list important addresses from being dropped if you do the repeat offender thing... this is an old redhat script i wrote to do this... it's not the best way to do it by a long stetch, this may not even work on gentoo... but with some tweaking it shouldn't have much problem.

```

#!/bin/bash

#        Name: sshdbl.sh

#      Author: Ralph O. Weaver

#    Function: Blacklist people who portscan

# Description:

# Script to auto route to bit bucket anyone who

# tries to brute force the ssh daemon.

#

# Obviously this isn't the best methodology, but

# it prevents reoccurances from the same ip addresses.

#

# Should probally do something to force ssh to only

# accept addresses we specify or perhaps you need to

# open a seperate port on the machine first before you

# can open the sshd.

#

#        Date: Description

#  --|--|----: ---------------------------------------------

#  07/11/2003: Initital write of script.

#  --|--|----: ---------------------------------------------

#

# Program Locations

SED=/bin/sed

CUT=/bin/cut

ROUTE=/sbin/route

ECHO=/bin/echo

GREP=/bin/grep

SORT=/bin/sort

UNIQ=/usr/bin/uniq

IFCONFIG=/sbin/ifconfig

TOUCH=/bin/touch

CAT=/bin/cat

RM=/bin/rm

# Default Host Information

ETH=eth2

IPBLACKLIST=/etc/ip.blacklist

IPBLACKLISTNEW=${IPBLACKLIST}.new

LOGFILE=/var/log/messages

# Default Command Lines

MYIPADDR=`$IFCONFIG $ETH | $GREP "inet addr" | $CUT -f2 -d: | $CUT -f1 -d" "`

# Program Mainline

# touch used files incase they don't exist

$TOUCH $IPBLACKLIST $IPBLACKLISTNEW

# generate a list of ip's and send it to the new blacklisted ips

$CAT $LOGFILE | $GREP -i illegal | $GREP -i sshd | $GREP -v input | $SED 's/  / /g' | $CUT -f13 -d' ' | $SORT -n | $UNIQ >

 $IPBLACKLISTNEW

# cat both lists, sort em, uniq em and regen the blacklist with the new ips

$CAT $IPBLACKLISTNEW $IPBLACKLIST | $SORT -n | $UNIQ > $IPBLACKLIST

# remove the new list since it's no longer...well, new

$RM -f $IPBLACKLISTNEW

# generate a list of ip addresses based on the blacklist

IPS=`$CAT $IPBLACKLIST | $GREP -v $MYIPADDR | $GREP -v 192.168. | $GREP -v 127.0.0.1 | $GREP -v 10.`

# Loop thorugh list of ips in blacklist

for IP in $IPS; do

  # Check to see if the ip is currently blacklisted

  CURBL=`$ROUTE -n | $GREP -i 255.255.255.255 | $CUT -f1 -d" " | $GREP $IP`

  if [ "$CURBL" == "" ]; then

    # Route wasn't blacklisted so-- route it to the bit bucket.

    ROUTECMD="$ROUTE add -host $IP reject"

    $ROUTECMD

  fi

done

```

Edit2: I think at the "height" of my servers use of this script it had 340 addresses it maintained in ip.blacklist... and it eventually cut the scanning down to about 1-2 hosts a week.

----------

## fisk

Hmm... can't I instead do something like this:

(I don't really know bash_scripts, I just took a few lines out of a firewall_script I run)

I take the ip.blacklist generated by ie. awk from the /var/log/messages and somehow:

```

BAD_IP="/etc/ip.blacklist"

for NET in $BAD_IP

  do

  if [ $LOG != "no" ]

          then

          $IPTABLES -A INPUT -s $NET -m limit --limit $LOG -j LOG --log-level $LOGLVL

          $IPTABLES -A FORWARD -s $NET -m limit --limit $LOG -j LOG --log-level $LOGLVL

  fi

  $IPTABLES -A INPUT -s $NET -j $DROP

  $IPTABLES -A FORWARD -s $NET -j $DROP

```

Would this be simpler?

----------

## Roguelazer

I just finished writing a ruby script that uses iptables and maintains a state list and can be run as a cron job. It also automatically removes blocked users after a set delay (30 days by default, but you can set it to 300 years if it so suits you), and does all sorts of other neat stuff. However, I'd like some people to test it privately before I post it to all the world. If you're interested, private message me here or e-mail me at Roguelazer.gmail@com (yes, fix the punctuation).

----------

## jamapii

I have a lot of these log entries, too, but I'm not aware of any bruteforce attack. They never try more than 1 or 2 passwords per user, they try about 10 for root which probably rarely has ssh access.

The simplest way to counter more serious attacks would be to disable password authentication.

The defense of blocking IPs after a few failed attempts can be abused for a DOS attack.

"wc -l /usr/share/dict/words" says "234937" for me, and a single try uses 5-6 seconds, this makes 13.5 days for a complete dictionary attack - per user.

Blocking IPs after 1000 failed attempts makes a DOS attack take more than an hour per IP, and would't hit for the current attempts to find "guest" accounts. If they really try a bruteforce attack, and use a new IP for each try, they can save IP addresses this way, so you might want to calculate a good treshold from possible scenarios... Just using strong passwords will enhance your security in any case.

----------

## Shadus

 *fisk wrote:*   

> Hmm... can't I instead do something like ...<SNIP>... simpler?

 

There are alot easier and more correct ways to do it... I did that a few years ago while i was tender and green, since I've done several things that have shown to be much more effective (moving port, requiring a key, port knocking, etc).

Easiest solution is to just deny all attempted connects except from specific addresses.

----------

## m.b.j.

Currendly all this scripts do scanning over the logfiles, maybe the opensshd provides the ability to run scripts for evry n failed login?

If not it would be a nice feature request...

----------

## bigfunkymo

making a script that automagically bans ip addresses based on brute force attempts opens you up to the easiest denial of service attack ever.  All someone has to do is spoof the source IP address to something like google.com and launch an attack that would appear to be a brute force attempt.  Your script picks that up and bans google's IP and now you can no longer connect to google from that machine.

such a script or feature is a *VERY BAD IDEA*

configuring ssh to only allow certian users to connect and denying password-based authentication all together in favor of public key authentication are much better ideas.

----------

## fisk

Is there some simple way to let ie. IPTABLES to DROP a certain IP for an amount of time then? That way if the source-IP indeed is spoofed, you could just ban it for ... let's say 20 minutes, and then open it again...

so sort of like this:

1. User runs dictionary bruteforcing

2. After 5 failed attempts, the IP is temporarily banned 

3. 20 minutes later the ban is removed

---

This would make it basically a lifetime effort to bruteforce a host.

----------

## bigfunkymo

not allowing passwords in the first place defeats 100% of brute force attempts  :Wink: 

----------

## fisk

Yes, I hear the words, but I understand Jack and Sh** ... and Jack just left town.

How do I go about and configure that?

Also, does this still allow me to remotely connect from ie. servers at my school?

----------

## _dA_CyANIDe

Hi man,

i'm using this IPTABLES rules for SSH. You can try it too.

echo -n "Setting SSH security"

$IPTABLES -N SSH-HACKER

$IPTABLES -A SSH-HACKER -m recent --name badSSH --set -j LOG \

		--log-level DEBUG --log-prefix "hacker SSH user :>"

$IPTABLES -A SSH-HACKER -j REJECT

$IPTABLES -N SSH

$IPTABLES -A SSH -p tcp ! --syn -m state --state ESTABLISHED,RELATED \

		-j ACCEPT

$IPTABLES  -A SSH -p tcp --syn -m recent --name badSSH --rcheck \

		--seconds 300 -j REJECT 

$IPTABLES -A SSH -p tcp --syn -m recent --name sshconn --rcheck \

		--seconds 60 --hitcount 5 -j SSH-HACKER

$IPTABLES -A SSH -p tcp --syn -m recent --name sshconn --set

$IPTABLES -A SSH -p tcp --syn -j ACCEPT

echo -n "...done!"

$IPTABLES -A INPUT -i $NET_IFACE -p TCP --dport 22 -j SSH #SSH server

----------

## DNAspark99

knock knock.

port knocking is the way to go. several options out there.

Also only allow key authentication in sshd, to be even more secured.

if you're creating scripts to ban brute offenders, if one of them actually happens to find a valid user/pass before your script swings into action, then it's probably allready TOO LATE!!

----------

## _dA_CyANIDe

Yes, yes, you have right. No user/pass.  :Laughing:   :Laughing: 

----------

## Shadus

 *DNAspark99 wrote:*   

> if you're creating scripts to ban brute offenders, if one of them actually happens to find a valid user/pass before your script swings into action, then it's probably allready TOO LATE!!

 

Heh, if they manage to get a password you deserve to be rooted. ;P

bob.bob.net bob/bob whee!

----------

## Spockmeat

All I did for mine (and I don't claim it to be correct or finished, but it seems to be working properly) was the following, and you can just run these command as is from the command line to add the rules to your iptables. 

```

#create the SSH and bad ssh tables

iptables -N SSH

iptables -N SSH-bad

#in the bad ssh table, mark the ip as bad and drop all packets from it

iptables -A SSH-bad -m recent --name badSSH --set

iptables -A SSH-bad -j DROP

# in the ssh table, allow all connections that are already connected

iptables -A SSH -p TCP --dport 22 ! --syn -m state --state ESTABLISHED,RELATED -j ACCEPT

#drop all packets from marked bad ips for 10 minutes

iptables -A SSH -p TCP --syn -m recent --name badSSH --rcheck --seconds 600 -j DROP

# if an ip tries to connect 5 times in 10 minutes, pass the ip to the bad ssh table

iptables -A SSH -p TCP --dport 22 --syn -m recent --name sshconn --rcheck --seconds 600 --hitcount 5 -j SSH-bad

#if the ip address is still ok, mark it as having connected and accept it

iptables -A SSH -p TCP --dport 22 --syn -m recent --name sshconn --set

iptables -A SSH -p TCP --dport 22 -j ACCEPT

# make iptables go through the ssh table and then go through the rest of the regular stuff

iptables -I INPUT 1 -j SSH

```

I basically did this because I was getting between 3 and 5 thousand hits on root, unknown and others per day.... now I get 5 from a particular ip address and they're all done  :Smile: 

edit: heh, I started this post at noon, and someone else posted about the exact same thing just a couple hours ago.  :Laughing: 

----------

## Syzygy

I'm going to go ahead and /bump this.  I would like to add my thoughts and question:

- Like everyone else I am constantly brute-forced

- I have taken the smart route and disabled logins for all but a single non-root user, who has a strong password.

I would still like a program that temporarily bans "login-happy" IP's. ... Not because I am paranoid about security, but because it gets rather tedious, waiting for mutt to load up 10,000 e-mails every day, most of which are titled "Warning (program: sshd)".  So I would like a solution to stop the problem at its source (i.e., autoban chatty IP's) or somewhere downstream (i.e., suppress cron e-mailing of those particular warning messages).

Running sshd on a port other than 22 seems like a good solution to the problem, but I wanted to see what other people suggested.

----------

## alsuren

okay, here's something:

When people do brute force attacks, they'll probably be doing it from a compromised box (one would assume) so would it be possible to do a "return fire" attack, with the intention of getting rid of whatever is running on the system to automatically brute force you (and maybe even run something on the compromised system so if someone (possibly the cracker who compromised the box in the first place?) tries to log in, it'll lock him out too.

*shrug* 

I don't know how this would work really, but it would be nice if we could set up a load of booby trap boxes out there on the net that are locked down so that nobody can break in, and will return fire only when attacked. Then we might see the numbers of compromised boxes going *down*

Trouble is if the compromised boxes are windows ones, you couldn't simply make it run a bash script :P

This is probably not the most useful of posts, but it'd be a cool idea, no?

----------

## marslander

bah i'm running a deny host script and ahave only one user that can login to the server 

and moslty bans stay for a while say till i get the mood of cleaning them out or say a month ban i think for each ip 

kidan less trouble if they can find the right user and theright pass 

they realy arent bad 

since in brute force hm start by A kidna or say depending on there dictionary and the change they find right user and pass 

is one out of i dunno and since htye gat banned after 5 wrong login attempts 

would take thema while to get there

----------

## nevynxxx

How about the easier way.

1) how often do you connect from the outside?

2) how often do you connect from a subnet other than your work/favorite cafe?

Step one, block all ssh connection on the external interface.

If the answer to 1) is never. Stop here, your done. If the answer to two is never, add rules to allow from the apropriate subnet(s). Otherwise implement port knocking.

----------

## isilia

There are LOADS of invalid user errors (sshd) in /var/log/auth.log, example:

```
Sep 23 22:18:40 localhost sshd[2235]: Invalid user admin from 200.67.79.212

Sep 23 22:18:42 localhost sshd[2239]: Invalid user test from 200.67.79.212

Sep 23 22:18:44 localhost sshd[2243]: Invalid user guest from 200.67.79.212

Sep 23 22:18:46 localhost sshd[2247]: Invalid user webmaster from 200.67.79.212

```

I'm guessing it's a hacker? I got 2 IP addresses trying to log in; on the 23th, the 25th and the 27th.

Edit: I stopped sshd in either case.

----------

## erik258

It's probably the Bot Net.  That's just speculation, but  it's unlikely that somebody's trying to log into your computers manually.  Instead, I would think that it's an automated system that uses already compromised computers to try to compromise new systems by finding accounts with guessable passwords and logging in with ssh, in an effort to grow the ranks of the compromised servers.  

I have seen these logins ever since I put my boxes on broadband.  I don't worry about it because I use strong passwords and have few users.  However, I would recommend you look into Fail2Ban which uses IPTables and/or log files to temporarily or permanently firewall access from abusive IPs.  I have seen it configured, and was impressed with the results.  

You can also have SSH listen on a port other than 22, the standard SSH port. 222 and 223 used to be forwarded through the router to internal servers, and my logs don't show anyone unauthorized ever tried to log in to an SSH server listening on a nonstandard port (although it is technically possible to identify an SSH server running on a nonstandard port, it takes substantially longer, and therefore is probably a much less efficient attack vector than simply hitting the standard port).  

I have always wanted to set up a honey pot on 22, so that I could turn around the username/password combinations I collected and use them to start fighting back against these bot nets.  But I ran into difficulties getting the supplied password out of the SSH server from openSSH; I am not a skilled hacker.  But I digress.  

In conclusion, I do not worry about these failed logins, but some of my friends do; I usually recommend listening on a nonstandard port because fail2ban is more difficult to configure, but both are good solutions, and fail2ban requires no outside knowledge client-side (which port to connect to) and avoids possible attacks that have found your nonstandard SSH ports using smarter service identification, so it's probably a better choice all around.  Of course, you can always use RSA certs rather than passwords to log in, making it absurd to try to guess the authentication info.  And nothing is a replacement for strong passwords.  

And remember, the originating IP of these attacks is probably not owned by an attacker, but rather to the poorly secured server of a more or less benevolent internetzien.  (I like to look up the admin of the IP range if driven to action, and send them an informative email about the problem, but I have never once heard back from them.   They are usually overseas).  

Good luck.

----------

## nixnut

merged above two posts here

----------

## isilia

erik258: Thank you for your (lengthy) reply! Running SSH on a non standard port isn't an option for me, so I'll configure fail2ban. Thanks again.

----------

## zyko

There is also http://denyhosts.sourceforge.net/

I manage to ban myself roughly once a month with denyhosts, so there are downsides  :Wink: 

----------

## erik258

 *fisk wrote:*   

> Hmm... can't I instead do something like this:
> 
> (I don't really know bash_scripts, I just took a few lines out of a firewall_script I run)
> 
> I take the ip.blacklist generated by ie. awk from the /var/log/messages and somehow:
> ...

 

Fail2ban fleshes out this approach further by adding an iptables table for counting connections and banning hosts in realtime.  It's a good system, I recommend you look into it.  

 *Quote:*   

> - I have taken the smart route and disabled logins for all but a single non-root user, who has a strong password. 

 

and if you should have more than one user?

----------

