Submit Hint Search The Forums LinksStatsPollsHeadlinesRSS
14,000 hints and counting!

Disable ssh access for password-guessing bots Network
My machine is being hit by a lot of automated attacks that try to guess account names and passwords on sshd. (This problem has been touched in this hint.) Thanks to Little Snitch, it is very easy to see that this happens. Anyway, it is annoying, and I wanted to add an ipfw rule to block those machines that fail to log in fifteen or more times. So I wrote a launchd script to do this:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
        <key>Label</key>
        <string>se.sics.lra.denyhosts</string>
        <key>ProgramArguments</key>
        <array>
                <string>/usr/bin/awk</string>
                <string>
          substr( $5, 0, 4) == "sshd" && $6 == "Failed" {
                ip = $13
                count[ip] += 1
          }
          END {
                s = "ipfw delete 101; "
                sep = "ipfw add 101 deny src-ip "
                for (ip in count) {
                   if (count[ip] > 15) {
                      s = s sep ip
                      sep = ", "
                      print count[ip] " failed attempts from " ip
                   }
                }
                print
                system(s)
          }
                </string>
                <string>/var/log/secure.log</string>
        </array>
        <key>StartInterval</key>
        <integer>20</integer>
        <key>UserName</key>
        <string>root</string>
        <key>StandardOutPath</key>
        <string>/tmp/denyhosts.out</string>
</dict>
</plist>
I put the finished script in /Library/LaunchAgents/se.sics.lra.denyhosts.plist, and set the owner as root:
 # chmod root:wheel /Library/LaunchAgents/se.sics.lra.denyhosts.plist
To start it (without rebooting), just do (in Terminal as root):
# launchctl load /Library/LaunchAgents/se.sics.lra.denyhosts.plist
The script scans /var/log/system.log every 20 seconds for failing ssh logins. If it finds more than 15 from a particular address, that address is disabled by ipfw. Do sudo ipfw list to see the active rules. Note that when the entries disappear from the log file, the ipfw rules are removed. The script must unfortunately run as root, as only root has permisson to read /var/log/system.log and to modify ipfw rules.

[robg adds: I haven't tested this one.]
    •    
  • Currently 2.00 / 5
  You rated: 1 / 5 (9 votes cast)
 
[24,123 views]  

Disable ssh access for password-guessing bots | 38 comments | Create New Account
Click here to return to the 'Disable ssh access for password-guessing bots' hint
The following comments are owned by whoever posted them. This site is not responsible for what they say.
Disable ssh access for password-guessing bots
Authored by: remolinero on Oct 10, '08 08:17:42AM
I'm missing something? AFAIK LittleSnitch (which I use) just inform about outgoing connections, not incoming as ssh connections trying to get into your computer...

[ Reply to This | # ]
Disable ssh access for password-guessing bots
Authored by: davearonson on Oct 10, '08 08:22:31AM

This is one of the times where a bit of "security by obscurity" can be convenient. Simply changing your ssh port, will stop the vast majority of the bots hammering on your box. Of course it won't stop a real live human who really wants to get in, or even a semi-smart scan that can notice something answering on the new port and figure out what it is. So, still do all the usual stuff, like disabling root ssh and so on, and consider Iras's hint. But, it will keep your security log a lot cleaner so you can spot the more worrisome problems more easily, and relieve your network stack and security subsystem of some work.

---
"Specialization is for insects." -Heinlein
Work: http://www.davearonson.com/
Play: http://www.davearonson.net/



[ Reply to This | # ]
Disable ssh access for password-guessing bots
Authored by: zadig on Oct 10, '08 08:26:31AM

I have to disagree. Security by obscurity is almost as bad as no security at all. A port scanner can see which ports are open, and then identify your alternative SSH port as SSH anyway. At that point, you're in the same danger as any other SSH user.

Disabling password authentication (per my other comment) is much safer. If you do that, people can pound on the port with any passwords they want without any danger. But with the right private key, you can get in any time you need to.



[ Reply to This | # ]
Disable ssh access for password-guessing bots
Authored by: tempel on Oct 10, '08 08:45:45AM

And I disagree with you. The bots I've seen attacking public ssh servers at random do _not_ scan all ports but just go for the easy route. Sure, if some hacker is dedicating all its time to crash just your machine, he's going for the port scan route for sure, but the poster here tries to get rid of the random and dumb attempts, which are the major and most common annoyonce for a public server.



[ Reply to This | # ]
Disable ssh access for password-guessing bots
Authored by: zadig on Oct 10, '08 09:04:48AM

Perhaps I read the original hint wrong, then. It didn't seem aimed at preventing the messages from appearing (which your suggestion would definitely help with), but the poster seemed to want to ban machines that try and fail too many times, which seems like a security issue.

I have no problem with securing your machine against general, automated scans/attacks, but I'd rather secure it against targeted manual attacks too, which obscurity doesn't do. That's why locking out password auth seemed like a better solution to me.

This doesn't change the basic question: how to keep the Mac safe from brute-force password attacks. Safest thing is disable SSH altogether. Next safest is enable SSH but block the connections from the outside world, aka blocking at the router. Finally, if you allow connections from the outside world, disable passwords and depend on key authentication.



[ Reply to This | # ]
Disable ssh access for password-guessing bots
Authored by: corienti on Oct 10, '08 09:56:33AM

I agree with both of you - changing the port WILL stop the constant bot scans - they only check port 22.
However it won't stop a targeted attack.
I prefer to run SSH on a nonstandard port to stop the bot scans, AND disable password login to help defend against targeted attack.

I ALSO don't believe in scanning the logfile for failed logins; I simply have the firewall start dropping ALL packets from an IP that hits my SSH port more frequently than a certain rate, say 10 times in 8 seconds.

Nobody, including even me, has any business hitting my SSH port at a high rate. So if anyone does, simply drop all packets (not just SSH!) from them for the next hour or so. Or day, if you like.

I'm not sure how to do this with ipfw cos I don't use it, as all my Macs sit behind NATing firewall that I set up personally; but it's easy enough to do with iptables (Linux) or pf (OpenBSD) and I have iptables doing it at home and pf doing it at work. I'm sure it's easy enough to do with ipfw.

(actually, I tell a small lie; it's actually slightly tricky with pf - but still no major hassle)



[ Reply to This | # ]
Disable ssh access for password-guessing bots
Authored by: isancho on Oct 10, '08 10:11:24AM

I don't think that IPFW lets you overload tables dynamically like PF. I'm willing (and hoping) to be proven wrong on this, though.



[ Reply to This | # ]
Disable ssh access for password-guessing bots
Authored by: robdew on Oct 10, '08 10:32:19AM

If you don't care about breaking compatibility, moving SSH to a different port will have two effects: 1) it will clear clutter from your logs and 2) ssh login attempts you see on another port are probably far more serious than port 22 scanning bots.

So long as you realize you aren't trying to hide the door, just move doorknob so someone has to look around to find it, you'll will still be better off.

I've heard the "obscurity is not security" phrases all the time. Obscurity is a layer of security. Just make sure it's not the only layer.

Private keys help a lot.



[ Reply to This | # ]
Disable ssh access for password-guessing bots
Authored by: jeremyp on Oct 10, '08 10:34:47AM

Only problem is if, like me, you regularly work in an office which blocks outbound connections to all non well known ports.




[ Reply to This | # ]
Disable ssh access for password-guessing bots
Authored by: zadig on Oct 10, '08 08:23:32AM

Another solution that I've used on my installation is to disable password-based access to SSH, but still allow logins using public/private key authentication.

I did this because I wanted remote access to my system while I was at work, but didn't like the thousands of password attempts I saw every day to have any chance of succeeding.

You can set up key authentication in SSH by following this hint. After that, you can disable password authentication by editing /etc/sshd and setting PasswordAuthentication=no.



[ Reply to This | # ]
Disable ssh access for password-guessing bots
Authored by: zadig on Oct 10, '08 08:32:02AM

Forgot to look at my own /etc/sshd_config file before posting. No equal sign, and there's another setting to change (as the comments in the file warn you anyway). Set these two lines:

PasswordAuthentication no
UsePAM no

Another thing I remembered while I was editing is that Apple sometimes overwrites that file during updates. At least, it must have once because I looked at this file after changing it a long time ago, and saw that my custom settings were gone. So check it after you install any update to make sure your sshd_config is still locked down.



[ Reply to This | # ]
Disable ssh access for password-guessing bots
Authored by: Cobalt Jacket on Oct 12, '08 08:55:37PM

This person is spot-on. Using private-key authentication will instantly negate scriptkiddies as an issue. And if you're at a foreign computer, you can carry SSH and a private key (perhaps not your main one) around on a USB keyfob.



[ Reply to This | # ]
Disable ssh access for password-guessing bots
Authored by: eddiem5 on Oct 10, '08 08:32:12AM

There are a few other choices you might want to look at..

1) Denyhosts
Similar to what you built but has a clearing service where you can download IP's from other users of denyhosts.. Google it..

2) Have you looked at the adaptive firewall already in Mac OSX??

Try man afctl




[ Reply to This | # ]
Disable ssh access for password-guessing bots
Authored by: robdew on Oct 10, '08 10:35:32AM

$man afctl
No manual entry for afctl



[ Reply to This | # ]
Disable ssh access for password-guessing bots
Authored by: robdew on Oct 10, '08 10:39:54AM

so is it possible to get/build afctl on Mac OS client/desktop?



[ Reply to This | # ]
Disable ssh access for password-guessing bots
Authored by: club60.org on Oct 10, '08 12:26:25PM

It is present on Mac OS X Server



[ Reply to This | # ]
Disable ssh access for password-guessing bots
Authored by: danaris on Oct 10, '08 08:46:57AM

Yes, obviously security by obscurity is no security at all *in theory*, but given the number of ssh attack-bots that only go for port 22, and don't bother with a port-scan, in this case it gives some good practical results.

If you're hosed with your SSH port at 28376, you're *even more* hosed with it at 22.

~dan



[ Reply to This | # ]
Disable ssh access for password-guessing bots
Authored by: danaris on Oct 10, '08 08:50:22AM

Gah, this was meant to be a reply to zadig above :-P

Guess I lose at comment-posting...

~dan



[ Reply to This | # ]
Disable ssh access for password-guessing bots
Authored by: zadig on Oct 10, '08 09:07:13AM

Agreed, you're less hosed if you change the SSH port. But see my reply to tempel above - why go for partial security when you can just lock down the whole thing?



[ Reply to This | # ]
Disable ssh access for password-guessing bots
Authored by: tempel on Oct 10, '08 08:56:21AM

There are a few problems with this:

1. The "chmod" command needs to be called "chown" instead.

2. The text for the plist file can't be used directly that way, at least not in OS 10.5.5, because it contains illegal characters, such as "&" and ">".
To fix this, replace the "&&" with "&amp;&amp;" and "if (count[ip] > 15) {" with "if (count[ip] &gt; 15) {"

Not sure if that's all, but at least now the instructions work. Remains to see if it works.



[ Reply to This | # ]
Disable ssh access for password-guessing bots
Authored by: tempel on Oct 10, '08 09:05:06AM

OK, it appears to work. I've "attacked" my ssh server with a few different user names and now my IP is blocked in ipfw.



[ Reply to This | # ]
Disable ssh access for password-guessing bots
Authored by: Solarusdude on Oct 10, '08 09:13:24AM

For those interested in learning how to secure SSH using a public/private key pair (or learn a lot about using SSH in general), there is an excellent 8-part video podcast series hosted by "Typical Mac User Podcast" which shows you how to do all that.



[ Reply to This | # ]
Disable ssh access for password-guessing bots
Authored by: isancho on Oct 10, '08 10:09:35AM

The upshot of this hint, though, is that you'll see 15 attempts in your logs, and then you'll stop seeing them. Since I routinely see around a hundred attempts from the same IP address, this will cut down on the size of my logs and the time spent reading them.

If you don't have any users requiring SSH besides yourself, you could even lower than to 5 or so.



[ Reply to This | # ]
Disable ssh access for password-guessing bots
Authored by: robdew on Oct 10, '08 11:12:20AM

Also be aware that Denyhosts-style scripts like this are subject to DOS attacks. If a bot or a bad person gets behind the same IP address as you (e.g. NAT) you're locked out.



[ Reply to This | # ]
Disable ssh access for password-guessing bots
Authored by: foilpan on Oct 10, '08 12:40:36PM

it would be easier to use /etc/hosts.allow and /etc/hosts.deny in conjunction with running ssh on a different port and disabling normal typed logins in favor or keys.

i do that for most of my clients' servers if ssh is allowed inbound through their firewalls. these simple measures don't prevent the type of dictionary attacks you mention, but they will prohibit access. ideally, if you're getting hammered, you'd want to manage this at the firewall level by dropping the attackers' connections.



[ Reply to This | # ]
Disable ssh access for password-guessing bots
Authored by: Brathahn on Oct 10, '08 01:05:40PM

Had similar problems with our web server at home. When I was really bored I used to watch /var/log/messages (was a Linux box) scrolling by with all the automated SSH attacks.... Then I got bored of watching this, and changed the listening port for SSHd in the sshd config file and since then there hasn't been a single automated attack on SSHd.

This also had the interesting side effect that I could access my box from work where they thought to be clever and blocked outbound TCP/22 connections.... but somehow allow outgoing SSH connection on some 10000+ port....



[ Reply to This | # ]
Disable ssh access for password-guessing bots
Authored by: lras on Oct 10, '08 01:50:08PM

Answers to the comments:
@remolinero: LittleSnitch now also has a floating window which shows the network activity of all programs, even if they are allowed to communicate.

@eddiem5: this single file was intended to replace the denyhosts package, which is bigger than this file and relies on old stuff like modifying /etc/hosts files.

@tempel: you are absolutely right. It should be chown, and the ampersands looked nice in the preview but got translated back when the hint was sent out. Rob, it would be wonderful if you could fix that. And another typo, I wrote that it scans system.log when it really scans secure.log.

@robdew: about denial of service attacks. Interesting thought. Could perhaps be wise to just block for an hour instead of until secure.log is rotated.





[ Reply to This | # ]
Disable ssh access for password-guessing bots
Authored by: mush on Oct 10, '08 03:37:21PM

Wow! This is great!

Is there a way to get this to start up automatically during boot?

Thanks



[ Reply to This | # ]
Disable ssh access for password-guessing bots
Authored by: mush on Oct 10, '08 04:30:14PM

ok. I was able to make this start up at boot.

But now, in my console log, I'm getting the following messages:

10/10/08 7:20:22 PM com.apple.launchd[91] (se.sics.lra.denyhosts[548]) open("/tmp/denyhosts.out", ...): Permission denied
10/10/08 7:20:22 PM se.sics.lra.denyhosts[548] 27 failed attempts from 92.xxxx
10/10/08 7:20:22 PM se.sics.lra.denyhosts[548] 32 failed attempts from 202.xxxx
10/10/08 7:20:22 PM se.sics.lra.denyhosts[548] ipfw: socket: Operation not permitted
10/10/08 7:20:22 PM se.sics.lra.denyhosts[548] ipfw: socket: Operation not permitted

I'm worried about all of these messages happening every 20s.

I was able to stop the "Permission denied" by removing the print statement and the STDOUT key and string. That also remove the "failed attempts from" message, which is OK.

Any idea what the operation not permitted error is? If I do a 'sudo ipfw list' I do see those IP address blocked.

Thanks



[ Reply to This | # ]
Disable ssh access for password-guessing bots
Authored by: lras on Oct 14, '08 12:21:14AM

The problem is that your script is not running as root.
That's why you are not allowed to change the network settings with ipfw, and that's why you are not allowed to write to the /tmp/denyhosts.log, since there is probably a file with that name already which is owned by root. (It was created when you ran the agent earlier. And btw, it can safely be removed.)

I think you have managed to start the script running as yourself, perhaps by putting it in /Users/<yourlogin>/Library/LaunchAgents/ ?



[ Reply to This | # ]
Disable ssh access for password-guessing bots
Authored by: grefft on Oct 10, '08 08:26:20PM
Thanks for the great tip. I get raked by these bots all the time.
This script seems to be exactly what i need but I'm getting some errors in my system log that appear to be keeping it from running. Any idea what I could do to fix this?

I'm seeing this in system.log every 20 seconds
Oct 10 23:21:36 Home-iMac se.sics.lra.denyhosts[571]:  context is
Oct 10 23:21:36 Home-iMac se.sics.lra.denyhosts[571]: 	                >>>  print <<< 
Oct 10 23:21:36 Home-iMac se.sics.lra.denyhosts[571]: 	extra }
Oct 10 23:21:36 Home-iMac se.sics.lra.denyhosts[571]: /usr/bin/awk: bailing out at source line 19
Oct 10 23:21:36 Home-iMac com.apple.launchd[103] (se.sics.lra.denyhosts[571]): Exited with exit code: 2
thanks again.

[ Reply to This | # ]
Disable ssh access for password-guessing bots
Authored by: lras on Oct 14, '08 12:23:57AM

Check out the comment by

By: tempel on Fri, Oct 10 2008 at 8:56AM PDT

The problem is that the MacOSXHints blog software ate the markup characters.

& and < are not allowed in the XML .plist file, and must be written as &amp; and &gt;




[ Reply to This | # ]
Disable ssh access for password-guessing bots
Authored by: eagle on Oct 11, '08 11:02:07AM

Another solution is to enable SSH access from only those networks that need it.

The entire world can access my web server, but you need to be coming from one of a handful of source IP subnets in order to even hit my SSH port. Now, of course, there could still be bots on those networks, but that hasn't been my experience. And, yes, I watch my log daily.

---

Another option: disable IPv4 SSH altogether. If you're behind a router, this is easy. And, with a properly configured router, Back To My Mac still works for inbound IPv6 SSH.



[ Reply to This | # ]
SSHBlack python script
Authored by: grahamix on Oct 11, '08 03:22:24PM
I had exactly the same problem of script kiddies trying to break in - searching around I found SSHBlack which is a python script that adds failed login IPs to a blacklist, and after a period of time (several days), frees them up again. I have mine set for three incorrect attempts to login with SSH and then it locks the IP address out.

http://www.pettingers.org/code/sshblack.html

When I moved house and reconfigured the network, I also switched the external port - that action alone has meant zero script kiddie attacks in the 2 months it has been in place. Versus two or three attackers per day when I was on Port 22.



[ Reply to This | # ]
ipfw errors...
Authored by: rcfa on Oct 29, '08 11:36:57PM

I like the basic idea of this, because it's low overhead and uses existing system functionality in a smart way.

However, now I get these messages:
"ipfw: rule 101: setsockopt(IP_FW_DEL): Invalid argument"
in my console.log.
I presume, that's the result of trying to remove old ipfw rules where none exist.
It would be nice if the script checked first if there are any, rather than deleting blindly...

Anyway, that's my guess from playing with this for a few minutes...



[ Reply to This | # ]
Disable ssh access for password-guessing bots
Authored by: krunk7 on Feb 03, '09 05:23:46PM

You could also just put ssh on a non-standard port and let the guys slam away at 22 all they want.



[ Reply to This | # ]
Disable ssh access for password-guessing bots
Authored by: thejoecarroll on Mar 24, '09 06:22:19AM
Thanks very much for this script.

I'd like to suggest the following amendment to avoid needlessly filling up logs with errors even though the script is working normally. To check first if the script already has a rule in place before attempting to delete it, simply replace the line:

s = "ipfw delete 101; "

with:

if (system("ipfw list | cut -d ' ' -f 1 | grep 00101") == 0) {

print;

s = "ipfw delete 00101; ";

} else {

s = "";

}



[ Reply to This | # ]

Disable ssh access for password-guessing bots
Authored by: stephenr on Jun 10, '09 04:07:26PM
First, I modified this script to pick up other brute force like activity against SSH (i already have password auth turned off)..

Then I got rid of that and went for a better solution: fail2ban.

It's available as a pre-built OS X package here: http://www.lsa.umich.edu/lsait/admin/mac/software/index.asp

[ Reply to This | # ]