authentik.sources.ldap.sync.vendor.ms_ad

Active Directory specific

  1"""Active Directory specific"""
  2
  3from collections.abc import Generator
  4from datetime import UTC, datetime
  5from enum import IntFlag
  6from typing import Any
  7
  8from django.utils.timezone import now
  9
 10from authentik.core.models import User
 11from authentik.lib.sync.outgoing.exceptions import StopSync
 12from authentik.sources.ldap.models import flatten
 13from authentik.sources.ldap.sync.base import BaseLDAPSynchronizer
 14from authentik.stages.password.models import PasswordDevice
 15
 16FILETIME_EPOCH = datetime(1601, 1, 1, tzinfo=UTC)
 17FILETIME_NEVER = 9223372036854775807
 18
 19
 20class UserAccountControl(IntFlag):
 21    """UserAccountControl attribute for Active directory users"""
 22
 23    # https://docs.microsoft.com/en-us/troubleshoot/windows-server/identity
 24    #   /useraccountcontrol-manipulate-account-properties
 25
 26    SCRIPT = 1
 27    ACCOUNTDISABLE = 2
 28    HOMEDIR_REQUIRED = 8
 29    LOCKOUT = 16
 30    PASSWD_NOTREQD = 32
 31    PASSWD_CANT_CHANGE = 64
 32    ENCRYPTED_TEXT_PWD_ALLOWED = 128
 33    TEMP_DUPLICATE_ACCOUNT = 256
 34    NORMAL_ACCOUNT = 512
 35    INTERDOMAIN_TRUST_ACCOUNT = 2048
 36    WORKSTATION_TRUST_ACCOUNT = 4096
 37    SERVER_TRUST_ACCOUNT = 8192
 38    DONT_EXPIRE_PASSWORD = 65536
 39    MNS_LOGON_ACCOUNT = 131072
 40    SMARTCARD_REQUIRED = 262144
 41    TRUSTED_FOR_DELEGATION = 524288
 42    NOT_DELEGATED = 1048576
 43    USE_DES_KEY_ONLY = 2097152
 44    DONT_REQ_PREAUTH = 4194304
 45    PASSWORD_EXPIRED = 8388608
 46    TRUSTED_TO_AUTH_FOR_DELEGATION = 16777216
 47    PARTIAL_SECRETS_ACCOUNT = 67108864
 48
 49
 50class MicrosoftActiveDirectory(BaseLDAPSynchronizer):
 51    """Microsoft-specific LDAP"""
 52
 53    @staticmethod
 54    def name() -> str:
 55        return "microsoft_ad"
 56
 57    def get_objects(self, **kwargs) -> Generator:
 58        yield None
 59
 60    def sync(self, attributes: dict[str, Any], user: User, created: bool):
 61        self.ms_check_pwd_last_set(attributes, user, created)
 62
 63    def ms_check_pwd_last_set(self, attributes: dict[str, Any], user: User, created: bool):
 64        """Check pwdLastSet"""
 65        if "pwdLastSet" not in attributes:
 66            return
 67        pwd_last_set: datetime = attributes.get("pwdLastSet", datetime.now())
 68        pwd_last_set = pwd_last_set.replace(tzinfo=UTC)
 69        if created or pwd_last_set > user.password_change_date:
 70            self._task.info(f"'{user.username}': Reset user's password")
 71            self._logger.debug(
 72                "Reset user's password",
 73                user=user.username,
 74                created=created,
 75                pwd_last_set=pwd_last_set,
 76            )
 77            # Record the directory's change date, or every later sync resets the password
 78            # again, and each new unusable hash ends the user's sessions.
 79            PasswordDevice.set_unusable_password(user, password_change_date=pwd_last_set)
 80
 81    @staticmethod
 82    def account_expired(value: Any) -> bool:
 83        """Interpret accountExpires with or without ldap3's schema-aware formatting."""
 84        value = flatten(value)
 85        if value is None:
 86            return False
 87        current_time = now()
 88        if isinstance(value, datetime):
 89            # ldap3 formats zero as the FILETIME epoch and the maximum integer as datetime.max.
 90            if value.tzinfo is None:
 91                value = value.replace(tzinfo=UTC)
 92            else:
 93                value = value.astimezone(UTC)
 94            if value in (FILETIME_EPOCH, datetime.max.replace(tzinfo=UTC)):
 95                return False
 96            return value <= current_time
 97        if isinstance(value, bool) or not isinstance(value, int | str | bytes):
 98            raise ValueError("Invalid accountExpires: expected an AD timestamp")
 99        try:
100            timestamp = int(value)
101        except ValueError as exc:
102            raise ValueError("Invalid accountExpires: expected an AD timestamp") from exc
103        if not 0 <= timestamp <= FILETIME_NEVER:
104            raise ValueError("Invalid accountExpires: timestamp is outside the AD range")
105        if timestamp in (0, FILETIME_NEVER):
106            return False
107        # Compare integers to avoid floating-point rounding and datetime overflow.
108        elapsed = current_time - FILETIME_EPOCH
109        current_timestamp = (elapsed.days * 86400 + elapsed.seconds) * 10000000
110        current_timestamp += elapsed.microseconds * 10
111        return timestamp <= current_timestamp
112
113    def get_account_active(self, attributes: dict[str, Any]) -> bool | None:
114        """Combine AD restrictions before saving, preserving state when UAC is unavailable."""
115        try:
116            expired = self.account_expired(attributes.get("accountExpires"))
117        except ValueError as exc:
118            raise StopSync(exc) from exc
119        if expired:
120            return False
121        uac_bit = flatten(attributes.get("userAccountControl"))
122        if uac_bit is None:
123            return None
124        uac = UserAccountControl(int(uac_bit))
125        return (
126            UserAccountControl.ACCOUNTDISABLE not in uac and UserAccountControl.LOCKOUT not in uac
127        )
FILETIME_EPOCH = datetime.datetime(1601, 1, 1, 0, 0, tzinfo=datetime.timezone.utc)
FILETIME_NEVER = 9223372036854775807
class UserAccountControl(enum.IntFlag):
21class UserAccountControl(IntFlag):
22    """UserAccountControl attribute for Active directory users"""
23
24    # https://docs.microsoft.com/en-us/troubleshoot/windows-server/identity
25    #   /useraccountcontrol-manipulate-account-properties
26
27    SCRIPT = 1
28    ACCOUNTDISABLE = 2
29    HOMEDIR_REQUIRED = 8
30    LOCKOUT = 16
31    PASSWD_NOTREQD = 32
32    PASSWD_CANT_CHANGE = 64
33    ENCRYPTED_TEXT_PWD_ALLOWED = 128
34    TEMP_DUPLICATE_ACCOUNT = 256
35    NORMAL_ACCOUNT = 512
36    INTERDOMAIN_TRUST_ACCOUNT = 2048
37    WORKSTATION_TRUST_ACCOUNT = 4096
38    SERVER_TRUST_ACCOUNT = 8192
39    DONT_EXPIRE_PASSWORD = 65536
40    MNS_LOGON_ACCOUNT = 131072
41    SMARTCARD_REQUIRED = 262144
42    TRUSTED_FOR_DELEGATION = 524288
43    NOT_DELEGATED = 1048576
44    USE_DES_KEY_ONLY = 2097152
45    DONT_REQ_PREAUTH = 4194304
46    PASSWORD_EXPIRED = 8388608
47    TRUSTED_TO_AUTH_FOR_DELEGATION = 16777216
48    PARTIAL_SECRETS_ACCOUNT = 67108864

UserAccountControl attribute for Active directory users

ACCOUNTDISABLE = <UserAccountControl.ACCOUNTDISABLE: 2>
HOMEDIR_REQUIRED = <UserAccountControl.HOMEDIR_REQUIRED: 8>
LOCKOUT = <UserAccountControl.LOCKOUT: 16>
PASSWD_NOTREQD = <UserAccountControl.PASSWD_NOTREQD: 32>
PASSWD_CANT_CHANGE = <UserAccountControl.PASSWD_CANT_CHANGE: 64>
ENCRYPTED_TEXT_PWD_ALLOWED = <UserAccountControl.ENCRYPTED_TEXT_PWD_ALLOWED: 128>
TEMP_DUPLICATE_ACCOUNT = <UserAccountControl.TEMP_DUPLICATE_ACCOUNT: 256>
NORMAL_ACCOUNT = <UserAccountControl.NORMAL_ACCOUNT: 512>
INTERDOMAIN_TRUST_ACCOUNT = <UserAccountControl.INTERDOMAIN_TRUST_ACCOUNT: 2048>
WORKSTATION_TRUST_ACCOUNT = <UserAccountControl.WORKSTATION_TRUST_ACCOUNT: 4096>
SERVER_TRUST_ACCOUNT = <UserAccountControl.SERVER_TRUST_ACCOUNT: 8192>
DONT_EXPIRE_PASSWORD = <UserAccountControl.DONT_EXPIRE_PASSWORD: 65536>
MNS_LOGON_ACCOUNT = <UserAccountControl.MNS_LOGON_ACCOUNT: 131072>
SMARTCARD_REQUIRED = <UserAccountControl.SMARTCARD_REQUIRED: 262144>
TRUSTED_FOR_DELEGATION = <UserAccountControl.TRUSTED_FOR_DELEGATION: 524288>
NOT_DELEGATED = <UserAccountControl.NOT_DELEGATED: 1048576>
USE_DES_KEY_ONLY = <UserAccountControl.USE_DES_KEY_ONLY: 2097152>
DONT_REQ_PREAUTH = <UserAccountControl.DONT_REQ_PREAUTH: 4194304>
PASSWORD_EXPIRED = <UserAccountControl.PASSWORD_EXPIRED: 8388608>
TRUSTED_TO_AUTH_FOR_DELEGATION = <UserAccountControl.TRUSTED_TO_AUTH_FOR_DELEGATION: 16777216>
PARTIAL_SECRETS_ACCOUNT = <UserAccountControl.PARTIAL_SECRETS_ACCOUNT: 67108864>
class MicrosoftActiveDirectory(authentik.sources.ldap.sync.base.BaseLDAPSynchronizer):
 51class MicrosoftActiveDirectory(BaseLDAPSynchronizer):
 52    """Microsoft-specific LDAP"""
 53
 54    @staticmethod
 55    def name() -> str:
 56        return "microsoft_ad"
 57
 58    def get_objects(self, **kwargs) -> Generator:
 59        yield None
 60
 61    def sync(self, attributes: dict[str, Any], user: User, created: bool):
 62        self.ms_check_pwd_last_set(attributes, user, created)
 63
 64    def ms_check_pwd_last_set(self, attributes: dict[str, Any], user: User, created: bool):
 65        """Check pwdLastSet"""
 66        if "pwdLastSet" not in attributes:
 67            return
 68        pwd_last_set: datetime = attributes.get("pwdLastSet", datetime.now())
 69        pwd_last_set = pwd_last_set.replace(tzinfo=UTC)
 70        if created or pwd_last_set > user.password_change_date:
 71            self._task.info(f"'{user.username}': Reset user's password")
 72            self._logger.debug(
 73                "Reset user's password",
 74                user=user.username,
 75                created=created,
 76                pwd_last_set=pwd_last_set,
 77            )
 78            # Record the directory's change date, or every later sync resets the password
 79            # again, and each new unusable hash ends the user's sessions.
 80            PasswordDevice.set_unusable_password(user, password_change_date=pwd_last_set)
 81
 82    @staticmethod
 83    def account_expired(value: Any) -> bool:
 84        """Interpret accountExpires with or without ldap3's schema-aware formatting."""
 85        value = flatten(value)
 86        if value is None:
 87            return False
 88        current_time = now()
 89        if isinstance(value, datetime):
 90            # ldap3 formats zero as the FILETIME epoch and the maximum integer as datetime.max.
 91            if value.tzinfo is None:
 92                value = value.replace(tzinfo=UTC)
 93            else:
 94                value = value.astimezone(UTC)
 95            if value in (FILETIME_EPOCH, datetime.max.replace(tzinfo=UTC)):
 96                return False
 97            return value <= current_time
 98        if isinstance(value, bool) or not isinstance(value, int | str | bytes):
 99            raise ValueError("Invalid accountExpires: expected an AD timestamp")
100        try:
101            timestamp = int(value)
102        except ValueError as exc:
103            raise ValueError("Invalid accountExpires: expected an AD timestamp") from exc
104        if not 0 <= timestamp <= FILETIME_NEVER:
105            raise ValueError("Invalid accountExpires: timestamp is outside the AD range")
106        if timestamp in (0, FILETIME_NEVER):
107            return False
108        # Compare integers to avoid floating-point rounding and datetime overflow.
109        elapsed = current_time - FILETIME_EPOCH
110        current_timestamp = (elapsed.days * 86400 + elapsed.seconds) * 10000000
111        current_timestamp += elapsed.microseconds * 10
112        return timestamp <= current_timestamp
113
114    def get_account_active(self, attributes: dict[str, Any]) -> bool | None:
115        """Combine AD restrictions before saving, preserving state when UAC is unavailable."""
116        try:
117            expired = self.account_expired(attributes.get("accountExpires"))
118        except ValueError as exc:
119            raise StopSync(exc) from exc
120        if expired:
121            return False
122        uac_bit = flatten(attributes.get("userAccountControl"))
123        if uac_bit is None:
124            return None
125        uac = UserAccountControl(int(uac_bit))
126        return (
127            UserAccountControl.ACCOUNTDISABLE not in uac and UserAccountControl.LOCKOUT not in uac
128        )

Microsoft-specific LDAP

@staticmethod
def name() -> str:
54    @staticmethod
55    def name() -> str:
56        return "microsoft_ad"

UI name for the type of object this class synchronizes

def get_objects(self, **kwargs) -> Generator:
58    def get_objects(self, **kwargs) -> Generator:
59        yield None

Get objects from LDAP, implemented in subclass

def sync( self, attributes: dict[str, typing.Any], user: authentik.core.models.User, created: bool):
61    def sync(self, attributes: dict[str, Any], user: User, created: bool):
62        self.ms_check_pwd_last_set(attributes, user, created)

Sync function, implemented in subclass

def ms_check_pwd_last_set( self, attributes: dict[str, typing.Any], user: authentik.core.models.User, created: bool):
64    def ms_check_pwd_last_set(self, attributes: dict[str, Any], user: User, created: bool):
65        """Check pwdLastSet"""
66        if "pwdLastSet" not in attributes:
67            return
68        pwd_last_set: datetime = attributes.get("pwdLastSet", datetime.now())
69        pwd_last_set = pwd_last_set.replace(tzinfo=UTC)
70        if created or pwd_last_set > user.password_change_date:
71            self._task.info(f"'{user.username}': Reset user's password")
72            self._logger.debug(
73                "Reset user's password",
74                user=user.username,
75                created=created,
76                pwd_last_set=pwd_last_set,
77            )
78            # Record the directory's change date, or every later sync resets the password
79            # again, and each new unusable hash ends the user's sessions.
80            PasswordDevice.set_unusable_password(user, password_change_date=pwd_last_set)

Check pwdLastSet

@staticmethod
def account_expired(value: Any) -> bool:
 82    @staticmethod
 83    def account_expired(value: Any) -> bool:
 84        """Interpret accountExpires with or without ldap3's schema-aware formatting."""
 85        value = flatten(value)
 86        if value is None:
 87            return False
 88        current_time = now()
 89        if isinstance(value, datetime):
 90            # ldap3 formats zero as the FILETIME epoch and the maximum integer as datetime.max.
 91            if value.tzinfo is None:
 92                value = value.replace(tzinfo=UTC)
 93            else:
 94                value = value.astimezone(UTC)
 95            if value in (FILETIME_EPOCH, datetime.max.replace(tzinfo=UTC)):
 96                return False
 97            return value <= current_time
 98        if isinstance(value, bool) or not isinstance(value, int | str | bytes):
 99            raise ValueError("Invalid accountExpires: expected an AD timestamp")
100        try:
101            timestamp = int(value)
102        except ValueError as exc:
103            raise ValueError("Invalid accountExpires: expected an AD timestamp") from exc
104        if not 0 <= timestamp <= FILETIME_NEVER:
105            raise ValueError("Invalid accountExpires: timestamp is outside the AD range")
106        if timestamp in (0, FILETIME_NEVER):
107            return False
108        # Compare integers to avoid floating-point rounding and datetime overflow.
109        elapsed = current_time - FILETIME_EPOCH
110        current_timestamp = (elapsed.days * 86400 + elapsed.seconds) * 10000000
111        current_timestamp += elapsed.microseconds * 10
112        return timestamp <= current_timestamp

Interpret accountExpires with or without ldap3's schema-aware formatting.

def get_account_active(self, attributes: dict[str, typing.Any]) -> bool | None:
114    def get_account_active(self, attributes: dict[str, Any]) -> bool | None:
115        """Combine AD restrictions before saving, preserving state when UAC is unavailable."""
116        try:
117            expired = self.account_expired(attributes.get("accountExpires"))
118        except ValueError as exc:
119            raise StopSync(exc) from exc
120        if expired:
121            return False
122        uac_bit = flatten(attributes.get("userAccountControl"))
123        if uac_bit is None:
124            return None
125        uac = UserAccountControl(int(uac_bit))
126        return (
127            UserAccountControl.ACCOUNTDISABLE not in uac and UserAccountControl.LOCKOUT not in uac
128        )

Combine AD restrictions before saving, preserving state when UAC is unavailable.