How to fake or spoof x-forwarded-for header

The x-forwarded-for header is a way of identifying the IP address of the original client when a web server is sitting behind a proxy or load-balancer. The load-balancer does get the actual client IP as it directly sets up the TCP session with the load-balancer. But the x-forwarded-for address might contain a list of comma separated IP addresses in addition to the immediate client IP. It is these extra IPs that we can spoof and the procedure is similar to modifying any HTTP header such as user agent.

import requests
headers={'X-Forwarded-For':'1.1.1.1'}
r = requests.get('http://web.home.net/index.html', headers=headers)
if r.ok:
    print('Success.')

How the log likes like on an nginx access log –

1.1.1.1, 192.168.10.206 - - [19/Mar/2017:16:43:55 -0700] "GET /index.html HTTP/1.0" 200 1311 "-" "python-requests/2.2.1 CPython/2.7.6 Linux/3.13.0-121-generic"
1.1.1.1, 192.168.10.206 - - [19/Mar/2017:16:53:55 -0700] "GET /index.html HTTP/1.0" 200 1311 "-" "python-requests/2.2.1 CPython/2.7.6 Linux/3.13.0-121-generic"
1.1.1.1, 192.168.10.206 - - [19/Mar/2017:16:58:55 -0700] "GET /index.html HTTP/1.0" 200 1311 "-" "python-requests/2.2.1 CPython/2.7.6 Linux/3.13.0-121-generic"

The take away is not to trust any IPs in the x-forwarded-for list apart from the load balancer IP and the immediate client IP which made a direct call to the load balancer. If we trust our load balancer, we can also reliably identify the immediate client IP. The rest of the IPs in the x-forwarded-for list can be ignored.

References –

https://en.wikipedia.org/wiki/X-Forwarded-For