Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- Usage:
- An example of adding the bruteforce() function to a custom authentication backend:
- from django.contrib.auth.backends import ModelBackend
- from django.contrib.auth.models import User
- from bruteforce import bruteforce
- class EmailBackend(ModelBackend):
- def authenticate(self, username=None, password=None):
- try:
- user = User.objects.get(email=username)
- if user.check_password(password):
- return user
- except User.DoesNotExist:
- pass
- # bruteforce
- if username is not None:
- bruteforce(username)
- return None
- """
- import datetime
- import hashlib
- from time import sleep
- from django.conf import settings
- from django.core.cache import cache
- #https://raw.githubusercontent.com/naremit/NaremitBruteforce/master/bruteforce.py
- # settings
- BRUTEFORCE_MINUTES = getattr(settings, 'BRUTEFORCE_MINUTES', 5)
- BRUTEFORCE_ALLOWED_ATTEMPTS = getattr(settings, 'BRUTEFORCE_ALLOWED_ATTEMPTS', 3)
- BRUTEFORCE_MAX_PAUSE = getattr(settings, 'BRUTEFORCE_MAX_PAUSE', 10)
- BRUTEFORCE_PREFIX = getattr(settings, 'BRUTEFORCE_PREFIX', 'bruteforce')
- def bruteforce(ident):
- # hash the identifier to prevent control character problems
- prefix = '%s_%s' % (BRUTEFORCE_PREFIX, hashlib.md5(ident).hexdigest())
- # create cache keys for each of the last n minutes
- cache_keys = []
- dt = datetime.datetime.now()
- count = 0
- while count < BRUTEFORCE_MINUTES:
- cache_keys.append('%s_%s:%s' % (prefix, dt.hour, dt.minute))
- dt -= datetime.timedelta(seconds=60)
- count +=1
- # increment count for this minute
- try:
- cache.incr(cache_keys[0])
- except:
- cache.set(cache_keys[0], 1, (60 * (BRUTEFORCE_MINUTES + 1)))
- # collect count from cache
- attempt_count = 0
- attempt_dict = cache.get_many(cache_keys)
- for v in attempt_dict.itervalues():
- attempt_count += v
- # if we detect multiple attempts, sleep
- sleep(min(
- BRUTEFORCE_MAX_PAUSE,
- max(0, attempt_count - BRUTEFORCE_ALLOWED_ATTEMPTS)
- ))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement