authentik.policies.reputation.signals

authentik reputation request signals

  1"""authentik reputation request signals"""
  2
  3from django.contrib.auth.signals import user_logged_in
  4from django.db.models import Case, F, Value, When
  5from django.db.models.functions import Greatest, Least
  6from django.dispatch import receiver
  7from django.http import HttpRequest
  8from psqlextra.query import ConflictAction
  9from psqlextra.util import postgres_manager
 10from structlog.stdlib import get_logger
 11
 12from authentik.admin.utils import get_system_settings
 13from authentik.core.signals import login_failed
 14from authentik.events.context_processors.asn import ASN_CONTEXT_PROCESSOR
 15from authentik.events.context_processors.geoip import GEOIP_CONTEXT_PROCESSOR
 16from authentik.policies.reputation.models import Reputation, reputation_expiry
 17from authentik.root.middleware import ClientIPMiddleware
 18from authentik.stages.identification.signals import identification_failed
 19
 20LOGGER = get_logger()
 21
 22
 23def update_score(request: HttpRequest, identifier: str, amount: int):
 24    """Update score for IP and User"""
 25    remote_ip = ClientIPMiddleware.get_client_ip(request)
 26    settings = get_system_settings()
 27    amount = max(settings.reputation_lower_limit, min(settings.reputation_upper_limit, amount))
 28
 29    with postgres_manager(Reputation) as manager:
 30        reputation = manager.on_conflict(
 31            ["ip", "identifier"],
 32            ConflictAction.UPDATE,
 33            update_values=dict(
 34                score=Greatest(
 35                    settings.reputation_lower_limit,
 36                    Least(settings.reputation_upper_limit, F("score") + amount),
 37                ),
 38            ),
 39        ).insert_and_get(
 40            ip=remote_ip,
 41            identifier=identifier,
 42            score=amount,
 43            ip_geo_data=GEOIP_CONTEXT_PROCESSOR.city_dict(remote_ip) or {},
 44            ip_asn_data=ASN_CONTEXT_PROCESSOR.asn_dict(remote_ip) or {},
 45            expires=reputation_expiry(),
 46        )
 47
 48    LOGGER.info("Updated score", amount=reputation.score, for_user=identifier, for_ip=remote_ip)
 49
 50
 51def update_score_on_login(request: HttpRequest, identifier: str):
 52    """Update score for IP and User on a successful login: a negative score is reset
 53    to 0, any other score is raised by 1. Both branches happen in the same statement
 54    so that concurrent logins cannot race each other."""
 55    remote_ip = ClientIPMiddleware.get_client_ip(request)
 56    settings = get_system_settings()
 57    initial = max(settings.reputation_lower_limit, min(settings.reputation_upper_limit, 1))
 58
 59    with postgres_manager(Reputation) as manager:
 60        reputation = manager.on_conflict(
 61            ["ip", "identifier"],
 62            ConflictAction.UPDATE,
 63            update_values=dict(
 64                score=Greatest(
 65                    settings.reputation_lower_limit,
 66                    Least(
 67                        settings.reputation_upper_limit,
 68                        Case(
 69                            When(score__lt=0, then=Value(0)),
 70                            default=F("score") + 1,
 71                        ),
 72                    ),
 73                ),
 74            ),
 75        ).insert_and_get(
 76            ip=remote_ip,
 77            identifier=identifier,
 78            score=initial,
 79            ip_geo_data=GEOIP_CONTEXT_PROCESSOR.city_dict(remote_ip) or {},
 80            ip_asn_data=ASN_CONTEXT_PROCESSOR.asn_dict(remote_ip) or {},
 81            expires=reputation_expiry(),
 82        )
 83
 84    LOGGER.info("Updated score", amount=reputation.score, for_user=identifier, for_ip=remote_ip)
 85
 86
 87@receiver(login_failed)
 88def handle_failed_login(sender, request, credentials, **_):
 89    """Lower Score for failed login attempts"""
 90    if "username" in credentials:
 91        update_score(request, credentials.get("username"), -1)
 92
 93
 94@receiver(identification_failed)
 95def handle_identification_failed(sender, request, uid_field: str, **_):
 96    """Lower Score for failed identification attempts"""
 97    update_score(request, uid_field, -1)
 98
 99
100@receiver(user_logged_in)
101def handle_successful_login(sender, request, user, **_):
102    """Reset a negative score, otherwise raise it, for successful attempts"""
103    update_score_on_login(request, user.username)
LOGGER = <BoundLoggerLazyProxy(logger=None, wrapper_class=None, processors=None, context_class=None, initial_values={}, logger_factory_args=())>
def update_score( request: django.http.request.HttpRequest, identifier: str, amount: int):
24def update_score(request: HttpRequest, identifier: str, amount: int):
25    """Update score for IP and User"""
26    remote_ip = ClientIPMiddleware.get_client_ip(request)
27    settings = get_system_settings()
28    amount = max(settings.reputation_lower_limit, min(settings.reputation_upper_limit, amount))
29
30    with postgres_manager(Reputation) as manager:
31        reputation = manager.on_conflict(
32            ["ip", "identifier"],
33            ConflictAction.UPDATE,
34            update_values=dict(
35                score=Greatest(
36                    settings.reputation_lower_limit,
37                    Least(settings.reputation_upper_limit, F("score") + amount),
38                ),
39            ),
40        ).insert_and_get(
41            ip=remote_ip,
42            identifier=identifier,
43            score=amount,
44            ip_geo_data=GEOIP_CONTEXT_PROCESSOR.city_dict(remote_ip) or {},
45            ip_asn_data=ASN_CONTEXT_PROCESSOR.asn_dict(remote_ip) or {},
46            expires=reputation_expiry(),
47        )
48
49    LOGGER.info("Updated score", amount=reputation.score, for_user=identifier, for_ip=remote_ip)

Update score for IP and User

def update_score_on_login(request: django.http.request.HttpRequest, identifier: str):
52def update_score_on_login(request: HttpRequest, identifier: str):
53    """Update score for IP and User on a successful login: a negative score is reset
54    to 0, any other score is raised by 1. Both branches happen in the same statement
55    so that concurrent logins cannot race each other."""
56    remote_ip = ClientIPMiddleware.get_client_ip(request)
57    settings = get_system_settings()
58    initial = max(settings.reputation_lower_limit, min(settings.reputation_upper_limit, 1))
59
60    with postgres_manager(Reputation) as manager:
61        reputation = manager.on_conflict(
62            ["ip", "identifier"],
63            ConflictAction.UPDATE,
64            update_values=dict(
65                score=Greatest(
66                    settings.reputation_lower_limit,
67                    Least(
68                        settings.reputation_upper_limit,
69                        Case(
70                            When(score__lt=0, then=Value(0)),
71                            default=F("score") + 1,
72                        ),
73                    ),
74                ),
75            ),
76        ).insert_and_get(
77            ip=remote_ip,
78            identifier=identifier,
79            score=initial,
80            ip_geo_data=GEOIP_CONTEXT_PROCESSOR.city_dict(remote_ip) or {},
81            ip_asn_data=ASN_CONTEXT_PROCESSOR.asn_dict(remote_ip) or {},
82            expires=reputation_expiry(),
83        )
84
85    LOGGER.info("Updated score", amount=reputation.score, for_user=identifier, for_ip=remote_ip)

Update score for IP and User on a successful login: a negative score is reset to 0, any other score is raised by 1. Both branches happen in the same statement so that concurrent logins cannot race each other.

@receiver(login_failed)
def handle_failed_login(sender, request, credentials, **_):
88@receiver(login_failed)
89def handle_failed_login(sender, request, credentials, **_):
90    """Lower Score for failed login attempts"""
91    if "username" in credentials:
92        update_score(request, credentials.get("username"), -1)

Lower Score for failed login attempts

@receiver(identification_failed)
def handle_identification_failed(sender, request, uid_field: str, **_):
95@receiver(identification_failed)
96def handle_identification_failed(sender, request, uid_field: str, **_):
97    """Lower Score for failed identification attempts"""
98    update_score(request, uid_field, -1)

Lower Score for failed identification attempts

@receiver(user_logged_in)
def handle_successful_login(sender, request, user, **_):
101@receiver(user_logged_in)
102def handle_successful_login(sender, request, user, **_):
103    """Reset a negative score, otherwise raise it, for successful attempts"""
104    update_score_on_login(request, user.username)

Reset a negative score, otherwise raise it, for successful attempts