X-Forwarded-For improvements and bug fixes (#15204)
* Use new trusted_proxies setting for X-Forwarded-For whitelist * Only use the last IP in the header Per Wikipedia (https://en.wikipedia.org/wiki/X-Forwarded-For#Format): > The last IP address is always the IP address that connects to the last proxy, > which means it is the most reliable source of information. * Add two additional tests * Ignore nonsense header values instead of failing
This commit is contained in:
1 parent
c61a652c90
commit
fd38caa287
5 files changed
+67
-9
No files matched your search
@@ -11,7 +11,7 @@ from .const import KEY_REAL_IP
|
||||
|
||||
|
||||
@callback
|
||||
def setup_real_ip(app, use_x_forwarded_for, trusted_networks):
|
||||
def setup_real_ip(app, use_x_forwarded_for, trusted_proxies):
|
||||
"""Create IP Ban middleware for the app."""
|
||||
@middleware
|
||||
async def real_ip_middleware(request, handler):
|
||||
@@ -21,12 +21,15 @@ def setup_real_ip(app, use_x_forwarded_for, trusted_networks):
|
||||
request[KEY_REAL_IP] = connected_ip
|
||||
|
||||
# Only use the XFF header if enabled, present, and from a trusted proxy
|
||||
if (use_x_forwarded_for and
|
||||
X_FORWARDED_FOR in request.headers and
|
||||
any(connected_ip in trusted_network
|
||||
for trusted_network in trusted_networks)):
|
||||
request[KEY_REAL_IP] = ip_address(
|
||||
request.headers.get(X_FORWARDED_FOR).split(',')[0])
|
||||
try:
|
||||
if (use_x_forwarded_for and
|
||||
X_FORWARDED_FOR in request.headers and
|
||||
any(connected_ip in trusted_proxy
|
||||
for trusted_proxy in trusted_proxies)):
|
||||
request[KEY_REAL_IP] = ip_address(
|
||||
request.headers.get(X_FORWARDED_FOR).split(', ')[-1])
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
return await handler(request)
|
||||
|
||||
|
||||
Reference in new issue
Block a user