On Thu, Mar 24, 2011 at 04:35:57PM -0400, bradford wrote:
> I know there have been several emails about this, but what is the most
> secure way of logging the client's IP address in the application code?
> Do you just log the full X-Forwarded-For comma delimited value?
> Also, can't they manipulate the X-Forwarded-For header in the HTTP
> request?
Anyone can manipulate it. However, standards are clear : when headers
are folded into one, the order must be respected. If a product such as
haproxy, squid, nginx, apache or whatever says that when it sets the
IP address in x-forwarded-for, it APPENDS it, it means that the IP will
always be the last one in the list when going out of that product.
Thus here's what the application should do :
- get the list of values in the same order they appear.
- take the last value, or last-1, or last-2, etc... depending
on the number of proxies in the infrastructure.
Here's an example :
client ---> rproxy1 (cache) ---> rproxy2 (LB) ---> app server
Let's say the client goes out through a proxy farm and already presents :
X-Forwarded-For: 192.168.0.1, 172.16.0.1
The client reaches rproxy1 with IP 11.11.11.11. Rproxy1 then appends
this value to the list. Let's say it adds it to the end of the list,
out of rproxy1 you'd have :
X-Forwarded-For: 192.168.0.1, 172.16.0.1, 11.11.11.11
Now consider rproxy1 has 192.168.2.1, and rproxy2 adds its IP to the
list, this time using a separate line. After it, you'll get :
X-Forwarded-For: 192.168.0.1, 172.16.0.1, 11.11.11.11
X-Forwarded-For: 192.168.2.1
This request reaches the app server. Depending on the framework used,
maybe the list will automatically be folded by the application server,
maybe you'll get raw headers and will have to concat them yourself.
Anyway, you now have this list :
192.168.0.1, 172.16.0.1, 11.11.11.11, 192.168.2.1
Your app server knows that it is behind two reverse proxies, so it will
take not the last entry, but the (N-1)th, which is 11.11.11.11. The
former ones are useless, because they were presented by the client.
However sometimes it might be worth logging them because in case of
litigation it might help an admin on the other site to discover that
some action was not performed by the person you think, for instance.
Hoping this helps,
Willy