authentik.sources.ldap.password
Help validate and update passwords in LDAP
1"""Help validate and update passwords in LDAP""" 2 3from enum import IntFlag 4from re import split 5 6from structlog.stdlib import get_logger 7 8from authentik.core.models import User 9from authentik.sources.ldap.auth import LDAP_DISTINGUISHED_NAME 10from authentik.sources.ldap.models import LDAPSource 11 12LOGGER = get_logger() 13 14NON_ALPHA = r"~!@#$%^&*_-+=`|\(){}[]:;\"'<>,.?/" 15RE_DISPLAYNAME_SEPARATORS = r"[,._ #\t-]+" 16MIN_TOKEN_SIZE = 3 17# Defined in RFC 3062 Section 2 18PASSWD_MODIFY_OID = "1.3.6.1.4.1.4203.1.11.1" 19 20 21class PwdProperties(IntFlag): 22 """Possible values for the pwdProperties attribute""" 23 24 DOMAIN_PASSWORD_COMPLEX = 1 25 DOMAIN_PASSWORD_NO_ANON_CHANGE = 2 26 DOMAIN_PASSWORD_NO_CLEAR_CHANGE = 4 27 DOMAIN_LOCKOUT_ADMINS = 8 28 DOMAIN_PASSWORD_STORE_CLEARTEXT = 16 29 DOMAIN_REFUSE_PASSWORD_CHANGE = 32 30 31 32class PasswordCategories(IntFlag): 33 """Password categories as defined by Microsoft, a category can only be counted 34 once, hence intflag.""" 35 36 NONE = 0 37 ALPHA_LOWER = 1 38 ALPHA_UPPER = 2 39 ALPHA_OTHER = 4 40 NUMERIC = 8 41 SYMBOL = 16 42 43 44class LDAPPasswordChanger: 45 """Help validate and update passwords in LDAP""" 46 47 _source: LDAPSource 48 49 def __init__(self, source: LDAPSource) -> None: 50 self._source = source 51 self._connection = source.connection() 52 53 @staticmethod 54 def should_check_user(user: User) -> bool: 55 """Check if the user has LDAP parameters and needs to be checked""" 56 return LDAP_DISTINGUISHED_NAME in user.attributes 57 58 def get_domain_root_dn(self) -> str: 59 """Attempt to get root DN via MS specific fields or generic LDAP fields""" 60 info = self._connection.server.info 61 if "rootDomainNamingContext" in info.other: 62 return info.other["rootDomainNamingContext"][0] 63 naming_contexts = info.naming_contexts 64 naming_contexts.sort(key=len) 65 return naming_contexts[0] 66 67 def check_ad_password_complexity_enabled(self) -> bool: 68 """Check if DOMAIN_PASSWORD_COMPLEX is enabled""" 69 from ldap3 import BASE 70 from ldap3.core.exceptions import LDAPAttributeError, LDAPUnwillingToPerformResult 71 72 root_dn = self.get_domain_root_dn() 73 try: 74 root_attrs = self._connection.extend.standard.paged_search( 75 search_base=root_dn, 76 search_filter="(objectClass=*)", 77 search_scope=BASE, 78 attributes=["pwdProperties"], 79 ) 80 root_attrs = list(root_attrs)[0] 81 except LDAPAttributeError, LDAPUnwillingToPerformResult, KeyError, IndexError: 82 return False 83 raw_pwd_properties = root_attrs.get("attributes", {}).get("pwdProperties", None) 84 if not raw_pwd_properties: 85 return False 86 87 try: 88 pwd_properties = PwdProperties(raw_pwd_properties) 89 except ValueError: 90 return False 91 if PwdProperties.DOMAIN_PASSWORD_COMPLEX in pwd_properties: 92 return True 93 94 return False 95 96 def supports_password_modify_extension(self) -> bool: 97 info = self._connection.server.info 98 if info is None: 99 return True 100 return any( 101 extension[0] == PASSWD_MODIFY_OID for extension in info.supported_extensions or [] 102 ) 103 104 def change_password(self, user: User, password: str): 105 """Change user's password""" 106 from ldap3.core.exceptions import ( 107 LDAPAttributeError, 108 LDAPNoSuchAttributeResult, 109 LDAPUnwillingToPerformResult, 110 ) 111 112 user_dn = user.attributes.get(LDAP_DISTINGUISHED_NAME, None) 113 if not user_dn: 114 LOGGER.info(f"User has no {LDAP_DISTINGUISHED_NAME} set.") 115 return 116 try: 117 self._connection.extend.microsoft.modify_password(user_dn, password) 118 except LDAPAttributeError, LDAPUnwillingToPerformResult, LDAPNoSuchAttributeResult: 119 if not self.supports_password_modify_extension(): 120 raise 121 self._connection.extend.standard.modify_password(user_dn, new_password=password) 122 123 def _ad_check_password_existing(self, password: str, user_dn: str) -> bool: 124 """Check if a password contains sAMAccount or displayName""" 125 from ldap3 import BASE 126 127 users = list( 128 self._connection.extend.standard.paged_search( 129 search_base=user_dn, 130 search_filter=self._source.user_object_filter, 131 search_scope=BASE, 132 attributes=["displayName", "sAMAccountName"], 133 ) 134 ) 135 if len(users) != 1: 136 raise AssertionError() 137 user_attributes = users[0]["attributes"] 138 # If sAMAccountName is at least 3 chars, check if it is contained in the password 139 if len(user_attributes["sAMAccountName"]) >= MIN_TOKEN_SIZE: 140 if user_attributes["sAMAccountName"].lower() in password.lower(): 141 return False 142 # displayName is either a string or a list of strings 143 display_names = user_attributes["displayName"] 144 if isinstance(display_names, str): 145 display_names = [display_names] 146 # No display name set, can't check any further 147 if len(display_names) < 1: 148 return True 149 for display_name in display_names: 150 display_name_tokens = split(RE_DISPLAYNAME_SEPARATORS, display_name) 151 for token in display_name_tokens: 152 # Ignore tokens under 3 chars 153 if len(token) < MIN_TOKEN_SIZE: 154 continue 155 if token.lower() in password.lower(): 156 return False 157 return True 158 159 def ad_password_complexity(self, password: str, user: User | None = None) -> bool: 160 """Check if password matches Active directory password policies 161 162 https://docs.microsoft.com/en-us/windows/security/threat-protection/ 163 security-policy-settings/password-must-meet-complexity-requirements 164 """ 165 if user: 166 # Check if password contains sAMAccountName or displayNames 167 if LDAP_DISTINGUISHED_NAME in user.attributes: 168 existing_user_check = self._ad_check_password_existing( 169 password, user.attributes.get(LDAP_DISTINGUISHED_NAME) 170 ) 171 if not existing_user_check: 172 LOGGER.debug("Password failed name check", user=user) 173 return existing_user_check 174 175 # Step 2, match at least 3 of 5 categories 176 matched_categories = PasswordCategories.NONE 177 required = 3 178 for letter in password: 179 # Only match one category per letter, 180 if letter.islower(): 181 matched_categories |= PasswordCategories.ALPHA_LOWER 182 elif letter.isupper(): 183 matched_categories |= PasswordCategories.ALPHA_UPPER 184 elif not letter.isascii() and letter.isalpha(): 185 # Not exactly matching microsoft's policy, but count it as "Other unicode" char 186 # when its alpha and not ascii 187 matched_categories |= PasswordCategories.ALPHA_OTHER 188 elif letter.isnumeric(): 189 matched_categories |= PasswordCategories.NUMERIC 190 elif letter in NON_ALPHA: 191 matched_categories |= PasswordCategories.SYMBOL 192 if bin(matched_categories).count("1") < required: 193 LOGGER.debug( 194 "Password didn't match enough categories", 195 has=matched_categories, 196 must=required, 197 ) 198 return False 199 LOGGER.debug("Password matched categories", has=matched_categories, must=required) 200 return True
LOGGER =
<BoundLoggerLazyProxy(logger=None, wrapper_class=None, processors=None, context_class=None, initial_values={}, logger_factory_args=())>
NON_ALPHA =
'~!@#$%^&*_-+=`|\\(){}[]:;\\"\'<>,.?/'
RE_DISPLAYNAME_SEPARATORS =
'[,._ #\\t-]+'
MIN_TOKEN_SIZE =
3
PASSWD_MODIFY_OID =
'1.3.6.1.4.1.4203.1.11.1'
class
PwdProperties(enum.IntFlag):
22class PwdProperties(IntFlag): 23 """Possible values for the pwdProperties attribute""" 24 25 DOMAIN_PASSWORD_COMPLEX = 1 26 DOMAIN_PASSWORD_NO_ANON_CHANGE = 2 27 DOMAIN_PASSWORD_NO_CLEAR_CHANGE = 4 28 DOMAIN_LOCKOUT_ADMINS = 8 29 DOMAIN_PASSWORD_STORE_CLEARTEXT = 16 30 DOMAIN_REFUSE_PASSWORD_CHANGE = 32
Possible values for the pwdProperties attribute
DOMAIN_PASSWORD_COMPLEX =
<PwdProperties.DOMAIN_PASSWORD_COMPLEX: 1>
DOMAIN_PASSWORD_NO_ANON_CHANGE =
<PwdProperties.DOMAIN_PASSWORD_NO_ANON_CHANGE: 2>
DOMAIN_PASSWORD_NO_CLEAR_CHANGE =
<PwdProperties.DOMAIN_PASSWORD_NO_CLEAR_CHANGE: 4>
DOMAIN_LOCKOUT_ADMINS =
<PwdProperties.DOMAIN_LOCKOUT_ADMINS: 8>
DOMAIN_PASSWORD_STORE_CLEARTEXT =
<PwdProperties.DOMAIN_PASSWORD_STORE_CLEARTEXT: 16>
DOMAIN_REFUSE_PASSWORD_CHANGE =
<PwdProperties.DOMAIN_REFUSE_PASSWORD_CHANGE: 32>
class
PasswordCategories(enum.IntFlag):
33class PasswordCategories(IntFlag): 34 """Password categories as defined by Microsoft, a category can only be counted 35 once, hence intflag.""" 36 37 NONE = 0 38 ALPHA_LOWER = 1 39 ALPHA_UPPER = 2 40 ALPHA_OTHER = 4 41 NUMERIC = 8 42 SYMBOL = 16
Password categories as defined by Microsoft, a category can only be counted once, hence intflag.
NONE =
<PasswordCategories.NONE: 0>
ALPHA_LOWER =
<PasswordCategories.ALPHA_LOWER: 1>
ALPHA_UPPER =
<PasswordCategories.ALPHA_UPPER: 2>
ALPHA_OTHER =
<PasswordCategories.ALPHA_OTHER: 4>
NUMERIC =
<PasswordCategories.NUMERIC: 8>
SYMBOL =
<PasswordCategories.SYMBOL: 16>
class
LDAPPasswordChanger:
45class LDAPPasswordChanger: 46 """Help validate and update passwords in LDAP""" 47 48 _source: LDAPSource 49 50 def __init__(self, source: LDAPSource) -> None: 51 self._source = source 52 self._connection = source.connection() 53 54 @staticmethod 55 def should_check_user(user: User) -> bool: 56 """Check if the user has LDAP parameters and needs to be checked""" 57 return LDAP_DISTINGUISHED_NAME in user.attributes 58 59 def get_domain_root_dn(self) -> str: 60 """Attempt to get root DN via MS specific fields or generic LDAP fields""" 61 info = self._connection.server.info 62 if "rootDomainNamingContext" in info.other: 63 return info.other["rootDomainNamingContext"][0] 64 naming_contexts = info.naming_contexts 65 naming_contexts.sort(key=len) 66 return naming_contexts[0] 67 68 def check_ad_password_complexity_enabled(self) -> bool: 69 """Check if DOMAIN_PASSWORD_COMPLEX is enabled""" 70 from ldap3 import BASE 71 from ldap3.core.exceptions import LDAPAttributeError, LDAPUnwillingToPerformResult 72 73 root_dn = self.get_domain_root_dn() 74 try: 75 root_attrs = self._connection.extend.standard.paged_search( 76 search_base=root_dn, 77 search_filter="(objectClass=*)", 78 search_scope=BASE, 79 attributes=["pwdProperties"], 80 ) 81 root_attrs = list(root_attrs)[0] 82 except LDAPAttributeError, LDAPUnwillingToPerformResult, KeyError, IndexError: 83 return False 84 raw_pwd_properties = root_attrs.get("attributes", {}).get("pwdProperties", None) 85 if not raw_pwd_properties: 86 return False 87 88 try: 89 pwd_properties = PwdProperties(raw_pwd_properties) 90 except ValueError: 91 return False 92 if PwdProperties.DOMAIN_PASSWORD_COMPLEX in pwd_properties: 93 return True 94 95 return False 96 97 def supports_password_modify_extension(self) -> bool: 98 info = self._connection.server.info 99 if info is None: 100 return True 101 return any( 102 extension[0] == PASSWD_MODIFY_OID for extension in info.supported_extensions or [] 103 ) 104 105 def change_password(self, user: User, password: str): 106 """Change user's password""" 107 from ldap3.core.exceptions import ( 108 LDAPAttributeError, 109 LDAPNoSuchAttributeResult, 110 LDAPUnwillingToPerformResult, 111 ) 112 113 user_dn = user.attributes.get(LDAP_DISTINGUISHED_NAME, None) 114 if not user_dn: 115 LOGGER.info(f"User has no {LDAP_DISTINGUISHED_NAME} set.") 116 return 117 try: 118 self._connection.extend.microsoft.modify_password(user_dn, password) 119 except LDAPAttributeError, LDAPUnwillingToPerformResult, LDAPNoSuchAttributeResult: 120 if not self.supports_password_modify_extension(): 121 raise 122 self._connection.extend.standard.modify_password(user_dn, new_password=password) 123 124 def _ad_check_password_existing(self, password: str, user_dn: str) -> bool: 125 """Check if a password contains sAMAccount or displayName""" 126 from ldap3 import BASE 127 128 users = list( 129 self._connection.extend.standard.paged_search( 130 search_base=user_dn, 131 search_filter=self._source.user_object_filter, 132 search_scope=BASE, 133 attributes=["displayName", "sAMAccountName"], 134 ) 135 ) 136 if len(users) != 1: 137 raise AssertionError() 138 user_attributes = users[0]["attributes"] 139 # If sAMAccountName is at least 3 chars, check if it is contained in the password 140 if len(user_attributes["sAMAccountName"]) >= MIN_TOKEN_SIZE: 141 if user_attributes["sAMAccountName"].lower() in password.lower(): 142 return False 143 # displayName is either a string or a list of strings 144 display_names = user_attributes["displayName"] 145 if isinstance(display_names, str): 146 display_names = [display_names] 147 # No display name set, can't check any further 148 if len(display_names) < 1: 149 return True 150 for display_name in display_names: 151 display_name_tokens = split(RE_DISPLAYNAME_SEPARATORS, display_name) 152 for token in display_name_tokens: 153 # Ignore tokens under 3 chars 154 if len(token) < MIN_TOKEN_SIZE: 155 continue 156 if token.lower() in password.lower(): 157 return False 158 return True 159 160 def ad_password_complexity(self, password: str, user: User | None = None) -> bool: 161 """Check if password matches Active directory password policies 162 163 https://docs.microsoft.com/en-us/windows/security/threat-protection/ 164 security-policy-settings/password-must-meet-complexity-requirements 165 """ 166 if user: 167 # Check if password contains sAMAccountName or displayNames 168 if LDAP_DISTINGUISHED_NAME in user.attributes: 169 existing_user_check = self._ad_check_password_existing( 170 password, user.attributes.get(LDAP_DISTINGUISHED_NAME) 171 ) 172 if not existing_user_check: 173 LOGGER.debug("Password failed name check", user=user) 174 return existing_user_check 175 176 # Step 2, match at least 3 of 5 categories 177 matched_categories = PasswordCategories.NONE 178 required = 3 179 for letter in password: 180 # Only match one category per letter, 181 if letter.islower(): 182 matched_categories |= PasswordCategories.ALPHA_LOWER 183 elif letter.isupper(): 184 matched_categories |= PasswordCategories.ALPHA_UPPER 185 elif not letter.isascii() and letter.isalpha(): 186 # Not exactly matching microsoft's policy, but count it as "Other unicode" char 187 # when its alpha and not ascii 188 matched_categories |= PasswordCategories.ALPHA_OTHER 189 elif letter.isnumeric(): 190 matched_categories |= PasswordCategories.NUMERIC 191 elif letter in NON_ALPHA: 192 matched_categories |= PasswordCategories.SYMBOL 193 if bin(matched_categories).count("1") < required: 194 LOGGER.debug( 195 "Password didn't match enough categories", 196 has=matched_categories, 197 must=required, 198 ) 199 return False 200 LOGGER.debug("Password matched categories", has=matched_categories, must=required) 201 return True
Help validate and update passwords in LDAP
LDAPPasswordChanger(source: authentik.sources.ldap.models.LDAPSource)
54 @staticmethod 55 def should_check_user(user: User) -> bool: 56 """Check if the user has LDAP parameters and needs to be checked""" 57 return LDAP_DISTINGUISHED_NAME in user.attributes
Check if the user has LDAP parameters and needs to be checked
def
get_domain_root_dn(self) -> str:
59 def get_domain_root_dn(self) -> str: 60 """Attempt to get root DN via MS specific fields or generic LDAP fields""" 61 info = self._connection.server.info 62 if "rootDomainNamingContext" in info.other: 63 return info.other["rootDomainNamingContext"][0] 64 naming_contexts = info.naming_contexts 65 naming_contexts.sort(key=len) 66 return naming_contexts[0]
Attempt to get root DN via MS specific fields or generic LDAP fields
def
check_ad_password_complexity_enabled(self) -> bool:
68 def check_ad_password_complexity_enabled(self) -> bool: 69 """Check if DOMAIN_PASSWORD_COMPLEX is enabled""" 70 from ldap3 import BASE 71 from ldap3.core.exceptions import LDAPAttributeError, LDAPUnwillingToPerformResult 72 73 root_dn = self.get_domain_root_dn() 74 try: 75 root_attrs = self._connection.extend.standard.paged_search( 76 search_base=root_dn, 77 search_filter="(objectClass=*)", 78 search_scope=BASE, 79 attributes=["pwdProperties"], 80 ) 81 root_attrs = list(root_attrs)[0] 82 except LDAPAttributeError, LDAPUnwillingToPerformResult, KeyError, IndexError: 83 return False 84 raw_pwd_properties = root_attrs.get("attributes", {}).get("pwdProperties", None) 85 if not raw_pwd_properties: 86 return False 87 88 try: 89 pwd_properties = PwdProperties(raw_pwd_properties) 90 except ValueError: 91 return False 92 if PwdProperties.DOMAIN_PASSWORD_COMPLEX in pwd_properties: 93 return True 94 95 return False
Check if DOMAIN_PASSWORD_COMPLEX is enabled
105 def change_password(self, user: User, password: str): 106 """Change user's password""" 107 from ldap3.core.exceptions import ( 108 LDAPAttributeError, 109 LDAPNoSuchAttributeResult, 110 LDAPUnwillingToPerformResult, 111 ) 112 113 user_dn = user.attributes.get(LDAP_DISTINGUISHED_NAME, None) 114 if not user_dn: 115 LOGGER.info(f"User has no {LDAP_DISTINGUISHED_NAME} set.") 116 return 117 try: 118 self._connection.extend.microsoft.modify_password(user_dn, password) 119 except LDAPAttributeError, LDAPUnwillingToPerformResult, LDAPNoSuchAttributeResult: 120 if not self.supports_password_modify_extension(): 121 raise 122 self._connection.extend.standard.modify_password(user_dn, new_password=password)
Change user's password
def
ad_password_complexity( self, password: str, user: authentik.core.models.User | None = None) -> bool:
160 def ad_password_complexity(self, password: str, user: User | None = None) -> bool: 161 """Check if password matches Active directory password policies 162 163 https://docs.microsoft.com/en-us/windows/security/threat-protection/ 164 security-policy-settings/password-must-meet-complexity-requirements 165 """ 166 if user: 167 # Check if password contains sAMAccountName or displayNames 168 if LDAP_DISTINGUISHED_NAME in user.attributes: 169 existing_user_check = self._ad_check_password_existing( 170 password, user.attributes.get(LDAP_DISTINGUISHED_NAME) 171 ) 172 if not existing_user_check: 173 LOGGER.debug("Password failed name check", user=user) 174 return existing_user_check 175 176 # Step 2, match at least 3 of 5 categories 177 matched_categories = PasswordCategories.NONE 178 required = 3 179 for letter in password: 180 # Only match one category per letter, 181 if letter.islower(): 182 matched_categories |= PasswordCategories.ALPHA_LOWER 183 elif letter.isupper(): 184 matched_categories |= PasswordCategories.ALPHA_UPPER 185 elif not letter.isascii() and letter.isalpha(): 186 # Not exactly matching microsoft's policy, but count it as "Other unicode" char 187 # when its alpha and not ascii 188 matched_categories |= PasswordCategories.ALPHA_OTHER 189 elif letter.isnumeric(): 190 matched_categories |= PasswordCategories.NUMERIC 191 elif letter in NON_ALPHA: 192 matched_categories |= PasswordCategories.SYMBOL 193 if bin(matched_categories).count("1") < required: 194 LOGGER.debug( 195 "Password didn't match enough categories", 196 has=matched_categories, 197 must=required, 198 ) 199 return False 200 LOGGER.debug("Password matched categories", has=matched_categories, must=required) 201 return True
Check if password matches Active directory password policies
https://docs.microsoft.com/en-us/windows/security/threat-protection/ security-policy-settings/password-must-meet-complexity-requirements