Skip to content

Instantly share code, notes, and snippets.

@curlup
Forked from jeremyj/haproxy rate limiting
Created January 23, 2018 10:24
Show Gist options
  • Save curlup/a38a94a5c9cf8c714a762e5da79ca071 to your computer and use it in GitHub Desktop.
Save curlup/a38a94a5c9cf8c714a762e5da79ca071 to your computer and use it in GitHub Desktop.
haproxy rate limiting
HTTP request limiting ===================================================================================================================
frontend ft_web
# Use General Purpose Couter (gpc) 0 in SC1 as a global abuse counter
# Monitors the number of request sent by an IP over a period of 10 seconds
stick-table type ip size 1m expire 10s store gpc0,http_req_rate(10s)
tcp-request connection track-sc1 src
# refuses a new connection from an abuser
tcp-request content reject if { src_get_gpc0 gt 0 }
# returns a 403 for requests in an established connection
http-request deny if { src_get_gpc0 gt 0 }
backend bk_web
# If the source IP sent 10 or more http request over the defined period,
# flag the IP as abuser on the frontend
acl abuse src_http_req_rate(ft_web) ge 10
acl flag_abuser src_inc_gpc0(ft_web) ge 0
# Returns a 403 to the abuser
http-request deny if abuse flag_abuser
general connection limiting 2 ===================================================================================================================
frontend ft_web
# table used to store behaviour of source IPs
stick-table type ip size 200k expire 5m store gpc0,conn_rate(10s),http_req_rate(10s)
# IPs that have gpc0 > 0 are blocked until the go away for at least 5 minutes
acl source_is_abuser src_get_gpc0 gt 0
tcp-request connection reject if source_is_abuser
# connection rate abuses get blocked
acl conn_rate_abuse sc1_conn_rate gt 30
acl mark_as_abuser sc1_inc_gpc0 ge 0
tcp-request connection track-sc1 src
tcp-request connection reject if conn_rate_abuse mark_as_abuser
===================================================================================================================
# table used to store behaviour of source IPs
stick-table type ip size 999k expire 3m store gpc0,conn_rate(10s)
acl ip_whitelist src -f /etc/haproxy/whitelist.ip
acl source_is_abuser src_get_gpc0(proxy-01) gt 0
tcp-request connection reject if source_is_abuser !ip_whitelist
acl conn_rate_abuse sc1_conn_rate(proxy-01) gt 30
acl mark_as_abuser sc1_inc_gpc0(proxy-01) gt 0
tcp-request connection track-sc1 src
tcp-request connection reject if conn_rate_abuse !ip_whitelist mark_as_abuser
================================================================================================
$ echo "show table http_proxy data.gpc0 gt 0" \
| socat stdio /tmp/sock1 \
| fgrep 'key=' | cut -d' ' -f2 | cut -d= -f2 > abusers-ip.txt
( or | awk '/key/{ print a[split($2,a,"=")]; }' )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment