Fabien Schwebel avatar Fabien Schwebel committed 7f4798b

New ASP error feature, now PyPI-ready

Comments (0)

Files changed (11)

+copyright (c) 2012 Fabien Schwebel
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.

Empty file removed.

admin.py

-from django.contrib import admin
-from models import MiseryIP
-
-admin.site.register(MiseryIP)
Add a comment to this file

django_misery/__init__.py

Empty file added.

django_misery/admin.py

+from django.contrib import admin
+from models import MiseryIP
+
+admin.site.register(MiseryIP)

django_misery/middleware.py

+import logging
+from random import randint
+from time import sleep
+from django.http import HttpResponseForbidden
+from django.http import HttpResponse
+from django.http import Http404
+from django.core.exceptions import PermissionDenied
+from django.contrib.auth import logout
+
+from django.db import models
+from models import MiseryIP
+
+from django.conf import settings
+
+logger = logging.getLogger('django_misery')
+
+slowBanStrenght = getattr(settings, 'MISERY_SLOW_STRENGHT', '6')
+logoutProbability = getattr(settings, 'MISERY_LOGOUT_PROBABILITY', '10')
+e403Probability = getattr(settings, 'MISERY_403_PROBABILITY', '10')
+e404Probability = getattr(settings, 'MISERY_404_PROBABILITY', '10')
+whiteScreenProbability = getattr(settings, 'MISERY_WHITE_SCREEN_PROBABILITY', '20')
+
+
+class miserize(object):
+    def process_request(self, request):
+        user = request.user
+        ip = request.META['REMOTE_ADDR']
+
+        is_miserized = MiseryIP.objects.filter(ip=ip).count() > 0
+        logger.debug(is_miserized)
+
+        if is_miserized:
+            # unleash the wrath
+            sleep(randint(int(slowBanStrenght), 2*int(slowBanStrenght)))
+            
+            if randint(0, 100) <= int(logoutProbability):
+                logout(request)
+            elif randint(0, 100) <= int(e403Probability):
+                raise PermissionDenied
+            elif randint(0, 100) <= int(e404Probability):
+                raise Http404
+            elif randint(0, 100) <= int(whiteScreenProbability):
+                return HttpResponse("")
+            # else leave him alone, the poor pal

django_misery/models.py

+import ipcalc
+import datetime
+
+from django.db import models
+
+class MiseryIP(models.Model):
+    ip = models.GenericIPAddressField(primary_key = True, unpack_ipv4 = True)
+    date_added = models.DateTimeField('date entered the database', default = datetime.datetime.now)
+    notes = models.CharField(max_length = 100, blank = True)
+    
+    def __unicode__(self):
+        return 'Misery IP: %s' % self.ip
+
+    class Meta:
+        verbose_name = 'IP v4/v6 to put in misery'
+        verbose_name_plural = 'IP v4/v6 to put in misery'
+

django_misery/templates/django_misery/ASPerror.html

+<html>
+    <head>
+        <title>Une valeur Request.Form potentiellement dangereuse a &#233;t&#233; d&#233;tect&#233;e &#224; partir du client (DateDeb=&quot;&amp;#9731;&quot;).</title>
+        <style>
+        	body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;} 
+        	p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px}
+        	b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px}
+        	H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red }
+        	H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon }
+        	pre {font-family:"Lucida Console";font-size: .9em}
+        	.marker {font-weight: bold; color: black;text-decoration: none;}
+        	.version {color: gray;}
+        	.error {margin-bottom: 10px;}
+        	.expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; }
+        </style>
+    </head>
+
+    <body bgcolor="white">
+
+            <span><H1>Erreur du serveur dans l'application '/'.<hr width=100% size=1 color=silver></H1>
+
+            <h2> <i>Une valeur Request.Form potentiellement dangereuse a &#233;t&#233; d&#233;tect&#233;e &#224; partir du client (DateDeb=&quot;&amp;#9731;&quot;).</i> </h2></span>
+
+            <font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif ">
+
+            <b> Description : </b>La validation de la demande a détecté une valeur d'entrée du client potentiellement dangereuse et le traitement de la demande a été abandonné.  Cette valeur peut indiquer une tentative pour compromettre la sécurité de votre application, telle qu'une attaque de script entre sites.  Vous pouvez désactiver la validation de la demande en définissant validateRequest=false dans la directive de page ou dans la section de configuration <pages>.  Cependant, il est fortement recommandé que votre application contrôle explicitement toutes les entrées dans ce cas là.
+            <br><br>
+
+            <b> Détails de l'exception: </b>System.Web.HttpRequestValidationException: Une valeur Request.Form potentiellement dangereuse a &#233;t&#233; d&#233;tect&#233;e &#224; partir du client (DateDeb=&quot;&amp;#9731;&quot;).<br><br>
+
+            <b>Erreur source:</b> <br><br>
+
+            <table width=100% bgcolor="#ffffcc">
+               <tr>
+                  <td>
+                      <code>
+
+Une exception non g&#233;r&#233;e s'est produite lors de l'ex&#233;cution de la demande Web actuelle. Les informations relatives &#224; l'origine et l'emplacement de l'exception peuvent &#234;tre identifi&#233;es en utilisant la trace de la pile d'exception ci-dessous.</code>
+
+                  </td>
+               </tr>
+            </table>
+
+            <br>
+
+            <b>Trace de la pile:</b> <br><br>
+
+            <table width=100% bgcolor="#ffffcc">
+               <tr>
+                  <td>
+                      <code><pre>
+
+[HttpRequestValidationException (0x80004005): Une valeur Request.Form potentiellement dangereuse a &#233;t&#233; d&#233;tect&#233;e &#224; partir du client (DateDeb=&quot;&amp;#9731;&quot;).]
+   System.Web.HttpRequest.ValidateString(String s, String valueName, String collectionName) +240
+   System.Web.HttpRequest.ValidateNameValueCollection(NameValueCollection nvc, String collectionName) +99
+   System.Web.HttpRequest.get_Form() +113
+   System.Web.UI.Page.GetCollectionBasedOnMethod() +69
+   System.Web.UI.Page.DeterminePostBackMode() +128
+   System.Web.UI.Page.ProcessRequestMain() +2112
+   System.Web.UI.Page.ProcessRequest() +217
+   System.Web.UI.Page.ProcessRequest(HttpContext context) +18
+   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication+IExecutionStep.Execute() +179
+   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&amp; completedSynchronously) +87
+</pre></code>
+
+                  </td>
+               </tr>
+            </table>
+
+            <br>
+
+            <hr width=100% size=1 color=silver>
+
+            <b>Informations sur la version :</b>&nbsp;Version Microsoft .NET Framework :1.1.4322.2490; Version ASP.NET :1.1.4322.2494
+
+            </font>
+
+    </body>
+</html>

middleware.py

-import logging
-from random import randint
-from time import sleep
-from django.http import HttpResponseForbidden
-from django.http import HttpResponse
-from django.http import Http404
-from django.core.exceptions import PermissionDenied
-from django.contrib.auth import logout
-
-from django.db import models
-from models import MiseryIP
-
-from django.conf import settings
-
-logger = logging.getLogger('django_misery')
-
-slowBanStrenght = getattr(settings, 'MISERY_SLOW_STRENGHT', '6')
-logoutProbability = getattr(settings, 'MISERY_LOGOUT_PROBABILITY', '10')
-e403Probability = getattr(settings, 'MISERY_403_PROBABILITY', '10')
-e404Probability = getattr(settings, 'MISERY_404_PROBABILITY', '10')
-whiteScreenProbability = getattr(settings, 'MISERY_WHITE_SCREEN_PROBABILITY', '20')
-
-
-class miserize(object):
-    def process_request(self, request):
-        user = request.user
-        ip = request.META['REMOTE_ADDR']
-
-        is_miserized = MiseryIP.objects.filter(ip=ip).count() > 0
-        logger.debug(is_miserized)
-
-        if is_miserized:
-            # unleash the wrath
-            sleep(randint(int(slowBanStrenght), 2*int(slowBanStrenght)))
-            
-            if randint(0, 100) <= int(logoutProbability):
-                logout(request)
-            elif randint(0, 100) <= int(e403Probability):
-                raise PermissionDenied
-            elif randint(0, 100) <= int(e404Probability):
-                raise Http404
-            elif randint(0, 100) <= int(whiteScreenProbability):
-                return HttpResponse("")
-            # else leave him alone, the poor pal

models.py

-import ipcalc
-import datetime
-
-from django.db import models
-
-class MiseryIP(models.Model):
-    ip = models.GenericIPAddressField(primary_key = True, unpack_ipv4 = True)
-    date_added = models.DateTimeField('date entered the database', default = datetime.datetime.now)
-    notes = models.CharField(max_length = 100, blank = True)
-    
-    def __unicode__(self):
-        return 'Misery IP: %s' % self.ip
-
-    class Meta:
-        verbose_name = 'IP v4/v6 to put in misery'
-        verbose_name_plural = 'IP v4/v6 to put in misery'
-
+#!/usr/bin/env python
+from distutils.core import setup
+import os
+
+def read(fname):
+    return open(os.path.join(os.path.dirname(__file__), fname)).read()
+
+setup(
+    name = "django-misery",
+    version = "0.0.2",
+    author = "Fabien Schwebel",
+    author_email = "fabien@schwebel.com",
+    description = ("A simple ban system for Django, that does nasty stuff to trolls wandering on your website."),
+    license = "MIT License",
+    keywords = "django misery hellban slowban",
+    url = "http://packages.python.org/an_example_pypi_project",
+    packages=['django_misery'],
+    long_description=read('README.md'),
+    classifiers=[
+        "Development Status :: 3 - Alpha",
+        "Environment :: Web Environment",
+        "Framework :: Django",
+        "Topic :: Utilities",
+        "Intended Audience :: Developers",
+        "License :: OSI Approved :: MIT License",
+        "Operating System :: OS Independent",
+        "Programming Language :: Python",
+        "Topic :: Software Development :: Libraries :: Python Modules",
+    ],
+)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.