authentik.policies.geoip.models

GeoIP policy

  1"""GeoIP policy"""
  2
  3from itertools import chain
  4
  5from django.contrib.postgres.fields import ArrayField
  6from django.db import models
  7from django.utils.timezone import now
  8from django.utils.translation import gettext_lazy as _
  9from django_countries.fields import CountryField
 10from rest_framework.serializers import BaseSerializer
 11
 12from authentik.events.context_processors.geoip import GeoIPDict
 13from authentik.events.models import Event, EventAction
 14from authentik.policies.exceptions import PolicyException
 15from authentik.policies.geoip.exceptions import GeoIPNotFoundException
 16from authentik.policies.models import Policy
 17from authentik.policies.types import PolicyRequest, PolicyResult
 18
 19MAX_DISTANCE_HOUR_KM = 1000
 20
 21
 22class GeoIPPolicy(Policy):
 23    """Ensure the user satisfies requirements of geography or network topology, based on IP
 24    address."""
 25
 26    asns = ArrayField(models.IntegerField(), blank=True, default=list)
 27    countries = CountryField(multiple=True, blank=True)
 28
 29    distance_tolerance_km = models.PositiveIntegerField(default=50)
 30
 31    check_history_distance = models.BooleanField(default=False)
 32    history_max_distance_km = models.PositiveBigIntegerField(default=100)
 33    history_login_count = models.PositiveIntegerField(default=5)
 34
 35    check_impossible_travel = models.BooleanField(default=False)
 36    impossible_tolerance_km = models.PositiveIntegerField(default=100)
 37
 38    @property
 39    def serializer(self) -> type[BaseSerializer]:
 40        from authentik.policies.geoip.api import GeoIPPolicySerializer
 41
 42        return GeoIPPolicySerializer
 43
 44    @property
 45    def component(self) -> str:  # pragma: no cover
 46        return "ak-policy-geoip-form"
 47
 48    def passes(self, request: PolicyRequest) -> PolicyResult:
 49        """
 50        Passes if any of the following is true:
 51        - the client IP is advertised by an autonomous system with ASN in the `asns`
 52        - the client IP is geolocated in a country of `countries`
 53        """
 54        static_results: list[PolicyResult] = []
 55        dynamic_results: list[PolicyResult] = []
 56
 57        if self.asns:
 58            static_results.append(self.passes_asn(request))
 59        if self.countries:
 60            static_results.append(self.passes_country(request))
 61
 62        if self.check_history_distance or self.check_impossible_travel:
 63            dynamic_results.append(self.passes_distance(request))
 64
 65        if not static_results and not dynamic_results:
 66            return PolicyResult(True)
 67
 68        static_passing = any(r.passing for r in static_results) if static_results else True
 69        dynamic_passing = all(r.passing for r in dynamic_results)
 70        passing = static_passing and dynamic_passing
 71        messages = chain(
 72            *[r.messages for r in static_results], *[r.messages for r in dynamic_results]
 73        )
 74
 75        result = PolicyResult(passing, *messages)
 76        result.source_results = list(chain(static_results, dynamic_results))
 77
 78        return result
 79
 80    def passes_asn(self, request: PolicyRequest) -> PolicyResult:
 81        # This is not a single get chain because `request.context` can contain `{ "asn": None }`.
 82        asn_data = request.context.get("asn")
 83        asn = asn_data.get("asn") if asn_data else None
 84
 85        if not asn:
 86            raise PolicyException(
 87                GeoIPNotFoundException(str(_("GeoIP: client IP not found in ASN database.")))
 88            )
 89
 90        if asn not in self.asns:
 91            message = str(_("Client IP is not part of an allowed autonomous system."))
 92            return PolicyResult(False, message)
 93
 94        return PolicyResult(True)
 95
 96    def passes_country(self, request: PolicyRequest) -> PolicyResult:
 97        # This is not a single get chain because `request.context` can contain `{ "geoip": None }`.
 98        geoip_data: GeoIPDict | None = request.context.get("geoip")
 99        country = geoip_data.get("country") if geoip_data else None
100
101        if not country:
102            raise PolicyException(
103                GeoIPNotFoundException(
104                    str(_("GeoIP: client IP address not found in City database."))
105                )
106            )
107
108        if country not in self.countries:
109            message = str(_("Client IP is not in an allowed country."))
110            return PolicyResult(False, message)
111
112        return PolicyResult(True)
113
114    def passes_distance(self, request: PolicyRequest) -> PolicyResult:
115        """Check if current policy execution is out of distance range compared
116        to previous authentication requests"""
117        from geopy import distance
118
119        # Get previous login event and GeoIP data
120        previous_logins = Event.objects.filter(
121            action=EventAction.LOGIN,
122            user__pk=request.user.pk,  # context__geo__isnull=False
123        ).order_by("-created")[: self.history_login_count]
124        _now = now()
125        geoip_data: GeoIPDict | None = request.context.get("geoip")
126        if not geoip_data:
127            return PolicyResult(False)
128        if not previous_logins.exists():
129            return PolicyResult(True)
130        result = False
131        for previous_login in previous_logins:
132            if "geo" not in previous_login.context:
133                continue
134            previous_login_geoip: GeoIPDict = previous_login.context["geo"]
135
136            # Figure out distance
137            dist = distance.geodesic(
138                (previous_login_geoip["lat"], previous_login_geoip["long"]),
139                (geoip_data["lat"], geoip_data["long"]),
140            )
141            if self.check_history_distance and dist.km >= (
142                self.history_max_distance_km + self.distance_tolerance_km
143            ):
144                return PolicyResult(
145                    False,
146                    str(_("Distance from previous authentication is larger than threshold.")),
147                )
148            # Check if distance between `previous_login` and now is more
149            # than max distance per hour times the amount of hours since the previous login
150            # (round down to the lowest closest time of hours)
151            # clamped to be at least 1 hour
152            rel_time_hours = max(int((_now - previous_login.created).total_seconds() / 3600), 1)
153            if self.check_impossible_travel and dist.km >= (
154                (MAX_DISTANCE_HOUR_KM * rel_time_hours) + self.distance_tolerance_km
155            ):
156                return PolicyResult(False, str(_("Distance is further than possible.")))
157            result = True
158        return PolicyResult(result)
159
160    class Meta(Policy.PolicyMeta):
161        verbose_name = _("GeoIP Policy")
162        verbose_name_plural = _("GeoIP Policies")
MAX_DISTANCE_HOUR_KM = 1000
class GeoIPPolicy(authentik.policies.models.Policy):
 23class GeoIPPolicy(Policy):
 24    """Ensure the user satisfies requirements of geography or network topology, based on IP
 25    address."""
 26
 27    asns = ArrayField(models.IntegerField(), blank=True, default=list)
 28    countries = CountryField(multiple=True, blank=True)
 29
 30    distance_tolerance_km = models.PositiveIntegerField(default=50)
 31
 32    check_history_distance = models.BooleanField(default=False)
 33    history_max_distance_km = models.PositiveBigIntegerField(default=100)
 34    history_login_count = models.PositiveIntegerField(default=5)
 35
 36    check_impossible_travel = models.BooleanField(default=False)
 37    impossible_tolerance_km = models.PositiveIntegerField(default=100)
 38
 39    @property
 40    def serializer(self) -> type[BaseSerializer]:
 41        from authentik.policies.geoip.api import GeoIPPolicySerializer
 42
 43        return GeoIPPolicySerializer
 44
 45    @property
 46    def component(self) -> str:  # pragma: no cover
 47        return "ak-policy-geoip-form"
 48
 49    def passes(self, request: PolicyRequest) -> PolicyResult:
 50        """
 51        Passes if any of the following is true:
 52        - the client IP is advertised by an autonomous system with ASN in the `asns`
 53        - the client IP is geolocated in a country of `countries`
 54        """
 55        static_results: list[PolicyResult] = []
 56        dynamic_results: list[PolicyResult] = []
 57
 58        if self.asns:
 59            static_results.append(self.passes_asn(request))
 60        if self.countries:
 61            static_results.append(self.passes_country(request))
 62
 63        if self.check_history_distance or self.check_impossible_travel:
 64            dynamic_results.append(self.passes_distance(request))
 65
 66        if not static_results and not dynamic_results:
 67            return PolicyResult(True)
 68
 69        static_passing = any(r.passing for r in static_results) if static_results else True
 70        dynamic_passing = all(r.passing for r in dynamic_results)
 71        passing = static_passing and dynamic_passing
 72        messages = chain(
 73            *[r.messages for r in static_results], *[r.messages for r in dynamic_results]
 74        )
 75
 76        result = PolicyResult(passing, *messages)
 77        result.source_results = list(chain(static_results, dynamic_results))
 78
 79        return result
 80
 81    def passes_asn(self, request: PolicyRequest) -> PolicyResult:
 82        # This is not a single get chain because `request.context` can contain `{ "asn": None }`.
 83        asn_data = request.context.get("asn")
 84        asn = asn_data.get("asn") if asn_data else None
 85
 86        if not asn:
 87            raise PolicyException(
 88                GeoIPNotFoundException(str(_("GeoIP: client IP not found in ASN database.")))
 89            )
 90
 91        if asn not in self.asns:
 92            message = str(_("Client IP is not part of an allowed autonomous system."))
 93            return PolicyResult(False, message)
 94
 95        return PolicyResult(True)
 96
 97    def passes_country(self, request: PolicyRequest) -> PolicyResult:
 98        # This is not a single get chain because `request.context` can contain `{ "geoip": None }`.
 99        geoip_data: GeoIPDict | None = request.context.get("geoip")
100        country = geoip_data.get("country") if geoip_data else None
101
102        if not country:
103            raise PolicyException(
104                GeoIPNotFoundException(
105                    str(_("GeoIP: client IP address not found in City database."))
106                )
107            )
108
109        if country not in self.countries:
110            message = str(_("Client IP is not in an allowed country."))
111            return PolicyResult(False, message)
112
113        return PolicyResult(True)
114
115    def passes_distance(self, request: PolicyRequest) -> PolicyResult:
116        """Check if current policy execution is out of distance range compared
117        to previous authentication requests"""
118        from geopy import distance
119
120        # Get previous login event and GeoIP data
121        previous_logins = Event.objects.filter(
122            action=EventAction.LOGIN,
123            user__pk=request.user.pk,  # context__geo__isnull=False
124        ).order_by("-created")[: self.history_login_count]
125        _now = now()
126        geoip_data: GeoIPDict | None = request.context.get("geoip")
127        if not geoip_data:
128            return PolicyResult(False)
129        if not previous_logins.exists():
130            return PolicyResult(True)
131        result = False
132        for previous_login in previous_logins:
133            if "geo" not in previous_login.context:
134                continue
135            previous_login_geoip: GeoIPDict = previous_login.context["geo"]
136
137            # Figure out distance
138            dist = distance.geodesic(
139                (previous_login_geoip["lat"], previous_login_geoip["long"]),
140                (geoip_data["lat"], geoip_data["long"]),
141            )
142            if self.check_history_distance and dist.km >= (
143                self.history_max_distance_km + self.distance_tolerance_km
144            ):
145                return PolicyResult(
146                    False,
147                    str(_("Distance from previous authentication is larger than threshold.")),
148                )
149            # Check if distance between `previous_login` and now is more
150            # than max distance per hour times the amount of hours since the previous login
151            # (round down to the lowest closest time of hours)
152            # clamped to be at least 1 hour
153            rel_time_hours = max(int((_now - previous_login.created).total_seconds() / 3600), 1)
154            if self.check_impossible_travel and dist.km >= (
155                (MAX_DISTANCE_HOUR_KM * rel_time_hours) + self.distance_tolerance_km
156            ):
157                return PolicyResult(False, str(_("Distance is further than possible.")))
158            result = True
159        return PolicyResult(result)
160
161    class Meta(Policy.PolicyMeta):
162        verbose_name = _("GeoIP Policy")
163        verbose_name_plural = _("GeoIP Policies")

Ensure the user satisfies requirements of geography or network topology, based on IP address.

def asns(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

countries

A descriptor for country fields on a model instance. Returns a Country when accessed so you can do things like::

>>> from people import Person
>>> person = Person.object.get(name='Chris')

>>> person.country.name
'New Zealand'

>>> person.country.flag
'/static/flags/nz.gif'
def distance_tolerance_km(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def check_history_distance(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def history_max_distance_km(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def history_login_count(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def check_impossible_travel(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def impossible_tolerance_km(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

serializer: type[rest_framework.serializers.BaseSerializer]
39    @property
40    def serializer(self) -> type[BaseSerializer]:
41        from authentik.policies.geoip.api import GeoIPPolicySerializer
42
43        return GeoIPPolicySerializer

Get serializer for this model

component: str
45    @property
46    def component(self) -> str:  # pragma: no cover
47        return "ak-policy-geoip-form"

Return component used to edit this object

49    def passes(self, request: PolicyRequest) -> PolicyResult:
50        """
51        Passes if any of the following is true:
52        - the client IP is advertised by an autonomous system with ASN in the `asns`
53        - the client IP is geolocated in a country of `countries`
54        """
55        static_results: list[PolicyResult] = []
56        dynamic_results: list[PolicyResult] = []
57
58        if self.asns:
59            static_results.append(self.passes_asn(request))
60        if self.countries:
61            static_results.append(self.passes_country(request))
62
63        if self.check_history_distance or self.check_impossible_travel:
64            dynamic_results.append(self.passes_distance(request))
65
66        if not static_results and not dynamic_results:
67            return PolicyResult(True)
68
69        static_passing = any(r.passing for r in static_results) if static_results else True
70        dynamic_passing = all(r.passing for r in dynamic_results)
71        passing = static_passing and dynamic_passing
72        messages = chain(
73            *[r.messages for r in static_results], *[r.messages for r in dynamic_results]
74        )
75
76        result = PolicyResult(passing, *messages)
77        result.source_results = list(chain(static_results, dynamic_results))
78
79        return result

Passes if any of the following is true:

  • the client IP is advertised by an autonomous system with ASN in the asns
  • the client IP is geolocated in a country of countries
def passes_asn( self, request: authentik.policies.types.PolicyRequest) -> authentik.policies.types.PolicyResult:
81    def passes_asn(self, request: PolicyRequest) -> PolicyResult:
82        # This is not a single get chain because `request.context` can contain `{ "asn": None }`.
83        asn_data = request.context.get("asn")
84        asn = asn_data.get("asn") if asn_data else None
85
86        if not asn:
87            raise PolicyException(
88                GeoIPNotFoundException(str(_("GeoIP: client IP not found in ASN database.")))
89            )
90
91        if asn not in self.asns:
92            message = str(_("Client IP is not part of an allowed autonomous system."))
93            return PolicyResult(False, message)
94
95        return PolicyResult(True)
def passes_country( self, request: authentik.policies.types.PolicyRequest) -> authentik.policies.types.PolicyResult:
 97    def passes_country(self, request: PolicyRequest) -> PolicyResult:
 98        # This is not a single get chain because `request.context` can contain `{ "geoip": None }`.
 99        geoip_data: GeoIPDict | None = request.context.get("geoip")
100        country = geoip_data.get("country") if geoip_data else None
101
102        if not country:
103            raise PolicyException(
104                GeoIPNotFoundException(
105                    str(_("GeoIP: client IP address not found in City database."))
106                )
107            )
108
109        if country not in self.countries:
110            message = str(_("Client IP is not in an allowed country."))
111            return PolicyResult(False, message)
112
113        return PolicyResult(True)
def passes_distance( self, request: authentik.policies.types.PolicyRequest) -> authentik.policies.types.PolicyResult:
115    def passes_distance(self, request: PolicyRequest) -> PolicyResult:
116        """Check if current policy execution is out of distance range compared
117        to previous authentication requests"""
118        from geopy import distance
119
120        # Get previous login event and GeoIP data
121        previous_logins = Event.objects.filter(
122            action=EventAction.LOGIN,
123            user__pk=request.user.pk,  # context__geo__isnull=False
124        ).order_by("-created")[: self.history_login_count]
125        _now = now()
126        geoip_data: GeoIPDict | None = request.context.get("geoip")
127        if not geoip_data:
128            return PolicyResult(False)
129        if not previous_logins.exists():
130            return PolicyResult(True)
131        result = False
132        for previous_login in previous_logins:
133            if "geo" not in previous_login.context:
134                continue
135            previous_login_geoip: GeoIPDict = previous_login.context["geo"]
136
137            # Figure out distance
138            dist = distance.geodesic(
139                (previous_login_geoip["lat"], previous_login_geoip["long"]),
140                (geoip_data["lat"], geoip_data["long"]),
141            )
142            if self.check_history_distance and dist.km >= (
143                self.history_max_distance_km + self.distance_tolerance_km
144            ):
145                return PolicyResult(
146                    False,
147                    str(_("Distance from previous authentication is larger than threshold.")),
148                )
149            # Check if distance between `previous_login` and now is more
150            # than max distance per hour times the amount of hours since the previous login
151            # (round down to the lowest closest time of hours)
152            # clamped to be at least 1 hour
153            rel_time_hours = max(int((_now - previous_login.created).total_seconds() / 3600), 1)
154            if self.check_impossible_travel and dist.km >= (
155                (MAX_DISTANCE_HOUR_KM * rel_time_hours) + self.distance_tolerance_km
156            ):
157                return PolicyResult(False, str(_("Distance is further than possible.")))
158            result = True
159        return PolicyResult(result)

Check if current policy execution is out of distance range compared to previous authentication requests

def get_countries_display(unknown):

Method descriptor with partial application of the given arguments and keywords.

Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.

policy_ptr_id
policy_ptr

Accessor to the related object on the forward side of a one-to-one relation.

In the example::

class Restaurant(Model):
    place = OneToOneField(Place, related_name='restaurant')

Restaurant.place is a ForwardOneToOneDescriptor instance.

class GeoIPPolicy.DoesNotExist(authentik.policies.models.Policy.DoesNotExist):

The requested object does not exist

class GeoIPPolicy.MultipleObjectsReturned(authentik.policies.models.Policy.MultipleObjectsReturned):

The query returned multiple objects when only one was expected.