Simple DDOS Protection for you APIS
Install NGINX & Fail2ban
$sudo apt install nginx fail2ban
2. Create a simple nginx config that just proxies your API
$sudo nano /etc/nginx/sites-enabled/default
delete all. copy paste this one
server {
listen 80;
listen [::]:80;
server_name _;
location /api_proxy/ {
proxy_pass http://localhost:9090/api/v1/;
proxy_buffering off;
}
}
Where localhost:9090/api/v1/ is your local server, node, go, java, whatever
Test if everything works by calling http://server_ip/api_proxy/
Now that we got this out of the way, next step is configuring it
Configure nginx with rate limiting
Rate limiting, which can be effectively used to limit the amount of requests a user can make in a given period of time.
Rate limiting can be used for security purposes and it can greatly help you to protect our website against DDoS attacks by limiting the incoming request rate to a value typical for real users, and (with logging) identify the targeted URLs. Now that we have logging, we can create a filter in fail2ban, but let’s test the rate limiting first.
Update the nginx config to
limit_req_zone $request_uri zone=by_uri:10m rate=1r/s;
server {
listen 80;
listen [::]:80;
server_name _;
location /api_proxy/ {
limit_req zone=by_uri burst=5;
proxy_pass http://localhost:9090/api/v1/;
proxy_buffering off;
}
}
Test if everything works by calling http://server_ip/api_proxy/ and hit REFRESH button as fast as possible. You should get service unavailable from time to time
Configure fail2ban
create a new filter file
nano/etc/fail2ban/filter.d/nginx-req-limit.conf
with the following content:
# Fail2Ban configuration file
#
# supports: ngx_http_limit_req_module module
[Definition]
failregex = limiting requests, excess:.* by zone.*client: <HOST>
# Option: ignoreregex
# Notes.: regex to ignore. If this regex matches, the line is ignored.
# Values: TEXT #
ignoreregex =
cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
and add the following at the end
[nginx-req-limit]
enabled = true
filter = nginx-req-limit
action = iptables-multiport[name=ReqLimit, port=”http,https”, protocol=tcp]
logpath = /var/log/nginx/*error.log
findtime = 600
bantime = 20
maxretry = 10
restart fail2ban $sudo service fail2ban restart
Try some tests and check
fail2ban-client status nginx-req-limit
After that you can increase the ban time to something like: 7200 and increase the number of requests per second in nginx to 10/s (or whatever value suits you)
Congratulations! Now those hackers won’t take your API down.
You saved those $20 per month for Cloudflare :)