Skip to content

Commit

Permalink
Filter out bad forwarded IP address from Herkou.
Browse files Browse the repository at this point in the history
  • Loading branch information
jplehmann committed Feb 1, 2019
1 parent f5ea013 commit 084d0f4
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 5 deletions.
3 changes: 2 additions & 1 deletion iprestrict/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,8 @@ def extract_client_ip(self, request):
def get_forwarded_for(self, request):
hdr = request.META.get('HTTP_X_FORWARDED_FOR')
if hdr is not None:
return [ip.strip() for ip in hdr.split(',')]
# Exclude unknown which sometimes precedes an IP in Heroku.
return [ip.strip() for ip in hdr.split(',') if ip != 'unknown']
else:
return []

Expand Down
16 changes: 12 additions & 4 deletions tests/test_middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,10 +111,18 @@ def test_remote_addr_empty(self):
client_ip = self.middleware.extract_client_ip(request)
self.assertEquals(client_ip, '')

@override_settings(IPRESTRICT_TRUST_ALL_PROXIES=True)
def test_ignore_bad_forwarded_addr(self):
self.middleware = IPRestrictMiddleware()
request = self.factory.get('', REMOTE_ADDR=LOCAL_IP, HTTP_X_FORWARDED_FOR="unknown,1.2.3.4")

client_ip = self.middleware.extract_client_ip(request)
self.assertEquals(client_ip, '1.2.3.4')

@override_settings(IPRESTRICT_TRUSTED_PROXIES=(PROXY,))
def test_single_proxy(self):
self.middleware = IPRestrictMiddleware()
request = self.factory.get('', REMOTE_ADDR=PROXY, HTTP_X_FORWARDED_FOR = LOCAL_IP)
request = self.factory.get('', REMOTE_ADDR=PROXY, HTTP_X_FORWARDED_FOR=LOCAL_IP)

client_ip = self.middleware.extract_client_ip(request)
self.assertEquals(client_ip, LOCAL_IP)
Expand All @@ -123,9 +131,9 @@ def test_single_proxy(self):
def test_multiple_proxies_one_not_trusted(self):
self.middleware = IPRestrictMiddleware()
proxies = ['2.2.2.2', '3.3.3.3', '4.4.4.4']
request = self.factory.get('', REMOTE_ADDR=PROXY,
request = self.factory.get('', REMOTE_ADDR=PROXY,
HTTP_X_FORWARDED_FOR = ', '.join([LOCAL_IP] + proxies))

try:
client_ip = self.middleware.extract_client_ip(request)
except exceptions.PermissionDenied:
Expand All @@ -139,7 +147,7 @@ def test_multiple_proxies_all_trusted(self):
proxies = ['2.2.2.2', '3.3.3.3', '4.4.4.4']
request = self.factory.get('', REMOTE_ADDR=PROXY,
HTTP_X_FORWARDED_FOR = ', '.join([LOCAL_IP] + proxies))

client_ip = self.middleware.extract_client_ip(request)
self.assertEquals(client_ip, LOCAL_IP)

Expand Down

0 comments on commit 084d0f4

Please sign in to comment.