DDoS Detection and Blocking
This is the way to prevent (D)DoS Attack from your users to attacked resources, and drop (D)DoS directed to your clients.
First, we catch all new connections and send them to dedicated firewall chain:
/ip firewall filter add chain=forward connection-state=new action=jump jump-target=detect-ddos
Note: At least in v5.7 and earlier versions, any single UDP packet is considered to be new connection by Connection Tracking in any Firewall section except NAT - support said, it will be fixed in future versions... Before the fix, be careful - uTorrent's or Skype's UDP stream can be detected as DoS Attack.
Then, for each "SrcIP:DstIP" pair we allow some number of new connections. One may want also add some exceptions (like DNS servers - it won't be good if they will be blocked):
/ip firewall filter add chain=detect-ddos dst-limit=32,32,src-and-dst-addresses/10s action=return add chain=detect-ddos src-address=192.168.0.1 action=return
Note: At least up to version 5.6, 'dst-limit' matcher has two bugs:
- 'Expire' value is 10 times lower than you set; so '10s' is actually 1 second
- 'dst-limit' matches first 'Burst' packets (as it should be) plus one, and then skips packets for the first second; so if you have Rate set to 32 and Burst set to 0, and you start to flood packets, the rule will match 1 packet, and on 2nd packet it won't match until 1sec passes - that's why you need 'Burst' value at least as high as 'Rate' value
Now, we have only packets which exceed our limits - and we add their source to 'ddoser' and the target to 'ddosed' address lists:
/ip firewall filter add chain=detect-ddos action=add-dst-to-address-list address-list=ddosed address-list-timeout=10m add chain=detect-ddos action=add-src-to-address-list address-list=ddoser address-list-timeout=10m
Then packet processing returns to 'forward' chain, where we block any packets from ddosers to ddosed resources:
/ip firewall filter add chain=forward connection-state=new src-address-list=ddoser dst-address-list=ddosed action=drop