The other day, I had an issue with a client spoofing their IP address. The bot in question was able to do this by manually specifying the “X-Forwarded-For” header in its request.
Fortunately, HAProxy provides an easy method to strip this header from the request.
X-Forwarded-For and HAProxy.
If you use HAProxy as a load balancer, then it is fair to say that you rely on the X-Forwarded-For header to get the user’s IP address. This is because the IP that is accessing your web server belongs to HAProxy. It doesn’t belong to the client.
Unfortunately, this header can be easily spoofed. If a client adds a fake IP address to the X-Forwarded-For header, HAProxy’s default behavior is to pass it on to your web server. This means that the client can fool your web server into thinking the request came from a different IP address.
Preventing IP spoofing with HAProxy.
Thankfully, there is an easy way to put a stop to this.
Essentially, we need to configure HAProxy to strip the header from the client’s request. i.e. If a client sends us the header, our load balancer will remove it.
In your defaults section of your configuration file, you should have the following:
The forwardfor option tells HAProxy to send the X-Forwarded-For header to your backend web server. This is important, as without it, our servers won’t have access to the client’s IP address.
In your frontend definition (or your listen section), you will need to add the following:
The reqidel option allows us to delete any request header that matches a regular expression. In the line above, we are saying that we want to delete anything that could be construed as an X-Forwarded-For header.
To put it into plain English: We are telling our load balancer to remove the fake IP address so that it can insert the correct one.
Hopefully, this solved your issue.