Black Fedora
Anti-Abuse for Developers

Anti-Abuse for Developers

HAProxy: Restrict access by IP address

Crude way to stop an attack in case of an emergency.

Black Fedora's photo
Black Fedora
·Apr 2, 2022·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

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 }

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 }

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 }

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

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 }

Applying configuration

service haproxy check

to test the validity of the configuration file.

service haproxy reload

to reload the config.

Share this