Permalink
Browse files

support ip lists in X-Forwarded-For headers

  • Loading branch information...
1 parent d80fa56 commit e23cbd4769b8a6e37abe80f849275559399c3aeb @davidwilemski davidwilemski committed Apr 18, 2013
Showing with 18 additions and 1 deletion.
  1. +3 −1 tornado/httpserver.py
  2. +15 −0 tornado/test/httpserver_test.py
View
@@ -431,8 +431,10 @@ def __init__(self, method, uri, version="HTTP/1.0", headers=None,
# xheaders can override the defaults
if connection and connection.xheaders:
# Squid uses X-Forwarded-For, others use X-Real-Ip
+ ip = self.headers.get("X-Forwarded-For", self.remote_ip)
+ ip = ip.split(',')[-1].strip()
ip = self.headers.get(
- "X-Real-Ip", self.headers.get("X-Forwarded-For", self.remote_ip))
+ "X-Real-Ip", ip)
if netutil.is_valid_ip(ip):
self.remote_ip = ip
# AWS uses X-Forwarded-Proto
@@ -397,16 +397,31 @@ def test_ip_headers(self):
self.fetch_json("/", headers=valid_ipv4)["remote_ip"],
"4.4.4.4")
+ valid_ipv4_list = {"X-Forwarded-For": "127.0.0.1, 4.4.4.4"}
+ self.assertEqual(
+ self.fetch_json("/", headers=valid_ipv4_list)["remote_ip"],
+ "4.4.4.4")
+
valid_ipv6 = {"X-Real-IP": "2620:0:1cfe:face:b00c::3"}
self.assertEqual(
self.fetch_json("/", headers=valid_ipv6)["remote_ip"],
"2620:0:1cfe:face:b00c::3")
+ valid_ipv6_list = {"X-Forwarded-For": "::1, 2620:0:1cfe:face:b00c::3"}
+ self.assertEqual(
+ self.fetch_json("/", headers=valid_ipv6_list)["remote_ip"],
+ "2620:0:1cfe:face:b00c::3")
+
invalid_chars = {"X-Real-IP": "4.4.4.4<script>"}
self.assertEqual(
self.fetch_json("/", headers=invalid_chars)["remote_ip"],
"127.0.0.1")
+ invalid_chars_list = {"X-Forwarded-For": "4.4.4.4, 5.5.5.5<script>"}
+ self.assertEqual(
+ self.fetch_json("/", headers=invalid_chars_list)["remote_ip"],
+ "127.0.0.1")
+
invalid_host = {"X-Real-IP": "www.google.com"}
self.assertEqual(
self.fetch_json("/", headers=invalid_host)["remote_ip"],

0 comments on commit e23cbd4

Please sign in to comment.