Recently I was looking for a script to block SSH brute force attempts to the device itself but all I found was iptables connection threshold based rules. This is okay, but that means if I make multiple legitimate connections I could still get blocked.

So I wrote the script below to add IPs to the block list based on failed authentication log entries.

First you should setup a log specifically for failed authentication that this script will parse.

Now you need to setup a “schedule” to run the script. Again I did this with Winbox. The timing of the schedule does matter though. Basically it is the number of failed login attempts since the last time the script was run. In this case I used five (5) minutes. The schedule only has to run the command below, replacing the script name below with whatever you named your script.

/system script run ssh_bruteforce_block

Finally you need a filter rule to drop any IP on the blacklist. The command below will create the filter rule to block any IP on the blacklist coming into ethernet1 on port 22 (on the input chain). Please make sure to put this above your allow rule in the list.