Only use the X-Forwarded-For header if connection is from a trusted network (#15182)

See https://github.com/home-assistant/home-assistant/issues/14345#issuecomment-400854569
This commit is contained in:
Colin O'Dell authored and Paulus Schoutsen committed 2018-06-28 09:16:11 -04:00
1 parent dbb786c548
commit 19f2bbf52f
4 files changed
+31 -10

No files matched your search

+1 -1
View File
@@ -180,7 +180,7 @@ class HomeAssistantHTTP(object):
middlewares=[staticresource_middleware])
# This order matters
setup_real_ip(app, use_x_forwarded_for)
setup_real_ip(app, use_x_forwarded_for, trusted_networks)
if is_ban_enabled:
setup_bans(hass, app, login_threshold)
+9 -5
View File
@@ -11,18 +11,22 @@ from .const import KEY_REAL_IP
@callback
def setup_real_ip(app, use_x_forwarded_for):
def setup_real_ip(app, use_x_forwarded_for, trusted_networks):
"""Create IP Ban middleware for the app."""
@middleware
async def real_ip_middleware(request, handler):
"""Real IP middleware."""
connected_ip = ip_address(
request.transport.get_extra_info('peername')[0])
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):
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])
else:
request[KEY_REAL_IP] = \
ip_address(request.transport.get_extra_info('peername')[0])
return await handler(request)