authentik.enterprise.policies.unique_password.models
1from hashlib import sha1 2 3from django.contrib.auth.hashers import identify_hasher, make_password 4from django.db import models 5from django.utils.translation import gettext_lazy as _ 6from rest_framework.serializers import BaseSerializer 7from structlog.stdlib import get_logger 8 9from authentik.core.models import User 10from authentik.policies.models import Policy 11from authentik.policies.types import PolicyRequest, PolicyResult 12from authentik.stages.prompt.stage import PLAN_CONTEXT_PROMPT 13 14LOGGER = get_logger() 15 16 17class UniquePasswordPolicy(Policy): 18 """This policy prevents users from reusing old passwords.""" 19 20 password_field = models.TextField( 21 default="password", 22 help_text=_("Field key to check, field keys defined in Prompt stages are available."), 23 ) 24 25 # Limit on the number of previous passwords the policy evaluates 26 # Also controls number of old passwords the system stores. 27 num_historical_passwords = models.PositiveIntegerField( 28 default=1, 29 help_text=_("Number of passwords to check against."), 30 ) 31 32 @property 33 def serializer(self) -> type[BaseSerializer]: 34 from authentik.enterprise.policies.unique_password.api import UniquePasswordPolicySerializer 35 36 return UniquePasswordPolicySerializer 37 38 @property 39 def component(self) -> str: 40 return "ak-policy-password-uniqueness-form" 41 42 def passes(self, request: PolicyRequest) -> PolicyResult: 43 from authentik.enterprise.policies.unique_password.models import UserPasswordHistory 44 45 password = request.context.get(PLAN_CONTEXT_PROMPT, {}).get( 46 self.password_field, request.context.get(self.password_field) 47 ) 48 if not password: 49 LOGGER.warning( 50 "Password field not found in request when checking UniquePasswordPolicy", 51 field=self.password_field, 52 fields=request.context.keys(), 53 ) 54 return PolicyResult(False, str(_("Password not set in context"))) 55 password = str(password) 56 57 if not self.num_historical_passwords: 58 # Policy not configured to check against any passwords 59 return PolicyResult(True) 60 61 num_to_check = self.num_historical_passwords 62 password_history = UserPasswordHistory.objects.filter(user=request.user).order_by( 63 "-created_at" 64 )[:num_to_check] 65 66 if not password_history: 67 return PolicyResult(True) 68 69 for record in password_history: 70 if not record.old_password: 71 continue 72 73 if self._passwords_match(new_password=password, old_password=record.old_password): 74 # Return on first match. Authentik does not consider timing attacks 75 # on old passwords to be an attack surface. 76 return PolicyResult( 77 False, 78 str( 79 _("This password has been used previously. Please choose a different one.") 80 ), 81 ) 82 83 return PolicyResult(True) 84 85 def _passwords_match(self, *, new_password: str, old_password: str) -> bool: 86 try: 87 hasher = identify_hasher(old_password) 88 except ValueError: 89 LOGGER.warning( 90 "Skipping password; could not load hash algorithm", 91 ) 92 return False 93 94 return hasher.verify(new_password, old_password) 95 96 @classmethod 97 def is_in_use(cls): 98 """Check if any UniquePasswordPolicy is in use, either through policy bindings 99 or direct attachment to a PromptStage. 100 101 Returns: 102 bool: True if any policy is in use, False otherwise 103 """ 104 from authentik.policies.models import PolicyBinding 105 106 # Check if any policy is in use through bindings 107 if PolicyBinding.in_use.for_policy(cls).exists(): 108 return True 109 110 # Check if any policy is attached to a PromptStage 111 if cls.objects.filter(promptstage__isnull=False).exists(): 112 return True 113 114 return False 115 116 class Meta(Policy.PolicyMeta): 117 verbose_name = _("Password Uniqueness Policy") 118 verbose_name_plural = _("Password Uniqueness Policies") 119 120 121class UserPasswordHistory(models.Model): 122 user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="old_passwords") 123 # Mimic's column type of AbstractBaseUser.password 124 old_password = models.CharField(max_length=128) 125 created_at = models.DateTimeField(auto_now_add=True) 126 127 hibp_prefix_sha1 = models.CharField(max_length=5) 128 hibp_pw_hash = models.TextField() 129 130 class Meta: 131 verbose_name = _("User Password History") 132 133 def __str__(self) -> str: 134 timestamp = f"{self.created_at:%Y/%m/%d %X}" if self.created_at else "N/A" 135 return f"Previous Password (user: {self.user_id}, recorded: {timestamp})" 136 137 @classmethod 138 def create_for_user(cls, user: User, password: str): 139 # To check users' passwords against Have I been Pwned, we need the first 5 chars 140 # of the password hashed with SHA1 without a salt... 141 pw_hash_sha1 = sha1(password.encode("utf-8")).hexdigest() # nosec 142 # ...however that'll give us a list of hashes from HIBP, and to compare that we still 143 # need a full unsalted SHA1 of the password. We don't want to save that directly in 144 # the database, so we hash that SHA1 again with a modern hashing alg, 145 # and then when we check users' passwords against HIBP we can use `check_password` 146 # which will take care of this. 147 hibp_hash_hash = make_password(pw_hash_sha1) 148 return cls.objects.create( 149 user=user, 150 old_password=password, 151 hibp_prefix_sha1=pw_hash_sha1[:5], 152 hibp_pw_hash=hibp_hash_hash, 153 )
18class UniquePasswordPolicy(Policy): 19 """This policy prevents users from reusing old passwords.""" 20 21 password_field = models.TextField( 22 default="password", 23 help_text=_("Field key to check, field keys defined in Prompt stages are available."), 24 ) 25 26 # Limit on the number of previous passwords the policy evaluates 27 # Also controls number of old passwords the system stores. 28 num_historical_passwords = models.PositiveIntegerField( 29 default=1, 30 help_text=_("Number of passwords to check against."), 31 ) 32 33 @property 34 def serializer(self) -> type[BaseSerializer]: 35 from authentik.enterprise.policies.unique_password.api import UniquePasswordPolicySerializer 36 37 return UniquePasswordPolicySerializer 38 39 @property 40 def component(self) -> str: 41 return "ak-policy-password-uniqueness-form" 42 43 def passes(self, request: PolicyRequest) -> PolicyResult: 44 from authentik.enterprise.policies.unique_password.models import UserPasswordHistory 45 46 password = request.context.get(PLAN_CONTEXT_PROMPT, {}).get( 47 self.password_field, request.context.get(self.password_field) 48 ) 49 if not password: 50 LOGGER.warning( 51 "Password field not found in request when checking UniquePasswordPolicy", 52 field=self.password_field, 53 fields=request.context.keys(), 54 ) 55 return PolicyResult(False, str(_("Password not set in context"))) 56 password = str(password) 57 58 if not self.num_historical_passwords: 59 # Policy not configured to check against any passwords 60 return PolicyResult(True) 61 62 num_to_check = self.num_historical_passwords 63 password_history = UserPasswordHistory.objects.filter(user=request.user).order_by( 64 "-created_at" 65 )[:num_to_check] 66 67 if not password_history: 68 return PolicyResult(True) 69 70 for record in password_history: 71 if not record.old_password: 72 continue 73 74 if self._passwords_match(new_password=password, old_password=record.old_password): 75 # Return on first match. Authentik does not consider timing attacks 76 # on old passwords to be an attack surface. 77 return PolicyResult( 78 False, 79 str( 80 _("This password has been used previously. Please choose a different one.") 81 ), 82 ) 83 84 return PolicyResult(True) 85 86 def _passwords_match(self, *, new_password: str, old_password: str) -> bool: 87 try: 88 hasher = identify_hasher(old_password) 89 except ValueError: 90 LOGGER.warning( 91 "Skipping password; could not load hash algorithm", 92 ) 93 return False 94 95 return hasher.verify(new_password, old_password) 96 97 @classmethod 98 def is_in_use(cls): 99 """Check if any UniquePasswordPolicy is in use, either through policy bindings 100 or direct attachment to a PromptStage. 101 102 Returns: 103 bool: True if any policy is in use, False otherwise 104 """ 105 from authentik.policies.models import PolicyBinding 106 107 # Check if any policy is in use through bindings 108 if PolicyBinding.in_use.for_policy(cls).exists(): 109 return True 110 111 # Check if any policy is attached to a PromptStage 112 if cls.objects.filter(promptstage__isnull=False).exists(): 113 return True 114 115 return False 116 117 class Meta(Policy.PolicyMeta): 118 verbose_name = _("Password Uniqueness Policy") 119 verbose_name_plural = _("Password Uniqueness Policies")
This policy prevents users from reusing old passwords.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
33 @property 34 def serializer(self) -> type[BaseSerializer]: 35 from authentik.enterprise.policies.unique_password.api import UniquePasswordPolicySerializer 36 37 return UniquePasswordPolicySerializer
Get serializer for this model
43 def passes(self, request: PolicyRequest) -> PolicyResult: 44 from authentik.enterprise.policies.unique_password.models import UserPasswordHistory 45 46 password = request.context.get(PLAN_CONTEXT_PROMPT, {}).get( 47 self.password_field, request.context.get(self.password_field) 48 ) 49 if not password: 50 LOGGER.warning( 51 "Password field not found in request when checking UniquePasswordPolicy", 52 field=self.password_field, 53 fields=request.context.keys(), 54 ) 55 return PolicyResult(False, str(_("Password not set in context"))) 56 password = str(password) 57 58 if not self.num_historical_passwords: 59 # Policy not configured to check against any passwords 60 return PolicyResult(True) 61 62 num_to_check = self.num_historical_passwords 63 password_history = UserPasswordHistory.objects.filter(user=request.user).order_by( 64 "-created_at" 65 )[:num_to_check] 66 67 if not password_history: 68 return PolicyResult(True) 69 70 for record in password_history: 71 if not record.old_password: 72 continue 73 74 if self._passwords_match(new_password=password, old_password=record.old_password): 75 # Return on first match. Authentik does not consider timing attacks 76 # on old passwords to be an attack surface. 77 return PolicyResult( 78 False, 79 str( 80 _("This password has been used previously. Please choose a different one.") 81 ), 82 ) 83 84 return PolicyResult(True)
Check if request passes this policy
97 @classmethod 98 def is_in_use(cls): 99 """Check if any UniquePasswordPolicy is in use, either through policy bindings 100 or direct attachment to a PromptStage. 101 102 Returns: 103 bool: True if any policy is in use, False otherwise 104 """ 105 from authentik.policies.models import PolicyBinding 106 107 # Check if any policy is in use through bindings 108 if PolicyBinding.in_use.for_policy(cls).exists(): 109 return True 110 111 # Check if any policy is attached to a PromptStage 112 if cls.objects.filter(promptstage__isnull=False).exists(): 113 return True 114 115 return False
Check if any UniquePasswordPolicy is in use, either through policy bindings or direct attachment to a PromptStage.
Returns: bool: True if any policy is in use, False otherwise
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.
Inherited Members
- authentik.policies.models.Policy
- policy_uuid
- name
- execution_logging
- objects
- PolicyMeta
- created
- last_updated
- get_next_by_created
- get_previous_by_created
- get_next_by_last_updated
- get_previous_by_last_updated
- bindings
- dummypolicy
- eventmatcherpolicy
- passwordexpirypolicy
- reputationpolicy
- expressionpolicy
- geoippolicy
- promptstage_set
- promptstagevalidationpolicy_set
- passwordpolicy
- uniquepasswordpolicy
The requested object does not exist
The query returned multiple objects when only one was expected.
122class UserPasswordHistory(models.Model): 123 user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="old_passwords") 124 # Mimic's column type of AbstractBaseUser.password 125 old_password = models.CharField(max_length=128) 126 created_at = models.DateTimeField(auto_now_add=True) 127 128 hibp_prefix_sha1 = models.CharField(max_length=5) 129 hibp_pw_hash = models.TextField() 130 131 class Meta: 132 verbose_name = _("User Password History") 133 134 def __str__(self) -> str: 135 timestamp = f"{self.created_at:%Y/%m/%d %X}" if self.created_at else "N/A" 136 return f"Previous Password (user: {self.user_id}, recorded: {timestamp})" 137 138 @classmethod 139 def create_for_user(cls, user: User, password: str): 140 # To check users' passwords against Have I been Pwned, we need the first 5 chars 141 # of the password hashed with SHA1 without a salt... 142 pw_hash_sha1 = sha1(password.encode("utf-8")).hexdigest() # nosec 143 # ...however that'll give us a list of hashes from HIBP, and to compare that we still 144 # need a full unsalted SHA1 of the password. We don't want to save that directly in 145 # the database, so we hash that SHA1 again with a modern hashing alg, 146 # and then when we check users' passwords against HIBP we can use `check_password` 147 # which will take care of this. 148 hibp_hash_hash = make_password(pw_hash_sha1) 149 return cls.objects.create( 150 user=user, 151 old_password=password, 152 hibp_prefix_sha1=pw_hash_sha1[:5], 153 hibp_pw_hash=hibp_hash_hash, 154 )
UserPasswordHistory(id, user, old_password, created_at, hibp_prefix_sha1, hibp_pw_hash)
Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.
In the example::
class Child(Model):
parent = ForeignKey(Parent, related_name='children')
Child.parent is a ForwardManyToOneDescriptor instance.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
138 @classmethod 139 def create_for_user(cls, user: User, password: str): 140 # To check users' passwords against Have I been Pwned, we need the first 5 chars 141 # of the password hashed with SHA1 without a salt... 142 pw_hash_sha1 = sha1(password.encode("utf-8")).hexdigest() # nosec 143 # ...however that'll give us a list of hashes from HIBP, and to compare that we still 144 # need a full unsalted SHA1 of the password. We don't want to save that directly in 145 # the database, so we hash that SHA1 again with a modern hashing alg, 146 # and then when we check users' passwords against HIBP we can use `check_password` 147 # which will take care of this. 148 hibp_hash_hash = make_password(pw_hash_sha1) 149 return cls.objects.create( 150 user=user, 151 old_password=password, 152 hibp_prefix_sha1=pw_hash_sha1[:5], 153 hibp_pw_hash=hibp_hash_hash, 154 )
Method descriptor with partial application of the given arguments and keywords.
Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.
Method descriptor with partial application of the given arguments and keywords.
Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.
The requested object does not exist
The query returned multiple objects when only one was expected.