Commits

EGh5  committed d9e8f2f

README added

  • Participants

Comments (0)

Files changed (7)

File doorkeeper/README.rst

+django-doorkeeper
+*****************
+
+This application bannes bad bots making requests for exactly non-existent urls.
+Middleware-level is using.
+
+You should add patterns of this urls as LAST tuple elements in your urls.py
+
+  from doorkeeper.views import inspect
+  ...    
+  urlpatterns = patterns('',
+    ....
+    ....
+    url(r'php',inspect),
+    url(r'translators\.html',inspect),
+    url(r'dba',inspect),
+    )
+
+You can add this constants in your settings.py
+
+  DOORKEEPER_PATIENCE=3  # number of bad attempts
+  DOORKEEPER_TERM=1200   # penalty time (sec.)
+
+Add Ť'doorkeeper',ť to INSTALLED_APPS, and Ť'doorkeeper.middleware.DoorkeeperMiddleware',ť to MIDDLEWARE_CLASSES (as high as possible)
+    
+You can watch your catch in django-admin.
+ 
+NOTE: this application is not intendent for high-loaded django-site. Please consider os-level utilities. fail2ban should be mentioned among them.
+
+
+
+eug033@gmail.com

File doorkeeper/__init__.py

Empty file added.

File doorkeeper/admin.py

+# -*- coding: utf-8 -*-
+# Creation date: 10.03.12
+
+from doorkeeper.models import BotRecord
+from django.contrib import admin
+
+
+class BotRecordAdmin(admin.ModelAdmin):
+    list_display = ('bot_adr','bot_name','jail_count','last_date','penalty_count')
+
+admin.site.register(BotRecord,BotRecordAdmin)

File doorkeeper/middleware.py

+# -*- coding: utf-8 -*-
+# Creation date: 10.03.12
+
+import datetime
+
+#from django.conf import settings
+from django.http import HttpResponseNotFound
+from doorkeeper.models import BotRecord
+from django.conf import settings
+
+PATIENCE= getattr(settings,'DOORKEEPER_PATIENCE', 5)
+
+class DoorkeeperMiddleware(object):
+    def process_request(self, request):
+    """
+    Each request is investigated. 
+    """
+        sagent = request.META.get('HTTP_USER_AGENT',"n/a")
+        saddr = request.META.get('REMOTE_ADDR',"n/a")
+        shash = "%s %s"% (saddr, sagent)
+        try:
+            br=BotRecord.objects.get(bot_hash=shash)
+            now=datetime.datetime.now()
+            if br.detention_upto:
+                if br.detention_upto> now:           # fresh banned cleint
+                    raise Http404()                  # bounce
+                    #return HttpResponseNotFound("Not existent page!")
+                else:
+                    if br.penalty_count > PATIENCE:  # for old banned client
+                        br.penalty_count=0           # forgiving them
+                        br.save()
+                    pass
+        except BotRecord.DoesNotExist:
+            pass
+
+
+
+

File doorkeeper/models.py

+# -*- coding: utf-8 -*-
+from django.db import models
+
+class BotRecord(models.Model):
+    bot_name = models.CharField("имя бота",max_length=250)
+    bot_adr = models.CharField("адрес",max_length=250)
+    bot_hash = models.CharField("Ń
+    jail_count = models.IntegerField("запретов",default=0)
+    penalty_count = models.IntegerField("штрафы",default=0)
+    last_date=models.DateTimeField("ОйнОвНонО",null=True,auto_now=True)
+    detention_upto=models.DateTimeField("йНОк дО",null=True)
+
+    def __unicode__(self):
+        return "%s" % self.bot_hash
+

File doorkeeper/tests.py

+"""
+This file demonstrates writing tests using the unittest module. These will pass
+when you run "manage.py test".
+
+Replace this with more appropriate tests for your application.
+"""
+
+from django.test import TestCase
+
+
+class SimpleTest(TestCase):
+    def test_basic_addition(self):
+        """
+        Tests that 1 + 1 always equals 2.
+        """
+        self.assertEqual(1 + 1, 2)

File doorkeeper/views.py

+# Create your views here.
+from django.http import HttpResponseNotFound
+
+from models import BotRecord
+import datetime
+from users import views
+from django.conf import settings
+
+TERM = getattr(settings,'DOORKEEPER_TERM', 1200)
+PATIENCE= getattr(settings,'DOORKEEPER_PATIENCE', 5)
+
+def inspect(request):
+    """
+    View to regiter suspicious client and raise Http404
+    
+    """
+    sagent  =request.META.get('HTTP_USER_AGENT',"n/a")
+    saddr=request.META.get('REMOTE_ADDR',"n/a")
+    shash="%s %s"% (saddr, sagent)
+    try:
+        br=BotRecord.objects.get(bot_hash=shash)
+        now=datetime.datetime.now()
+        delta=datetime.timedelta(0,TERM)
+        if br.last_date+delta > now:
+            br.penalty_count+=1
+            if br.penalty_count > PATIENCE:
+                br.detention_upto=now+delta
+                br.jail_count+=1
+        br.save()
+        
+    except BotRecord.DoesNotExist:
+        br=BotRecord.objects.create(bot_hash=shash,bot_name=sagent, bot_adr=saddr)
+        br.save()
+    raise Http404()