Fail2ban for VPN on Mikrotik

Are they brute-forcing the VPN server? Zombie clients are endlessly trying to connect, unaware that their accounts have long since been deleted? I couldn’t find a ready-made solution for Mikrotik, so I had to turn to ChatGPT for help. After several attempts and manual debugging, I finally got a working solution.

Actually, we add this script to system > scripts:

 :local threshold 3;
:local interval 60;
:local currentTime [:tostr [/system clock get time]];
:local count [/log find where (message~"authentication failed") && (message~"user") && (time>=($currentTime-$interval))];
:foreach log in=$count do={
    :local logMessage [/log get $log message];
    :local srcAddr [:pick $logMessage 1 [:find $logMessage ">"]];
    :local srcUser [:pick $logMessage [:find $logMessage "user"] [:len $logMessage]];
    :local countAddr [/log find where (message~"authentication failed") && (message~$srcAddr) && (message~$srcUser)];
    :if ([:len $countAddr] >= $threshold) do={
        /ip firewall address-list add list=ban-l2tp address=$srcAddr timeout=1h;
    }
} 

The script will be run by the scheduler, search the logs for failed authorization attempts, and add the source address to the designated list. Timeout=1h can be omitted; in this case, the address will not disappear from the list automatically.

Go to system > scheduler and add a task:

Well, and of course, we add a rule to the filter that, for example, prohibits all traffic from addresses from the collected list.

Tested on l2tp with Routers 7.14