Advertisement
johnmahugu

django bruteforce

Mar 14th, 2016
300
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.09 KB | None | 0 0
  1. """
  2. Usage:
  3.  
  4. An example of adding the bruteforce() function to a custom authentication backend:
  5.  
  6. from django.contrib.auth.backends import ModelBackend
  7. from django.contrib.auth.models import User
  8.  
  9. from bruteforce import bruteforce
  10.  
  11. class EmailBackend(ModelBackend):
  12.    def authenticate(self, username=None, password=None):
  13.        try:
  14.            user = User.objects.get(email=username)
  15.            if user.check_password(password):
  16.                return user
  17.        except User.DoesNotExist:
  18.            pass
  19.  
  20.        # bruteforce
  21.        if username is not None:
  22.            bruteforce(username)
  23.        return None
  24.  
  25. """
  26. import datetime
  27. import hashlib
  28. from time import sleep
  29.  
  30. from django.conf import settings
  31. from django.core.cache import cache
  32. #https://raw.githubusercontent.com/naremit/NaremitBruteforce/master/bruteforce.py
  33. # settings
  34. BRUTEFORCE_MINUTES = getattr(settings, 'BRUTEFORCE_MINUTES', 5)
  35. BRUTEFORCE_ALLOWED_ATTEMPTS = getattr(settings, 'BRUTEFORCE_ALLOWED_ATTEMPTS', 3)
  36. BRUTEFORCE_MAX_PAUSE = getattr(settings, 'BRUTEFORCE_MAX_PAUSE', 10)
  37. BRUTEFORCE_PREFIX = getattr(settings, 'BRUTEFORCE_PREFIX', 'bruteforce')
  38.  
  39. def bruteforce(ident):
  40.     # hash the identifier to prevent control character problems
  41.     prefix = '%s_%s' % (BRUTEFORCE_PREFIX, hashlib.md5(ident).hexdigest())
  42.  
  43.     # create cache keys for each of the last n minutes
  44.     cache_keys = []
  45.     dt = datetime.datetime.now()
  46.     count = 0
  47.     while count < BRUTEFORCE_MINUTES:
  48.         cache_keys.append('%s_%s:%s' % (prefix, dt.hour, dt.minute))
  49.         dt -= datetime.timedelta(seconds=60)
  50.         count +=1
  51.  
  52.     # increment count for this minute
  53.     try:
  54.         cache.incr(cache_keys[0])
  55.     except:
  56.         cache.set(cache_keys[0], 1, (60 * (BRUTEFORCE_MINUTES + 1)))
  57.  
  58.     # collect count from cache
  59.     attempt_count = 0
  60.     attempt_dict = cache.get_many(cache_keys)
  61.     for v in attempt_dict.itervalues():
  62.         attempt_count += v
  63.  
  64.     # if we detect multiple attempts, sleep
  65.     sleep(min(
  66.         BRUTEFORCE_MAX_PAUSE,
  67.         max(0, attempt_count - BRUTEFORCE_ALLOWED_ATTEMPTS)
  68.     ))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement