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> # 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.
Mac OS X Hints
http://hints.macworld.com/article.php?story=20081009042121813