Reputation: 2641
I know this is a well covered theme on SO, but can someone tell me is there some third party package on django-admin
protection which is supproting django
version 1.8 + and python 3.4+. It seems all I have found is outdated and supporting <1.7 django
version and python 2.7.
Further more, can someone explain how can I manually protect django-admin, what will be the step's to take when writing a code to protect django-admin against brute-force attacks?
Upvotes: 1
Views: 854
Reputation: 7797
I use two methods:
The authentication backend caching a last login attempt and rejects the too frequents attempts.
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.auth.backends import ModelBackend
from django.core.cache import cache
import datetime
class BruteForceProtectedAuthBackend(ModelBackend):
def authenticate(self, username=None, password=None):
now = datetime.datetime.now()
last_login = cache.get(username + '-login-attempt', now - datetime.timedelta(days=1))
cache.set(username + '-login-attempt', now)
if (now - last_login) < datetime.timedelta(seconds=settings.AUTH_RATE):
return None
try:
user = User.objects.get(username=username)
if user.check_password(password):
return user
else:
return None
except User.DoesNotExist:
return None
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
Middleware rejecting request to admin urls from non local IP addresses.
from django.http import HttpResponseForbidden
from django.conf import settings
from ipware.ip import get_ip
class ProtectAdminSiteMiddleware(object):
def process_request(self, request):
if request.path.startswith(reverse('admin:index')):
remote_addr = get_ip(request)
if remote_addr is None:
return HttpResponseForbidden('Forbiden')
else:
if not remote_addr in settings.INTERNAL_IPS:
return HttpResponseForbidden('Forbiden')
return None
Upvotes: 2