I don’t know if anyone will find this useful, but I really liked the idea of the ruleset proposed by phear, so I went and wrote a Python 2.6 rule (although it is probably compatible with 2.5):
import re class SecurityException(Exception): pass class Rule: """Creates a rule to evaluate against a string. Rules can be regex patterns or a boolean returning function. Whether a rule is inclusive or exclusive is decided by the sign of the weight. Positive weights are inclusive, negative weights are exclusive. Call score() to return either 0 or the weight if the rule is fufilled. Raises a SecurityException if a required rule is violated. """ def __init__(self,rule,weight=1,required=False,name=u"The Unnamed Rule"): try: getattr(rule,"__call__") except AttributeError: self.rule = re.compile(rule) # If a regex, compile else: self.rule = rule # Otherwise it a function and it should be scored using it if weight == 0: return ValueError(u"Weights can not be 0") self.weight = weight self.required = required self.name = name def exclusive(self): return self.weight < 0 def inclusive(self): return self.weight >= 0 exclusive = property(exclusive) inclusive = property(inclusive) def _score_regex(self,password): match = self.rule.search(password) if match is None: if self.exclusive: # didn't match an exclusive rule return self.weight elif self.inclusive and self.required: # didn't match on a required inclusive rule raise SecurityException(u"Violation of Rule: %s by input \"%s\"" % (self.name.title(), password)) elif self.inclusive and not self.required: return 0 else: if self.inclusive: return self.weight elif self.exclusive and self.required: raise SecurityException(u"Violation of Rule: %s by input \"%s\"" % (self.name,password)) elif self.exclusive and not self.required: return 0 return 0 def score(self,password): try: getattr(self.rule,"__call__") except AttributeError: return self._score_regex(password) else: return self.rule(password) * self.weight def __unicode__(self): return u"%s (%i)" % (self.name.title(), self.weight) def __str__(self): return self.__unicode__()
I hope someone finds this useful!
Usage example:
rules = [ Rule("^foobar",weight=20,required=True,name=u"The Fubared Rule"), ] try: score = 0 for rule in rules: score += rule.score() except SecurityException e: print e else: print score
DISCLAIMER: Not tested in block
SapphireSun Dec 09 '09 at 9:00 2009-12-09 09:00
source share