Advertisement
carlosmfp

DDoS&ForceBruteDefenseMiddleware

Mar 20th, 2024
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.16 KB | Source Code | 0 0
  1. from rest_framework.status import HTTP_200_OK, HTTP_403_FORBIDDEN
  2. from django.http import HttpResponseForbidden
  3. from django.core.cache import cache
  4. from django.conf import settings
  5.  
  6. import settings
  7.  
  8.  
  9. class DDoSProtectionMiddleware:
  10.     def __init__(self, get_response):
  11.         self.get_response = get_response
  12.         self.time_window = 60
  13.  
  14.     def process_request(self, request):
  15.         ip_address = request.META.get('REMOTE_ADDR')
  16.         cache_key = f"DDoS_{ip_address}"
  17.  
  18.         request_count = cache.get(cache_key, 0)
  19.         request_count += 1
  20.  
  21.         if request_count > settings.REQUESTS_PER_MINUTE_ALLOWED:
  22.             return HttpResponseForbidden("Demasiadas solicitudes.", status=HTTP_403_FORBIDDEN)
  23.  
  24.         cache.set(cache_key, request_count, timeout=self.time_window)
  25.  
  26.         return None
  27.  
  28.     def __call__(self, request):
  29.         return self.process_request(request) or self.get_response(request)
  30.  
  31.  
  32. class BruteForceProtectionMiddleware:
  33.     def __init__(self, get_response):
  34.         self.get_response = get_response
  35.  
  36.     def __call__(self, request):
  37.         response = self.get_response(request)
  38.         print(response)
  39.  
  40.         # revisa si la solicitud es del endpoint para login (cambiar)
  41.         if request.path in 'url/de/la/api/para/autenticacion/' and request.method == 'POST':
  42.             ip_address = request.META.get('REMOTE_ADDR')
  43.  
  44.             cache_key = f"Intento_de_login_de_{ip_address}"
  45.             login_attempts = cache.get(cache_key, 0)
  46.  
  47.             if response.status_code != HTTP_200_OK:
  48.                 cache.set(cache_key, login_attempts + 1, timeout=settings.BRUTE_FORCE_TIMEOUT)
  49.                 print(f"Intentos de login: {login_attempts + 1}")
  50.             else:
  51.                 cache.delete(cache_key)
  52.                 print("Login exitoso")
  53.  
  54.             if login_attempts >= core.settings.BRUTE_FORCE_THRESHOLD:
  55.                 print(f"Excedidos los intentos de login, espere {settings.BRUTE_FORCE_TIMEOUT} segundos.")
  56.                 return HttpResponseForbidden(
  57.                     f"Excedidos los intentos de login, espere {settings.BRUTE_FORCE_TIMEOUT} segundos."
  58.                 )
  59.  
  60.         return response
  61.  
Tags: django
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement