HAProxy: Restrict access by IP address
Crude way to stop an attack in case of an emergency.
Keep in mind that this is a static configuration, which is not very effective against adversarial attacks when an attacker constantly changes their tactics.
By default HAProxy configuration file is located at /etc/haproxy/haproxy.cfg
. To block a single IP address we can use a conditional http-request deny
directive.
http-request deny if { src 8.8.8.8/32 }
If we need to apply it to a given endpoint we can use the keyword path
.
http-request deny if { path -i -m beg /login } { src 8.8.8.8/32 }
Note that the IP address is in the CIDR notation, we can use it to restrict the access to an entire subnet. Adding !
will invert the rule and allow the access to a given subnet, restricting it to the rest.
http-request deny if { path -i -m beg /login } !{ src 8.8.8.0/24 }
Managing a denylist
HAProxy allows to store the list of IP addresses in a separate file on the filesystem. Each IP address separated by a newline.
# cat blocked.ips
8.8.8.8
12.12.12.0/24
Then we can include them into the configuration file
http-request deny if { path -i -m beg /login } { src -f /etc/haproxy/blocked.ips }
Applying restrictions on TCP level
If we want to apply the restrictions deeper in the stack we can use tcp-request connection reject
for that.
tcp-request connection reject if { src 8.8.8.8/32 }
Applying configuration
service haproxy check
to test the validity of the configuration file.
service haproxy reload
to reload the config.