Nginx – Rate limit new connections in IPTables instead of Nginx or HAProxy

firewallhaproxyiptablesnginx

I would like to use some form of rate-limiting both 1) new TCP connections and 2) requests over an existing connection to HTTP(S). I will probably handle #2 with nginx or HAProxy (because I have more information about the user's history there).

However, I would like to prevent DoS (not DDos) with IPtables and save HAProxy or Nginx some load dealing with new TCP connections. It seems IPTables would be best suited to this job.

# Allow unlimited 80 traffic from our own network (duplicate this line for other local subnets)
# 192.168.16.0 - 192.168.16.255
-A INPUT -p tcp --dport 80 -s 192.168.1.0/24 -j ACCEPT

# Simple, single-IP DoS protection 
# Per-minute: Allow up to 200 new connections (packets) from an IP before rate-limiting to 50 packets is applied
# This could need to be an ISP, company, or college where 200 clients all connected from a single IP gateway
# in 1 minute and started using your service. After that first minute 50 more can join every minute.
-A INPUT -p tcp --dport 80 -m state --state NEW -m limit --limit 50/minute --limit-burst 200 -j ACCEPT
-A INPUT -p tcp --dport 443 -m state --state NEW -m limit --limit 50/minute --limit-burst 200 -j ACCEPT

Is this a good idea, or should I just do both types of rate limiting (new/established) at the nginx or HAproxy level?

(Note: I don't have access to an actual hardware firewall which is designed to handle this)

Best Answer

Personally I would rate limit only for specific TCP packets (syn flood, scans of various types, etc) with iptables and use nginx to rate limit HTTP requests per time interval behind this.

Keep in mind that browsers open multiple TCP connections for a single actual user so rate limiting to 50 connections per minute once the burst is reached is dramatically low and may cause trouble for people behind proxies.

Furthermore, nothing proves that a remote client establishing a TCP connection will send a request if you filter only on the NEW state in iptables rules. That means anyone that has access to an infrastructure not honoring ingress/egress filtering best practices can SYN flood your service with spoofed IPs thus degrading the service for specific targets, for instance mobile phone APs of famous companies.

Related Topic