Community discussions

MikroTik App
 
Term
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 88
Joined: Thu Jan 11, 2018 11:42 pm

How to block SSH attackers after 3 bad logins?

Sun Jan 14, 2018 1:55 pm

Hello,
I'm new in Mikrotik but need to learn it because my new work :)
Have RB962UiGS at home. Need to block SSH after 3 unsuccessful logins. I know there is a wiki with example but there are a lot of lists before it. I need if somebody will try login firewall will add him to SSH_Blacklist for 10 days. Don't understand what 1/1m,1,dst-address/1m protocol=tcp means but it works.

This is what I have for FTP, after 3 bad logins
/ip firewall address-list
add list=FTP_Blacklist
/ip firewall filter
add action=drop chain=input comment="drop ftp brute forcers" dst-port=21 \
    in-interface=ether1 protocol=tcp src-address-list=FTP_Blacklist
add action=accept chain=output content="530 Login incorrect" dst-limit=\
    1/1m,1,dst-address/1m protocol=tcp
add action=add-dst-to-address-list address-list=FTP_Blacklist \
    address-list-timeout=1w3d chain=output content="530 Login incorrect" \
    protocol=tcp
/ip firewall nat
add action=masquerade chain=srcnat out-interface=pppoe-out1
add action=dst-nat chain=dstnat comment=Transmission dst-port=53105 \
    in-interface=pppoe-out1 protocol=tcp to-addresses=10.31.0.102 to-ports=\
    53105
add action=dst-nat chain=dstnat comment="Synology DSM" dst-port=6271 \
    in-interface=pppoe-out1 protocol=tcp to-addresses=10.31.0.102 to-ports=6271
add action=masquerade chain=srcnat comment="VPN accept" src-address=\
    10.31.10.0/24
Thank you
 
User avatar
sebastia
Forum Guru
Forum Guru
Posts: 1782
Joined: Tue Oct 12, 2010 3:23 am
Location: Antwerp, BE

Re: How to block SSH attackers after 3 bad logins?

Sun Jan 14, 2018 7:41 pm

Hi

"1/1m,1,dst-address/1m" -> config for dst-limit matcher, have a look at https://wiki.mikrotik.com/wiki/Manual:I ... all/Filter.

It will not work for ssh, as it's traffic is encrypted. You could do it on the machine itself, plugging into pam.
 
emikrotik
Frequent Visitor
Frequent Visitor
Posts: 71
Joined: Fri Jun 19, 2015 9:30 am

Re: How to block SSH attackers after 3 bad logins?

Mon Jan 15, 2018 5:10 am

Hi,

Do you need to access your routes from outside of your network?

Why not allow connection via ssh or winbox only from your lan subnet and block from all other sources?

;;; Allow Firewall Remote access
chain=input action=accept src-address=<LAN subnet>

;;; Drop Firewall Remote access
chain=input action=drop protocol=tcp dst-port=8291,8728,21,161,22
 
User avatar
karlisi
Member
Member
Posts: 437
Joined: Mon May 31, 2004 8:09 am
Location: Latvia

Re: How to block SSH attackers after 3 bad logins?

Mon Jan 15, 2018 2:50 pm

If You want to keep ssh wide open, this is working configuration to add some brute-forcers to blacklist. Then You can use this blacklist to fully block these addresses (be careful, You can block yourself too) or only block ssh and perhaps some other sensitive ports.
add action=jump chain=input comment="jump to detect_bruteforce ssh \
    from WAN), except whitelist" dst-port=22 in-interface=WAN \
    jump-target=detect_bruteforce protocol=tcp connection-state=new
add action=add-src-to-address-list address-list=blacklist \
    address-list-timeout=10d chain=detect_bruteforce comment=\
    "add brute-forcer to blacklist for 10 days" src-address-list=blk_stage3
add action=add-src-to-address-list address-list=blk_stage3 \
    address-list-timeout=1m chain=detect_bruteforce comment=\
    "add client to blk_stage3 list" src-address-list=blk_stage2
add action=add-src-to-address-list address-list=blk_stage2 \
    address-list-timeout=1m chain=detect_bruteforce comment=\
    "add client to blk_stage2 list" src-address-list=blk_stage1
add action=add-src-to-address-list address-list=blk_stage1 \
    address-list-timeout=1m chain=detect_bruteforce comment=\
    "add client to blk_stage1 list"
 
Term
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 88
Joined: Thu Jan 11, 2018 11:42 pm

Re: How to block SSH attackers after 3 bad logins?

Mon Jan 15, 2018 7:18 pm

I don't need to access to my mikrotik from outside (using VPN).
My local dhcp is 10.31.0.0/24
My VPN pool is 10.31.10.0/24

So I added these pools in IP - services - ssh and winbox.
But I want to see in some lists that somebody tried to access to my mikrotik from outside. Is there any way?

karlisi: thank you but I don't want to have a lot of lists in firewall. All I want is block user after 3 failed logins and add him to list for 10 days
 
User avatar
sebastia
Forum Guru
Forum Guru
Posts: 1782
Joined: Tue Oct 12, 2010 3:23 am
Location: Antwerp, BE

Re: How to block SSH attackers after 3 bad logins?

Tue Jan 16, 2018 1:31 am

You could log all new connections to ssh. That would include yours too.
 
Term
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 88
Joined: Thu Jan 11, 2018 11:42 pm

Re: How to block SSH attackers after 3 bad logins?

Sat Jan 20, 2018 9:52 pm

I made something like this, don't know if it's ok. I somebody try to ssh 4 times in 15 seconds, it will block him. What do you think?
add action=drop chain=input comment="drop ssh brute forcers" dst-port=22 \
    protocol=tcp src-address-list=ssh_blacklist
add action=add-src-to-address-list address-list=ssh_blacklist \
    address-list-timeout=1w3d chain=input connection-state=new dst-port=22 \
    protocol=tcp src-address-list=ssh_stage1
add action=add-src-to-address-list address-list=ssh_stage1 \
    address-list-timeout=15s chain=input connection-state=new dst-port=22 \
    protocol=tcp

 
User avatar
acruhl
Member
Member
Posts: 371
Joined: Fri Jul 03, 2015 7:22 pm

Re: How to block SSH attackers after 3 bad logins?

Sat Jan 20, 2018 10:56 pm

But I want to see in some lists that somebody tried to access to my mikrotik from outside. Is there any way?
If "outside" means "internet", this gets tedious and fairly useless very quickly. You should try it though just to prove it to yourself. Add a log prefix for your port 22 tcp block rule (ssh) and you'll see what I mean. If it's internal to your company and you want to see who's doing this, then this is totally legit and you should do it.

I run ssh on a random high numbered port and I honestly don't get too many connection attempts. I put a block list action on anyone trying to access the ports just before and just after and it cut that small number in half or more.

My decision is to trust ssh. If I didn't I would put in port knocking which makes it a bit more tedious to connect.
 
User avatar
karlisi
Member
Member
Posts: 437
Joined: Mon May 31, 2004 8:09 am
Location: Latvia

Re: How to block SSH attackers after 3 bad logins?

Mon Jan 22, 2018 9:08 am

This will block ssh after 2nd time. To block after 4th time using this method, use 3 temporary stages and then add to blacklist.
I made something like this, don't know if it's ok. I somebody try to ssh 4 times in 15 seconds, it will block him. What do you think?
add action=drop chain=input comment="drop ssh brute forcers" dst-port=22 \
    protocol=tcp src-address-list=ssh_blacklist
add action=add-src-to-address-list address-list=ssh_blacklist \
    address-list-timeout=1w3d chain=input connection-state=new dst-port=22 \
    protocol=tcp src-address-list=ssh_stage1
add action=add-src-to-address-list address-list=ssh_stage1 \
    address-list-timeout=15s chain=input connection-state=new dst-port=22 \
    protocol=tcp

 
User avatar
donsergio
Frequent Visitor
Frequent Visitor
Posts: 85
Joined: Wed Jan 31, 2018 8:35 pm
Location: Spain

Re: How to block SSH attackers after 3 bad logins?

Thu Feb 01, 2018 6:49 pm

You also can change ssh port at IP-Services and change for a random port... such as 2200 (anyone easy to remember)....
 
zivtal
Frequent Visitor
Frequent Visitor
Posts: 57
Joined: Sun Feb 05, 2017 6:22 pm

Re: How to block SSH attackers after 3 bad logins?

Thu Feb 07, 2019 8:15 pm

I made this script, You should add scheduler every 5-10 minutes it's check if you had login failure more then 5 times from same ip it's automatically add the ip to block list.

If you want only 3 attempts you can change the line: ":local attempt 5" to ":local attempt 3"
#check if logging action exists, if not create action
:if ([:len [/system logging action find name=login]]=0) do={
	/system logging action add name=login target=memory
} 
#check if logging rule exists, if not create rule
:if ([:len [/system logging find action=login]]=0) do={
	/system logging add topics=system,error,critical action=login
}
#login failure attempts
:local attempt 5
:if ([:len [/log find where buffer=login message~"login failure" and message~"from"]]>0) do={
	#get IP from log
	:local getIP do={
		:if ([:type [:find $string "from"]]!="nil") do={
			:local cut [:pick $string ([:find $string "from"]+[:len "from"]+1) [:len $string]]
			:if ([:len [:find $cut " "]]>0) do={
				:return [:pick $cut 0 [:find $cut " "]]
			} else={
				:return [:pick $cut 0 [:len $cut]]
			}
		} else={
			:if ([:len $default]>0) do={
				:return $default
			} else={
				:return ""
			}
		}
	}
	#read value from string
	:local getKeyValue do={
		:if ([:type [:find $string $name]]!="nil") do={
			:local cut [:pick $string ([:find $string $name]+[:len $name]+1) [:len $string]]
			:if ([:len [:find $cut ";"]]>0) do={
				:return [:pick $cut 0 [:find $cut ";"]]
			} else={
				:return [:pick $cut 0 [:len $cut]]
			}
		} else={
			:if ([:len $default]>0) do={
				:return $default
			} else={
				:return ""
			}
		}
	}
	#set key and value to string
	:local setKeyValue do={
		:if ([:typeof [:find $string $name]]!="nil") do={
			:local current
			:local cut [:pick $string ([:find $string $name]) [:len $string]]
			:if ([:len [:find $cut ";"]]>0) do={
				:set current [:pick $cut 0 [:find $cut ";"]]
			} else={
				:set current [:pick $cut 0 [:len $cut]]
			}
			:return ([:pick $string 0 [:find $string $current]]."$name=$value".[:pick $string ([:find $string $current]+[:len $current]) [:len $string]])
		} else={
			:if (([:len $value]>0) and ([:len $name]>0)) do={
				:if (([:len $string]=0) or ([:pick $string ([:len $string]-1) [:len $string]]=";")) do={
					:return ($string."$name=$value;")
				} else={
					:return ($string.";$name=$value;")
				}
			} else={
				:return ($string)
			}
		}
	}
	#del key and value to string
	:local delKeyValue do={
		:if ([:typeof [:find $string $name]]!="nil") do={
			:local current
			:local cut [:pick $string ([:find $string $name]) [:len $string]]
			:if ([:len [:find $cut ";"]]>0) do={
				:set current [:pick $cut 0 [:find $cut ";"]]
			} else={
				:set current [:pick $cut 0 [:len $cut]]
			}
			:return ([:pick $string 0 [:find $string $current]].[:pick $string ([:find $string $current]+[:len $current]+1) [:len $string]])
		} else={
			:return ($string)
		}
	}
	#check log for "login failures"
	:local retry
	:global loginFailures
	:foreach index in=[/log find where buffer=login message~"login failure" and message~"from"] do={
		:set retry [:tonum [$getKeyValue string=$loginFailures name=[$getIP string=[/log get $index message]]]]
		:if (($retry+1)>=$attempt) do={
			/ip firewall address-list add address=[$getIP string=[/log get $index message]] list=login_failure comment=([/log get $index message].", added at ".[/system clock get date]." ".[/system clock get time]) timeout=1d
			:set loginFailures [$delKeyValue string=$loginFailures name=[$getIP string=[/log get $index message]]]
		} else={
			:if ([:len [/ip firewall address-list find where address=[$getIP string=[/log get $index message]] and list=login_failure]]=0) do={
				:set loginFailures [$setKeyValue string=$loginFailures name=[$getIP string=[/log get $index message]] value=($retry+1)]
			}
		}
	}
	#clear log
	/system logging disable [find action=login]
	/system logging enable [find action=login]
	:if ([:len $loginFailures]=0) do={
		/system script environment remove loginFailures
	}
	:if ([:len [/ip firewall filter find comment="block address that reach maximum login attempts"]]=0) do={
		/ip firewall filter add chain=input src-address-list=login_failure action=drop comment="block address that reach maximum login attempts"
	}
}
Last edited by zivtal on Thu Feb 07, 2019 9:21 pm, edited 3 times in total.
 
User avatar
anav
Forum Guru
Forum Guru
Posts: 19100
Joined: Sun Feb 18, 2018 11:28 pm
Location: Nova Scotia, Canada
Contact:

Re: How to block SSH attackers after 3 bad logins?

Thu Feb 07, 2019 8:38 pm

Wow things can get complex rather quickly.

If your not using SSH on the router at all, incoming or outgoing,
Simply put it in raw. Same with FTP,,,,,,,
/ip firewall raw
add chain=prerouting dst-port=common_ssh_port action=drop

/ip firewall raw
add chain=prerouting dst-port=common_Ftp_port action=drop

Not sure but perhaps it can be one rule
/ip firewall raw
add chain=prerouting dst-ports=20,21,22,23, 139 action=drop

For all the ports you do use and are concerned about why not (after established, related)
ex forward filter
add chain=forward dst-port=53 in-interface-list=WAN action= add source address to address list address list=dropbadguys
timeout=6hrs

Then in raw
add chain=prerouting source-address-list=dropbadguys action=drop
 
zivtal
Frequent Visitor
Frequent Visitor
Posts: 57
Joined: Sun Feb 05, 2017 6:22 pm

Re: How to block SSH attackers after 3 bad logins?

Thu Feb 07, 2019 9:12 pm

Wow things can get complex rather quickly.

If your not using SSH on the router at all, incoming or outgoing,
Simply put it in raw. Same with FTP,,,,,,,
/ip firewall raw
add chain=prerouting dst-port=common_ssh_port action=drop

/ip firewall raw
add chain=prerouting dst-port=common_Ftp_port action=drop

Not sure but perhaps it can be one rule
/ip firewall raw
add chain=prerouting dst-ports=20,21,22,23, 139 action=drop

For all the ports you do use and are concerned about why not (after established, related)
ex forward filter
add chain=forward dst-port=53 in-interface-list=WAN action= add source address to address list address list=dropbadguys
timeout=6hrs

Then in raw
add chain=prerouting source-address-list=dropbadguys action=drop
I'm not understanding, today I made my script quickly because this is the 1st time I see someone try connect to my mikrotik api, about 999 times... If you have port that you are using such mikrotik api how you block addresses that try to hack your router?
 
User avatar
anav
Forum Guru
Forum Guru
Posts: 19100
Joined: Sun Feb 18, 2018 11:28 pm
Location: Nova Scotia, Canada
Contact:

Re: How to block SSH attackers after 3 bad logins?

Thu Feb 07, 2019 9:29 pm

Hi Zivital, good question.........
First of all, I don't have any access to my router from external sources.
If I did it would be through VPN only.

As for services you use API for example or SSH or winbox, the first thing I would do is change to a non-standard port if possible.

Lets say you need to be able to use API port traffic
then in ip firewall filter
INPUT - after accept established related
add chain=input dst-port=api_port in-interface-list=WAN action=add source address list to address list=badguys timeout=6 hours
FORWARD - after accept established related
add chain=forward dst-port=api_port in-interface-list=WAN action=add source address list to address list=badguys timeout=6 hours

/ip raw
add chain=prerouting src-address-list=badguys action=drop

My thinking is as follows, more than likely the badguys will be probing many ports and thus my initial raw rule should catch most of them....
/ip raw
add chain=prerouting in-interface-list=WAN dst-ports= LIST ALL COMMON PORTS NOT USED ON YOUR DEVICE in our out (could be 20, 21,22, 23 139, etc.......) action= add to source address list, address-list=badguys timeout=6 hours.

In other words, we have one capture rule in raw, for all common ports not being or likely to be used on your router, thus statelessness doesnt matter. This should stop most of it.
Then we drop them in raw also. Least drag on CPU.

For badguys that do not blanket probe but specifically probe ports we do use, then we catch them in filter rules after our authorized usage of same ports occurs, and then we drop them in raw.

makes sense??
 
zivtal
Frequent Visitor
Frequent Visitor
Posts: 57
Joined: Sun Feb 05, 2017 6:22 pm

Re: How to block SSH attackers after 3 bad logins?

Thu Feb 07, 2019 9:42 pm

Hi Zivital, good question.........
First of all, I don't have any access to my router from external sources.
If I did it would be through VPN only.

As for services you use API for example or SSH or winbox, the first thing I would do is change to a non-standard port if possible.

Lets say you need to be able to use API port traffic
then in ip firewall filter
INPUT - after accept established related
add chain=input dst-port=api_port in-interface-list=WAN action=add source address list to address list=badguys timeout=6 hours
FORWARD - after accept established related
add chain=forward dst-port=api_port in-interface-list=WAN action=add source address list to address list=badguys timeout=6 hours

/ip raw
add chain=prerouting src-address-list=badguys action=drop

My thinking is as follows, more than likely the badguys will be probing many ports and thus my initial raw rule should catch most of them....
/ip raw
add chain=prerouting in-interface-list=WAN dst-ports= LIST ALL COMMON PORTS NOT USED ON YOUR DEVICE in our out (could be 20, 21,22, 23 139, etc.......) action= add to source address list, address-list=badguys timeout=6 hours.

In other words, we have one capture rule in raw, for all common ports not being or likely to be used on your router, thus statelessness doesnt matter. This should stop most of it.
Then we drop them in raw also. Least drag on CPU.

For badguys that do not blanket probe but specifically probe ports we do use, then we catch them in filter rules after our authorized usage of same ports occurs, and then we drop them in raw.

makes sense??
I'm trying to understand how it's decide who is badgay and who is legal connection ,,,...
 
User avatar
anav
Forum Guru
Forum Guru
Posts: 19100
Joined: Sun Feb 18, 2018 11:28 pm
Location: Nova Scotia, Canada
Contact:

Re: How to block SSH attackers after 3 bad logins?

Thu Feb 07, 2019 10:14 pm

Well, for ports you will not use on your router, it doesnt matter if the incoming traffic is coming from a bad guy originating, or is in response to router outgoing traffic that is being returned on said port presumably by a bad guy. Its an unauthorized port. So raw works being stateless.

As for the ports you do use............ outbound from the router and with return traffic, the port traffic is legit.
So basically we state if the port traffic is coming into the router (input) or coming across the router (forward) and has not already been identified/matched as established and related and thus accepted/passed on, then it must be badguy traffic!!!

The only time this approach would not work is for is possibly dstnat traffic, where we want originating external traffic to get through on specific ports.
If you have 'open servers' on your lan network then its more challenging.
I think open servers are a bad idea because ports are visible on scans but are reported as closed.
The magic solution for dst-nat traffic is to, if at all possible, to use source-address-list!!!
In other words if you know who (external public IP) is going to need access to the lan server then put that IP into a source address list.
The interesting byproduct of adding a source address list on the NAT RULE is that the port is no longer seen on scans, its not visible at all. Real cool!


Then in the forward filter rule you have
add chain=forward action=accept connection-nat-state=dstnat source-address-list=authorized ( followed by)
add chain=forward action=add to address list address-list=badguys dst-ports=(ports-you-use) timeout=6hrs

The one scenario as you may have guessed is what happens when you dont know the legitimate external public IPs coming to your server.
Could be from smartphones, dynamic IP addresses etc........................
The NAT rule will let any source IP be routed to the lan server
The firewall rule will let any IP through the forward filter rule
The only defence is the username and login on the server itself.
In this case, perhaps assuming repeated attempts on that server and destination port is where the number of attempts (hacking the username and password) rule noted earlier in the thread will be of use????
 
User avatar
anav
Forum Guru
Forum Guru
Posts: 19100
Joined: Sun Feb 18, 2018 11:28 pm
Location: Nova Scotia, Canada
Contact:

Re: How to block SSH attackers after 3 bad logins?

Thu Feb 07, 2019 10:34 pm

TERM
I don't need to access to my mikrotik from outside (using VPN).
(1) But I want to see in some lists that somebody tried to access to my mikrotik from outside. Is there any way?
(2) karlisi: thank you but I don't want to have a lot of lists in firewall. All I want is block user after 3 failed logins and add him to list for 10 days
+++++++++++++++++++++++++++++++
(1) Yes, you can log all the hits from the WAN as follows.
Input chain Last Two rules
add chain=input in-interface-list=WAN action=log prefix="Show ALL INPUT Traffic From WAN Being Dropped"
add chain=input action=drop

Forward Chain Last Two rules
add chain=forward in-interface-list=WAN action=log prefix="Show ALL FORWARD Traffic FROM WAN Being Dropped"
add chain=forward action=drop

(2) Well since you don't need external access to the router, then you could add all addresses from the two rules above and drop them in RAW.
You would not need to see the log which would quickly fill up anyway as you could then view the lists in the ip firewall address list tables..........

last rules input chain
add chain=input in-interface-list-WAN action=add to address list address-list=badguys timeout=6 hours
add chain=input action=drop

last rule forward chain
add chain=forward in-interface-list-WAN action=add to address list address-list=badguys timeout=6 hours
add chain=forward action=drop

In RAW
/ip raw
add chain=prerouting source-address-list=badguys action=drop

As to rapid attempts,,,,,,,,,,,,,,, the first attempt would get collected so attempts after that are moot.
If you ONLY wanted to stop rapid attempts then you would need a specific rule vice catch all..........
I just dont know how to setup the specific rule.

add input rule catch rapid attempts from wan list=rapidhackers
drop all

add forward rule catch rapid attempts from wan list=rapidhackers
drop all

raw - prerouting drop all 'rapidhackers'

The parameters for a specific rule seem to be either connection limit, OR psd parameters.
Perhaps some experts can speak eloquently on how to use either or or both sets of parameters (connections and psd)
to catch
a. flooding
b. scanning
c. hacking attempts (assume username/password)
 
freemannnn
Forum Veteran
Forum Veteran
Posts: 700
Joined: Sun Oct 13, 2013 7:29 pm

Re: How to block SSH attackers after 3 bad logins?

Mon Apr 20, 2020 9:32 pm

I made this script, You should add scheduler every 5-10 minutes it's check if you had login failure more then 5 times from same ip it's automatically add the ip to block list.

If you want only 3 attempts you can change the line: ":local attempt 5" to ":local attempt 3"
#check if logging action exists, if not create action
:if ([:len [/system logging action find name=login]]=0) do={
	/system logging action add name=login target=memory
} 
#check if logging rule exists, if not create rule
:if ([:len [/system logging find action=login]]=0) do={
	/system logging add topics=system,error,critical action=login
}
#login failure attempts
:local attempt 5
:if ([:len [/log find where buffer=login message~"login failure" and message~"from"]]>0) do={
	#get IP from log
	:local getIP do={
		:if ([:type [:find $string "from"]]!="nil") do={
			:local cut [:pick $string ([:find $string "from"]+[:len "from"]+1) [:len $string]]
			:if ([:len [:find $cut " "]]>0) do={
				:return [:pick $cut 0 [:find $cut " "]]
			} else={
				:return [:pick $cut 0 [:len $cut]]
			}
		} else={
			:if ([:len $default]>0) do={
				:return $default
			} else={
				:return ""
			}
		}
	}
	#read value from string
	:local getKeyValue do={
		:if ([:type [:find $string $name]]!="nil") do={
			:local cut [:pick $string ([:find $string $name]+[:len $name]+1) [:len $string]]
			:if ([:len [:find $cut ";"]]>0) do={
				:return [:pick $cut 0 [:find $cut ";"]]
			} else={
				:return [:pick $cut 0 [:len $cut]]
			}
		} else={
			:if ([:len $default]>0) do={
				:return $default
			} else={
				:return ""
			}
		}
	}
	#set key and value to string
	:local setKeyValue do={
		:if ([:typeof [:find $string $name]]!="nil") do={
			:local current
			:local cut [:pick $string ([:find $string $name]) [:len $string]]
			:if ([:len [:find $cut ";"]]>0) do={
				:set current [:pick $cut 0 [:find $cut ";"]]
			} else={
				:set current [:pick $cut 0 [:len $cut]]
			}
			:return ([:pick $string 0 [:find $string $current]]."$name=$value".[:pick $string ([:find $string $current]+[:len $current]) [:len $string]])
		} else={
			:if (([:len $value]>0) and ([:len $name]>0)) do={
				:if (([:len $string]=0) or ([:pick $string ([:len $string]-1) [:len $string]]=";")) do={
					:return ($string."$name=$value;")
				} else={
					:return ($string.";$name=$value;")
				}
			} else={
				:return ($string)
			}
		}
	}
	#del key and value to string
	:local delKeyValue do={
		:if ([:typeof [:find $string $name]]!="nil") do={
			:local current
			:local cut [:pick $string ([:find $string $name]) [:len $string]]
			:if ([:len [:find $cut ";"]]>0) do={
				:set current [:pick $cut 0 [:find $cut ";"]]
			} else={
				:set current [:pick $cut 0 [:len $cut]]
			}
			:return ([:pick $string 0 [:find $string $current]].[:pick $string ([:find $string $current]+[:len $current]+1) [:len $string]])
		} else={
			:return ($string)
		}
	}
	#check log for "login failures"
	:local retry
	:global loginFailures
	:foreach index in=[/log find where buffer=login message~"login failure" and message~"from"] do={
		:set retry [:tonum [$getKeyValue string=$loginFailures name=[$getIP string=[/log get $index message]]]]
		:if (($retry+1)>=$attempt) do={
			/ip firewall address-list add address=[$getIP string=[/log get $index message]] list=login_failure comment=([/log get $index message].", added at ".[/system clock get date]." ".[/system clock get time]) timeout=1d
			:set loginFailures [$delKeyValue string=$loginFailures name=[$getIP string=[/log get $index message]]]
		} else={
			:if ([:len [/ip firewall address-list find where address=[$getIP string=[/log get $index message]] and list=login_failure]]=0) do={
				:set loginFailures [$setKeyValue string=$loginFailures name=[$getIP string=[/log get $index message]] value=($retry+1)]
			}
		}
	}
	#clear log
	/system logging disable [find action=login]
	/system logging enable [find action=login]
	:if ([:len $loginFailures]=0) do={
		/system script environment remove loginFailures
	}
	:if ([:len [/ip firewall filter find comment="block address that reach maximum login attempts"]]=0) do={
		/ip firewall filter add chain=input src-address-list=login_failure action=drop comment="block address that reach maximum login attempts"
	}
}

thank you for this working+nice script. i was looking for it so long. i tested and it working nice (6.46.4). please keep us updated if there is a newer version of the script. your script even automatically adds the things needed in logging/rules-action and also rule needed in ip/firewall/filter to block address-list. very nice. thank u.
my changes where...

1.i removed timeout=1d because i want to block forever failure logins.
/ip firewall address-list add address=[$getIP string=[/log get $index message]] list=login_failure comment=([/log get $index message].", added at ".[/system clock get date]." ".[/system clock get time])

2. "place-before=1" so the rule will placed over the rule that i accept winbox.
/ip firewall filter add chain=input src-address-list=login_failure action=drop comment="block address that reach maximum login attempts" place-before=0

3. ":local attempt 3"
Last edited by freemannnn on Mon Mar 15, 2021 9:11 pm, edited 1 time in total.
 
User avatar
paalbo
just joined
Posts: 2
Joined: Fri May 29, 2020 8:22 pm

Re: How to block SSH attackers after 3 bad logins?

Fri May 29, 2020 9:05 pm

Hi all.
This rules I have on my Mikrotik Router and they work. But is there a way to do this for RDP also?
Have tried to apply this rules to RDP but doesn't seem to work.
I have the normal drop ssh brute forcers and based on ssh_stage1 - 3 address lists and then it goes to a ssh_blacklist.
But if I try to apply this to RDP and want to base it on time instead of stages how would I make a rule that work for the RDP. And no I'm not using the standard port for RDP 3389.
Example if I based it on stages then after 3 times it will go to blacklist. I experience that this happens if you suddenly get disconnected from the RDP server and try to reconnect the my IP gets blacklisted. Instead I would like so that if a hacker tries to get access and this is often done like connecting trying username and password and the get disconnected and this all over again. I would be nice if a rule could detect failed attempts on logging in and after 5 failed loggins get blacklisted. Is this possible?
 
User avatar
Jotne
Forum Guru
Forum Guru
Posts: 3291
Joined: Sat Dec 24, 2016 11:17 am
Location: Magrathean

Re: How to block SSH attackers after 3 bad logins?

Mon Jun 01, 2020 8:15 am

If you do not access your router from outside using SSH and there are not NAT rules for SSH, you do not need to worry to much. They will not get inn to you.

Here is what I do. If your try one port on my outside that are not open, example port 22, then your IP will go to a black list and stay there for 24 hours. When you are in the black list, you are blocked on all port on my router. Even the one that are normally open like 443 web server. If you try to access a non open port, I guess you are a script that scans my router and do not need anything from me. Many of these automatic scripts, starts with new script when an open port is found to check for vulnerabilities.

I do off course log this attach, so I can later see how many are blocked. There are at any given time around 2000-15000 IP in the blocked access list. Se my signature on how to log this.
 
helipos
Member Candidate
Member Candidate
Posts: 132
Joined: Sat Jun 25, 2016 11:32 am

Re: How to block SSH attackers after 3 bad logins?

Sat Jan 02, 2021 2:53 pm

Zivtal, just wanted to say, very nice code.
 
User avatar
kehrlein
newbie
Posts: 48
Joined: Tue Jul 09, 2019 1:35 am

Re: How to block SSH attackers after 3 bad logins?

Sun Oct 10, 2021 7:59 pm

I made this script, You should add scheduler every 5-10 minutes it's check if you had login failure more then 5 times from same ip it's automatically add the ip to block list.

Great script, Zivtal! Thank you very much!!

Who is online

Users browsing this forum: syslog and 45 guests