2019-03-03 19:26:25 +00:00
|
|
|
"""passbook suspicious request policy"""
|
|
|
|
from django.db import models
|
|
|
|
from django.utils.translation import gettext as _
|
2019-10-03 09:45:31 +01:00
|
|
|
from ipware import get_client_ip
|
2019-03-03 19:26:25 +00:00
|
|
|
|
2019-10-03 09:45:31 +01:00
|
|
|
from passbook.core.models import Policy, User
|
|
|
|
from passbook.policy.struct import PolicyRequest, PolicyResult
|
2019-03-03 19:26:25 +00:00
|
|
|
|
|
|
|
|
|
|
|
class SuspiciousRequestPolicy(Policy):
|
|
|
|
"""Return true if request IP/target username's score is below a certain threshold"""
|
|
|
|
|
|
|
|
check_ip = models.BooleanField(default=True)
|
|
|
|
check_username = models.BooleanField(default=True)
|
|
|
|
threshold = models.IntegerField(default=-5)
|
|
|
|
|
|
|
|
form = 'passbook.suspicious_policy.forms.SuspiciousRequestPolicyForm'
|
|
|
|
|
2019-10-03 09:45:31 +01:00
|
|
|
def passes(self, request: PolicyRequest) -> PolicyResult:
|
|
|
|
remote_ip, _ = get_client_ip(request.http_request)
|
2019-03-03 19:26:25 +00:00
|
|
|
passing = True
|
|
|
|
if self.check_ip:
|
|
|
|
ip_scores = IPScore.objects.filter(ip=remote_ip, score__lte=self.threshold)
|
|
|
|
passing = passing and ip_scores.exists()
|
|
|
|
if self.check_username:
|
2019-10-03 09:45:31 +01:00
|
|
|
user_scores = UserScore.objects.filter(user=request.user, score__lte=self.threshold)
|
2019-03-03 19:26:25 +00:00
|
|
|
passing = passing and user_scores.exists()
|
2019-10-01 09:17:39 +01:00
|
|
|
return PolicyResult(passing)
|
2019-03-03 19:26:25 +00:00
|
|
|
|
|
|
|
class Meta:
|
|
|
|
|
|
|
|
verbose_name = _('Suspicious Request Policy')
|
|
|
|
verbose_name_plural = _('Suspicious Request Policies')
|
|
|
|
|
|
|
|
class IPScore(models.Model):
|
|
|
|
"""Store score coming from the same IP"""
|
|
|
|
|
|
|
|
ip = models.GenericIPAddressField(unique=True)
|
|
|
|
score = models.IntegerField(default=0)
|
|
|
|
updated = models.DateTimeField(auto_now=True)
|
|
|
|
|
|
|
|
def __str__(self):
|
|
|
|
return "IPScore for %s @ %d" % (self.ip, self.score)
|
|
|
|
|
|
|
|
class UserScore(models.Model):
|
|
|
|
"""Store score attempting to log in as the same username"""
|
|
|
|
|
|
|
|
user = models.OneToOneField(User, on_delete=models.CASCADE)
|
|
|
|
score = models.IntegerField(default=0)
|
|
|
|
updated = models.DateTimeField(auto_now=True)
|
|
|
|
|
|
|
|
def __str__(self):
|
|
|
|
return "UserScore for %s @ %d" % (self.user, self.score)
|