From 4cf5aac2ca88902608e87f7492a09beacd785cf2 Mon Sep 17 00:00:00 2001 From: joaohortsenado <100957576+joaohortsenado@users.noreply.github.com> Date: Wed, 30 Aug 2023 23:04:00 -0300 Subject: [PATCH] fix: restring acesso ao prometheus metrics para apenas ips locais/invalidos (#3668) Co-authored-by: joao --- sapl/endpoint_restriction_middleware.py | 38 +++++++++++++++++++++++++ sapl/settings.py | 1 + 2 files changed, 39 insertions(+) create mode 100644 sapl/endpoint_restriction_middleware.py diff --git a/sapl/endpoint_restriction_middleware.py b/sapl/endpoint_restriction_middleware.py new file mode 100644 index 000000000..b815b4a2e --- /dev/null +++ b/sapl/endpoint_restriction_middleware.py @@ -0,0 +1,38 @@ +from django.http import HttpResponseForbidden +import logging + +# lista de IPs permitidos (localhost, redes locais, etc) +# https://en.wikipedia.org/wiki/Reserved_IP_addresses +ALLOWED_IPS = [ + '127.0.0.1', + '::1', + '10.0.0.0/8', + '172.16.0.0/12', + '192.168.0.0/16', + 'fc00::/7', + '::1', + 'fe80::/10', + '192.0.2.0/24', + '2001:db8::/32', + '224.0.0.0/4', + 'ff00::/8' +] + +RESTRICTED_ENDPOINTS = ['/metrics'] + + +class EndpointRestrictionMiddleware: + logging.getLogger(__name__) + + def __init__(self, get_response): + self.get_response = get_response + + def __call__(self, request): + # IP do cliente + client_ip = request.META.get('REMOTE_ADDR') + + # bloqueia acesso a endpoints restritos para IPs nao permitidos + if request.path in RESTRICTED_ENDPOINTS and client_ip not in ALLOWED_IPS: + return HttpResponseForbidden('Acesso proibido') + + return self.get_response(request) diff --git a/sapl/settings.py b/sapl/settings.py index c23acd084..ba143ca12 100644 --- a/sapl/settings.py +++ b/sapl/settings.py @@ -129,6 +129,7 @@ MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', + 'sapl.endpoint_restriction_middleware.EndpointRestrictionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware',