2018-02-15 21:06:14 +00:00
|
|
|
"""Middleware to fetch real IP."""
|
|
|
|
from ipaddress import ip_address
|
|
|
|
|
|
|
|
from aiohttp.hdrs import X_FORWARDED_FOR
|
2019-02-14 15:01:46 +00:00
|
|
|
from aiohttp.web import middleware
|
2018-02-15 21:06:14 +00:00
|
|
|
|
|
|
|
from homeassistant.core import callback
|
|
|
|
|
|
|
|
from .const import KEY_REAL_IP
|
|
|
|
|
2019-08-12 03:38:18 +00:00
|
|
|
# mypy: allow-untyped-defs
|
|
|
|
|
|
|
|
|
2018-02-15 21:06:14 +00:00
|
|
|
@callback
|
2018-06-29 20:27:06 +00:00
|
|
|
def setup_real_ip(app, use_x_forwarded_for, trusted_proxies):
|
2018-02-15 21:06:14 +00:00
|
|
|
"""Create IP Ban middleware for the app."""
|
2019-07-31 19:25:30 +00:00
|
|
|
|
2018-02-15 21:06:14 +00:00
|
|
|
@middleware
|
2018-03-09 01:51:49 +00:00
|
|
|
async def real_ip_middleware(request, handler):
|
2018-02-15 21:06:14 +00:00
|
|
|
"""Real IP middleware."""
|
2019-07-31 19:25:30 +00:00
|
|
|
connected_ip = ip_address(request.transport.get_extra_info("peername")[0])
|
2018-06-28 13:16:11 +00:00
|
|
|
request[KEY_REAL_IP] = connected_ip
|
|
|
|
|
|
|
|
# Only use the XFF header if enabled, present, and from a trusted proxy
|
2018-06-29 20:27:06 +00:00
|
|
|
try:
|
2019-07-31 19:25:30 +00:00
|
|
|
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
|
|
|
|
)
|
|
|
|
):
|
2018-06-29 20:27:06 +00:00
|
|
|
request[KEY_REAL_IP] = ip_address(
|
2019-07-31 19:25:30 +00:00
|
|
|
request.headers.get(X_FORWARDED_FOR).split(", ")[-1]
|
|
|
|
)
|
2018-06-29 20:27:06 +00:00
|
|
|
except ValueError:
|
|
|
|
pass
|
2018-02-15 21:06:14 +00:00
|
|
|
|
2018-03-09 01:51:49 +00:00
|
|
|
return await handler(request)
|
2018-02-15 21:06:14 +00:00
|
|
|
|
2018-11-21 19:55:21 +00:00
|
|
|
app.middlewares.append(real_ip_middleware)
|