You may have experienced that situation where your VPS feels slow or unresponsive and you think, "Is someone attacking my server again?" I have been there too. The good news is that rate-based firewall rules address this situation quickly. They will cutoff traffic from bad actors and allow real users back into your site. I am going to walk you through how to do this simply.
nft flush ruleset
I will first just add a table and a chain.
How Rate Limits Assist
I have always said this; don't the bots push your server around. When the bogus requests are hitting your VPS, your CPU is busy for no good reason. Rate limits prevent this by only allowing a certain number of requests per second. Have you ever hosted a database or website or stream without limits? It quickly spirals out of control.Basic Setup
Before the rules are added, I remove everything first into a blank ruleset. This helps to keep it simple.nft flush ruleset
I will first just add a table and a chain.
- nft add table inet filter
- nft add chain inet filter input { type filter hook input priority 0; }
Creating Rate-Based Rules
Now we come to the good stuff: controlling new connections. I really like how simple it is to create this with nftables, step-by-step:- nft add rule inet filter input tcp dport 22 ct state new limit rate 5/second accept
- nft add rule inet filter input tcp dport 22 drop
- Allows 5 new SSH connections per second
- Drops all the rest
Creating Rate Limit Rules for Websites (HTTP/HTTPS)
Do you run a website? You can safely limit incoming connections:- nft add rule inet filter input tcp dport {80,443} limit rate 200/second accept
- nft add rule inet filter input tcp dport {80,443} drop
Additional Features
You can fortify your firewall further with:- Connection tracking rules
- IP sets to protect against repeat attackers
- Logging rules (although use logging lightly)