diff --git a/changelog.d/4846-kerberos-realm-bound-to-entry.security.md b/changelog.d/4846-kerberos-realm-bound-to-entry.security.md new file mode 100644 index 0000000000..682c223665 --- /dev/null +++ b/changelog.d/4846-kerberos-realm-bound-to-entry.security.md @@ -0,0 +1,12 @@ +- **Windows SSO now resolves a ticket only to the account it proves.** The ticket's realm was + checked against `[auth].kerberos_realm` and dropped, and the directory was then asked the + password sign-in's wider question. So in the shipped code, under a forest-wide base or the global + catalog, `alice@CORP.EXAMPLE` would have signed in as a child domain's `alice`; one entry holding + only the UPN `alice@` would have answered a ticket for `alice`; and a machine's ticket + (`WS01$`) was looked up like a person's. The Kerberos lookup now asks for a person account whose + own `sAMAccountName` is the ticket's name and whose DN's whole trailing run of `DC=` RDNs equals + the realm's domain, and looks up no name ending in `$`. A realm whose users are not under its own + `DC=` RDNs, as on a directory other than Active Directory, now finds no account, and neither does + a ticket naming the account by an implicit UPN, which a client that does not ask for name + canonicalization may present. The password sign-in is unchanged. See + [SECURITY.md](../docs/SECURITY.md#local-vs-active-directory). (`BACKLOG #4846`) diff --git a/docs/SECURITY.md b/docs/SECURITY.md index 683b84c934..f4b59f31da 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -5431,6 +5431,20 @@ Both kinds of user share one identity model (`users.auth_provider` is `local` or this acceptor against a real domain. If it does, every Windows SSO sign-in on a Windows host fails closed until a lab run decides how to read it. That is no looser than before, when its directory lookup missed. + **The realm is bound to the directory entry too (BACKLOG #4846).** The Kerberos lookup asks only + what a ticket proves: a person account, `objectCategory=person` and `objectClass=user`, whose own + `sAMAccountName` is the ticket's account name, and whose DN's whole trailing run of `DC=` RDNs + equals the realm's domain, compared up to ASCII case as the ticket's realm is. So under a forest-wide base or the + global catalog, `alice@CORP.EXAMPLE` never resolves to a child domain's `alice`; an entry holding + the name only as its UPN answers no ticket; and a machine's ticket (`WS01$`) finds nothing. A + name ending in `$` is never looked up, which also covers an interdomain trust account, a + person-category `user`. The binding assumes Active Directory's rule that a domain's realm is its + DNS name and its naming context that name's `DC=` RDNs. An entry whose trailing `DC=` run is + not exactly the realm's labels, one per RDN, matches nothing, and neither does one whose DN the + engine's parser refuses; the sign-in is then refused as `not_in_directory`. So does a ticket naming the account by an implicit UPN rather than its + `sAMAccountName`, which a client that does not ask the KDC to canonicalize the name may present; + that is unverified against a real KDC. The password sign-in and the other name-keyed lookups, + `create_directory_account`'s among them, are unchanged. ### AD-group → role mapping diff --git a/messagefoundry/auth/ldap.py b/messagefoundry/auth/ldap.py index 36480c3648..a652ce7c79 100644 --- a/messagefoundry/auth/ldap.py +++ b/messagefoundry/auth/ldap.py @@ -646,6 +646,16 @@ def _account_state(entry: Any) -> DirectoryAnswer: return DirectoryAnswer.UNDETERMINED +def _holds_name(entry: Any, name: str) -> bool: + """Whether ``entry``'s own ``sAMAccountName`` is ``name``, which must be lower-case already. + + One rule for the ambiguity check and the Kerberos narrowing (BACKLOG #4846). Compared with + ``lower()``, not ``casefold()``, so a German sharp s does not equal "ss". An entry with no + readable name holds none. + """ + return (_attr(entry, "sAMAccountName") or "").lower() == name + + def _multi(entry: Any, name: str) -> list[str]: if name not in entry: return [] @@ -756,6 +766,20 @@ def canonical_group_dn(text: str) -> str | None: the store's own ``strip().lower()`` is a no-op on it. Linear apart from sorting a multi-valued RDN's parts, so operator text cannot make it backtrack. """ + rdns = _canonical_rdns(text) + if rdns is None or len(rdns) < _GROUP_DN_MIN_RDNS: + return None + return ",".join("+".join(rdn) for rdn in rdns) + + +def _canonical_rdns(text: str) -> list[list[str]] | None: + """``text`` parsed into RDNs of canonical ``type=value`` parts, or ``None`` if it is no DN. + + The parser behind :func:`canonical_group_dn`, which states the canonical form and what is + refused, apart from the minimum RDN count, which is that function's alone. Each RDN's parts + are sorted. :func:`_dn_realm` reads a user entry's DN through it too, so the two never + disagree on how a DN is split. + """ try: text.encode("utf-8") except UnicodeEncodeError: @@ -817,9 +841,43 @@ def close_ava() -> bool: if not close_ava(): return None rdns.append(sorted(avas)) - if len(rdns) < _GROUP_DN_MIN_RDNS: + return rdns + + +#: ``domainComponent`` as :func:`_canonical_rdns` writes its type: the name, lower-case, or the OID +#: (RFC 4519 section 2.4). +_DC_TYPES = frozenset({"dc", "domaincomponent", "0.9.2342.19200300.100.1.25"}) + + +def _dn_realm(dn: str) -> str | None: + """The DNS domain the ``DC=`` RDNs at the end of ``dn`` name, lower-case, or ``None``. + + BACKLOG #4846. ``CN=alice,OU=Staff,DC=child,DC=corp,DC=example`` gives + ``child.corp.example``. Only the trailing run of single-valued ``dc`` RDNs counts, so a ``DC=`` + higher up the DN, or one inside a multi-valued RDN, adds nothing. The type may be spelled as + its OID, which ends no run early. The value is canonical (:func:`_canonical_value`): ASCII + letters are lower-case, other printable ASCII stays literal apart from the RFC 4514 specials, + which are backslash-escaped, and every non-ASCII character is a ``\\xx`` escape. A realm is + printable ASCII with no ``\\`` (``check_kerberos_realm``), so an escaped label equals none. + + ``None`` when ``dn`` does not parse, ends in no ``DC=`` RDN, or has a label in that run that + holds a ``.``, escaped or not: ``DC=corp.example`` is one label, not the two Active Directory + writes for that domain, so it names no domain this compare can trust. + """ + rdns = _canonical_rdns(dn) + if rdns is None: return None - return ",".join("+".join(rdn) for rdn in rdns) + labels: list[str] = [] + for rdn in reversed(rdns): + if len(rdn) != 1: + break + kind, _eq, label = rdn[0].partition("=") + if kind not in _DC_TYPES: + break + if "." in label: + return None + labels.append(label) + return ".".join(reversed(labels)) or None def is_group_dn(value: str) -> bool: @@ -1955,6 +2013,7 @@ def _search_user( fallback_username: str, expected_object_id: str | None = None, tie_break_object_id: str | None = None, + kerberos_realm: str | None = None, ) -> _Lookup: """Run one user search and extract the entry. ``info`` is ``None`` for no match, more than one match (``AMBIGUOUS``, vault BACKLOG #2778), a disabled account or an undetermined one, @@ -1970,10 +2029,17 @@ def _search_user( does not read it back a no-match, before its account state is read (BACKLOG #2027). See :meth:`_lookup_by_object_id`. + ``kerberos_realm``, the configured realm a Kerberos ticket was checked against, keeps only + the entries that ticket can name, before anything else reads them (BACKLOG #4846, + :meth:`_kerberos_holders`). Only the Kerberos lookup passes it, and it is the one step that + reads the answer differently: under it the tie-break above never chooses, because every + entry left holds the name. + The filter is the caller's; everything after it -- the attribute list, the ACCOUNTDISABLE - rejection and the extraction -- is shared by both lookups on purpose. **The two lookups differ - only in which question they ask the directory**, and an attribute list that drifted between - them would give the name-keyed and id-keyed paths different views of the same account. + rejection and the extraction -- is shared by every lookup on purpose. **The lookups differ + only in which question they ask the directory**, apart from that Kerberos step, and an + attribute list that drifted between them would give the name-keyed and id-keyed paths + different views of the same account. ``fallback_username`` is what to call the account when the entry carries no ``sAMAccountName``. For the name-keyed lookup that is the name searched for; for the id-keyed @@ -1998,12 +2064,16 @@ def _search_user( _UAC_ATTR, ], ) - if not conn.entries: + entries = list(conn.entries) + if kerberos_realm is not None: + entries = self._kerberos_holders(entries, fallback_username, kerberos_realm) + if not entries: return _Lookup(DirectoryAnswer.NOT_FOUND) - e = conn.entries[0] + e = entries[0] own: str | None = None - if len(conn.entries) > 1: - # Vault BACKLOG #2778. The name filter matches sAMAccountName OR userPrincipalName, and + if len(entries) > 1: + # Vault BACKLOG #2778. The password path's name filter matches sAMAccountName OR + # userPrincipalName (the Kerberos one asks for the first alone, BACKLOG #4846), and # a directory may legally give one account a UPN prefix equal to another's # sAMAccountName. Taking entries[0] would let the server's result order pick which # account signs in. Logged with a label for the name and the count only, once per name: @@ -2015,29 +2085,27 @@ def _search_user( # Refusing it too let anyone able to write a colliding entry lock the account out. No # match, or more than one, still proves nothing, so it is refused as before. # - # THE CHOSEN ENTRY MUST BE THE ONLY MATCH HOLDING THE NAME AS ITS sAMAccountName. The - # Kerberos caller passes the ticket's name with its realm checked against - # [auth].kerberos_realm and then dropped (BACKLOG #2610), so the ticket proves only that - # its holder has this sAMAccountName in that realm, while the search base may span more. + # THE CHOSEN ENTRY MUST BE THE ONLY MATCH HOLDING THE NAME AS ITS sAMAccountName. A + # ticket proves only that its holder has this sAMAccountName in [auth].kerberos_realm + # (BACKLOG #2610). The Kerberos lookup keeps only such entries in that realm before + # this point (_kerberos_holders, BACKLOG #4846); for the other name-keyed callers: # - An entry that matched only through its UPN is not that holder. Choosing it would let # a renamed account that kept its old UPN be signed in by whoever was later given the # old name. # - Two entries holding the name, as same-named accounts in two domains under one - # search base would, cannot be told apart by the ticket, so the id does not choose. + # search base would, cannot be told apart by the name, so the id does not choose. # The id must also be on that entry alone: an id on two entries names neither. # Compared with lower(), not casefold(), so "straße" does not equal "strasse". # The `is not None` test is load-bearing: an entry with no readable id reads back # None, which must never match a caller that holds no id. label = safe_name(fallback_username) name = fallback_username.lower() - holders = [ - x for x in conn.entries if (_attr(x, "sAMAccountName") or "").lower() == name - ] + holders = [x for x in entries if _holds_name(x, name)] chosen = ( tie_break_object_id is not None and len(holders) == 1 # Identity, not ==: the one entry carrying the id must be the holder itself. - and [id(x) for x in conn.entries if _object_guid(x) == tie_break_object_id] + and [id(x) for x in entries if _object_guid(x) == tie_break_object_id] == [id(holders[0])] ) # Reported either way: the collision is in the directory, and an operator should clear it. @@ -2045,7 +2113,7 @@ def _search_user( f"ambiguous-chosen:{label}" if chosen else f"ambiguous:{label}", "AD user search for %s matched %d directory entries; %s (logged once per name)", label, - len(conn.entries), + len(entries), f"using the one carrying the account's stored {_OBJECT_GUID_ATTR}" if chosen else "refusing it as ambiguous", @@ -2087,11 +2155,55 @@ def _search_user( }, ) + @staticmethod + def _kerberos_holders(entries: list[Any], name: str, realm: str) -> list[Any]: + """The entries a ticket for ``name`` in ``realm`` can name (BACKLOG #4846). + + A ticket proves its holder has the ``sAMAccountName`` ``name`` in the domain ``realm`` + names. An entry is kept only when both hold for it: + + - its own ``sAMAccountName`` is ``name`` (:func:`_holds_name`, the ambiguity check's + rule). The Kerberos filter asks for nothing else, so this only re-reads what the + directory answered; + - the whole trailing run of ``DC=`` RDNs in its DN equals the realm's domain + (:func:`_dn_realm`), up to ASCII case, as the ticket's realm was compared + (:func:`_account_in_realm`). Under a forest-wide base or the global catalog, ``alice`` in + a child domain is another account than ``alice`` in the realm, and the ticket names only + the second. + + This binds the realm to the entry on Active Directory, where a domain's realm is its DNS + name and its naming context is that name's ``DC=`` RDNs. An entry whose DN does not end in + exactly those RDNs matches nothing, which fails closed. So does one whose DN this engine's + parser refuses (:func:`canonical_group_dn` lists those shapes), such as a name with an + unescaped ``"``. + + A dropped entry is logged at DEBUG, with a label for the name and the counts only. Under the + global catalog a name held in several domains drops entries on every sign-in, which is not + a fault an operator can clear. + """ + domain = realm.lower() + held = name.lower() + kept = [x for x in entries if _holds_name(x, held) and _dn_realm(str(x.entry_dn)) == domain] + if len(kept) < len(entries): + logger.debug( + "Kerberos lookup for %s kept %d of %d directory entries; the rest do not hold the " + "name, are outside [auth].kerberos_realm's domain, or have a DN the engine cannot read", + safe_name(name), + len(kept), + len(entries), + ) + return kept + def _find_user(self, conn: Any, username: str) -> dict[str, Any] | None: return self._lookup_by_name(conn, username).info def _lookup_by_name( - self, conn: Any, username: str, *, tie_break_object_id: str | None = None + self, + conn: Any, + username: str, + *, + tie_break_object_id: str | None = None, + kerberos_realm: str | None = None, ) -> _Lookup: """Find a user by name. ``tie_break_object_id`` only chooses among several matches. @@ -2100,16 +2212,44 @@ def _lookup_by_name( after the name passed to someone else. For the same reason the tie-break only accepts the one entry whose own ``sAMAccountName`` is the name (:meth:`_search_user`). The id is normalised here, the one place it enters this lookup; one that cannot be read breaks no tie. + + **``kerberos_realm`` asks the narrower question a ticket answers (BACKLOG #4846).** A ticket + for ``alice`` in that realm proves only that its holder is the person account whose + ``sAMAccountName`` is ``alice`` in the realm's domain, so the lookup asks for that and + nothing wider: + + - the filter has no ``userPrincipalName`` arm. With one, a single entry holding the UPN + ``alice@`` under another name would answer the ticket alone, so a renamed + account that kept its old UPN would sign in for whoever was later given the old name; + - the filter asks for ``objectCategory=person`` and ``objectClass=user``. A computer object + is a ``user`` by class but not a person by category, so a machine's ticket + (``WS01$@REALM``) finds nothing, and neither does a managed service account's or a + contact's; + - only entries in the realm's domain, holding the name, are read (:meth:`_kerberos_holders`). + + A name ending in ``$`` is NOT_FOUND without a search, and a malformed realm raises + (:func:`_kerberos_lookup_realm`). """ - upn = f"{username}@{self._s.ad_domain}" if self._s.ad_domain else username - return self._search_user( - conn, - ( + if kerberos_realm is not None: + kerberos_realm = _kerberos_lookup_realm(username, kerberos_realm) + if kerberos_realm is None: + return _Lookup(DirectoryAnswer.NOT_FOUND) + search_filter = ( + "(&(objectCategory=person)(objectClass=user)" + f"(sAMAccountName={_escape_filter(username)}))" + ) + else: + upn = f"{username}@{self._s.ad_domain}" if self._s.ad_domain else username + search_filter = ( f"(|(sAMAccountName={_escape_filter(username)})" f"(userPrincipalName={_escape_filter(upn)}))" - ), + ) + return self._search_user( + conn, + search_filter, fallback_username=username, tie_break_object_id=normalise_object_guid(tie_break_object_id), + kerberos_realm=kerberos_realm, ) def _lookup_by_object_id(self, conn: Any, object_id: str, *, fallback_username: str) -> _Lookup: @@ -2286,6 +2426,7 @@ def resolve_principal( *, object_id: str | None = None, tie_break_object_id: str | None = None, + kerberos_realm: str | None = None, ) -> AdPrincipal | None: """Look a user up + resolve groups *without* a password. Uses the service-account bind only. @@ -2313,9 +2454,18 @@ def resolve_principal( ``objectGUID``: when the name matches several entries, the one carrying that id is used (vault BACKLOG #3228, :meth:`_lookup_by_name`). Passing it with ``object_id`` is a programming error and raises :class:`ValueError`: an id-keyed search has no tie to break. + + ``kerberos_realm`` is for the Kerberos sign-in alone: ``username`` is a ticket's account + name, the realm is the one :func:`kerberos_principal` checked that ticket against, and the + lookup asks only what the ticket proves (BACKLOG #4846, :meth:`_lookup_by_name`). Passing + it with ``object_id`` raises :class:`ValueError` too, because an id-keyed search would skip + that narrowing. """ return self.probe_principal( - username, object_id=object_id, tie_break_object_id=tie_break_object_id + username, + object_id=object_id, + tie_break_object_id=tie_break_object_id, + kerberos_realm=kerberos_realm, ).principal def probe_principal( @@ -2324,6 +2474,7 @@ def probe_principal( *, object_id: str | None = None, tie_break_object_id: str | None = None, + kerberos_realm: str | None = None, ) -> DirectoryProbe: """:meth:`resolve_principal`, also saying WHY an account did not resolve (ADR 0195). @@ -2340,13 +2491,21 @@ def probe_principal( if object_id is not None and tie_break_object_id is not None: raise ValueError("pass object_id or tie_break_object_id, not both") + if object_id is not None and kerberos_realm is not None: + raise ValueError("pass object_id or kerberos_realm, not both") + # Before the session opens, since neither check needs the directory (BACKLOG #4846). + if kerberos_realm is not None and _kerberos_lookup_realm(username, kerberos_realm) is None: + return DirectoryProbe(DirectoryAnswer.NOT_FOUND) try: with self._service_session() as svc: found = ( self._lookup_by_object_id(svc, object_id, fallback_username=username) if object_id is not None else self._lookup_by_name( - svc, username, tie_break_object_id=tie_break_object_id + svc, + username, + tie_break_object_id=tie_break_object_id, + kerberos_realm=kerberos_realm, ) ) info = found.info @@ -2527,7 +2686,10 @@ def kerberos_principal(token: bytes, settings: AuthSettings) -> str | None: NTLM fallback, no mutual-auth response token, no multi-leg challenge handshake. The server must have a usable keytab/credential for ``kerberos_spn`` in its environment. The principal must be ``user@REALM`` with ``REALM`` equal to ``kerberos_realm``; :func:`_account_in_realm` says what - else it refuses (BACKLOG #2610). + else it refuses (BACKLOG #2610). The realm is dropped from the answer, so the caller must look + the name up with ``kerberos_realm`` set to the same realm + (:meth:`LdapAuthenticator.resolve_principal`), which binds it to an entry in that realm's + domain again (BACKLOG #4846). ``None`` unless :func:`_kerberos_context_complete` says the context finished (BACKLOG #2610 review point c), so no provider can hand back a principal from a half-done exchange. That is @@ -2584,12 +2746,31 @@ def _configured_kerberos_realm(settings: AuthSettings) -> str: """ if not settings.kerberos_realm: raise LdapError("kerberos_realm is not set; Windows SSO accepts no ticket without it") + return _checked_kerberos_realm(settings.kerberos_realm) + + +def _checked_kerberos_realm(realm: str) -> str: + """``realm`` through ``check_kerberos_realm``, its refusal raised as a configuration fault.""" try: - return check_kerberos_realm(settings.kerberos_realm) + return check_kerberos_realm(realm) except ValueError as exc: raise LdapError(str(exc)) from exc +def _kerberos_lookup_realm(username: str, realm: str) -> str | None: + """The checked ``realm`` a Kerberos lookup of ``username`` binds to, or ``None`` for no lookup. + + BACKLOG #4846. ``None`` for a name ending in ``$``: a machine account's, or an interdomain trust + account's, which is a person-category ``user`` that the Kerberos filter alone would find. No + person's name needs the ``$``. A malformed or empty realm raises :class:`LdapError`, a + configuration fault, never a reason to drop the binding. Both + :meth:`LdapAuthenticator.probe_principal`, before its session opens, and + :meth:`LdapAuthenticator._lookup_by_name`, where the filter is built, ask it. + """ + checked = _checked_kerberos_realm(realm) + return None if username.endswith("$") else checked + + def _account_in_realm(principal: str, realm: str) -> str: """The account name of ``principal``, whose realm must be ``realm`` (BACKLOG #2610). diff --git a/messagefoundry/auth/service.py b/messagefoundry/auth/service.py index 692c4e0fc4..3f042bac89 100644 --- a/messagefoundry/auth/service.py +++ b/messagefoundry/auth/service.py @@ -7078,6 +7078,9 @@ async def _authenticate_kerberos( self._ldap.resolve_principal, username, tie_break_object_id=await self._stored_directory_object_id(username), + # Only what the ticket proves, in the realm kerberos_principal checked it against + # (BACKLOG #4846). That call refused an unset realm already; "" would fail closed. + kerberos_realm=self._settings.kerberos_realm or "", ) except KerberosTokenRefused as exc: # BACKLOG #3196: audited as a failed sign-in, not a directory outage. An acceptor key diff --git a/tests/test_ad_ambiguous_name.py b/tests/test_ad_ambiguous_name.py index 245a336cd1..3962349e6f 100644 --- a/tests/test_ad_ambiguous_name.py +++ b/tests/test_ad_ambiguous_name.py @@ -166,8 +166,10 @@ def unbind(self) -> None: ... monkeypatch.setattr(ldap3, "Connection", FakeConnection) -def test_the_kerberos_lookup_resolves_no_principal(monkeypatch: pytest.MonkeyPatch) -> None: - """``resolve_principal`` with no object id is what the Kerberos sign-in calls.""" +def test_the_name_lookup_resolves_no_principal(monkeypatch: pytest.MonkeyPatch) -> None: + """``resolve_principal`` by name alone, as ``create_directory_account`` calls it. The Kerberos + sign-in passes ``kerberos_realm`` since BACKLOG #4846, which drops V as a UPN-only match; see + tests/test_kerberos_realm_binding.py.""" _install_directory(monkeypatch, []) auth = _authenticator() assert auth.resolve_principal("victor") is None @@ -256,8 +258,9 @@ def test_two_entries_carrying_the_stored_object_id_are_refused() -> None: def test_two_entries_holding_the_name_are_refused_whatever_the_stored_id() -> None: - """Same-named accounts in two domains under one search base. The ticket's realm is dropped - before the lookup, so it cannot say which one signed in, and the row's id must not choose.""" + """Same-named accounts in two domains under one search base. The name alone cannot say which + one is meant, and the row's id must not choose. The Kerberos lookup keeps only the one in the + ticket's realm (BACKLOG #4846); this is the name lookup the other callers keep.""" other_domain = _carrying(_Entry("victor", "CN=victor,DC=y"), _GUID_V) conn = _Conn([_carrying(_X, _GUID_X), other_domain]) found = _authenticator()._lookup_by_name(conn, "victor", tie_break_object_id=str(_GUID_X)) @@ -318,7 +321,12 @@ async def test_windows_sso_signs_a_bound_account_in_past_a_colliding_entry( The real ``LdapAuthenticator`` over a faked ``ldap3``; only the SPNEGO acceptor is replaced. The first sign-in finds X alone, and the row it creates is bound to X's id. Then V's UPN collides with the name. The sign-in must land on X's row, the one the engine already holds, and a - ticket for a name with no row must still be refused.""" + ticket for a name with no row must still be refused. + + Since BACKLOG #4846 the Kerberos lookup drops V before the tie-break, because V holds the name + only as a UPN, so this is still green with #3228 reverted and no longer exercises it. The realm + is ``X`` because the entries sit under ``DC=x``: that lookup keeps only entries in the realm's + domain.""" from messagefoundry.auth.service import AuthService from messagefoundry.store.store import MessageStore @@ -335,7 +343,7 @@ async def _no_pad(_deadline: float) -> None: _install_directory(monkeypatch, [], answer) store = await MessageStore.open(tmp_path / "tie-break.db") try: - settings = _settings(kerberos_enabled=True, kerberos_realm="EXAMPLE.COM") + settings = _settings(kerberos_enabled=True, kerberos_realm="X") service = AuthService(store, settings, ldap=LdapAuthenticator(settings)) await service.initialize() await service.set_ad_group_map([(group.lower(), "operator")], actor="admin") @@ -350,7 +358,8 @@ async def _no_pad(_deadline: float) -> None: assert again.ok, again.error assert again.identity is not None and again.identity.user_id == row.id - # Control: the same two entries, for a name no row holds, are still refused. + # Control: a name neither entry holds as its sAMAccountName is refused. Since BACKLOG + # #4846 that is a no-match rather than the ambiguity it once was. ticket["name"] = "vsmith-alias" refused = await service.authenticate_kerberos(b"spnego-token") assert not refused.ok diff --git a/tests/test_kerberos_realm_binding.py b/tests/test_kerberos_realm_binding.py new file mode 100644 index 0000000000..f8e5c48530 --- /dev/null +++ b/tests/test_kerberos_realm_binding.py @@ -0,0 +1,324 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +# Copyright (C) 2026 MessageFoundry Foundation, LLC and contributors +"""BACKLOG #4846: a Kerberos ticket resolves only to the account it proves. + +``kerberos_principal`` checks a ticket's realm against ``[auth].kerberos_realm`` and drops it +(BACKLOG #2610). The directory lookup that followed was the password path's name lookup, so +in the shipped code: + +* under a forest-wide base or the global catalog, ``alice@CORP.EXAMPLE`` would resolve to the + CHILD domain's ``alice`` when the root held none, and be refused as ambiguous when both did; +* a single entry holding only the UPN ``alice@``, under another ``sAMAccountName``, + would answer a ticket for ``alice``; +* a machine's ticket (``WS01$``) or a trust account's (``CHILD$``) was looked up like a person's. + +Pinned here, each with a control showing the name-keyed lookup the other callers keep still +answers the old way, so the difference is the Kerberos lookup and not the doubles. + +**Not exercised: a real directory.** The doubles return entries by construction and do not +evaluate the LDAP filter, so the ``objectCategory``/``objectClass`` clauses are pinned by reading +the filter sent, not by a domain controller answering it. Synthetic names only. +""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +import pytest +import spnego + +from messagefoundry.auth import ldap as ldap_mod +from messagefoundry.auth.ldap import DirectoryAnswer, LdapAuthenticator, LdapError, _Lookup +from messagefoundry.auth.service import AuthService +from messagefoundry.config.settings import AuthSettings +from messagefoundry.store.store import MessageStore + + +class _Attr: + def __init__(self, value: Any) -> None: + self.value = value + self.values = value if isinstance(value, list) else [value] + + +class _Entry: + def __init__(self, sam: str | None, dn: str) -> None: + self.entry_dn = dn + self._attrs = {"userAccountControl": _Attr("512"), "memberOf": _Attr([])} + if sam is not None: + self._attrs["sAMAccountName"] = _Attr(sam) + + def __contains__(self, name: str) -> bool: + return name in self._attrs + + def __getitem__(self, name: str) -> _Attr: + return self._attrs[name] + + +class _Conn: + """Answers every search with ``entries`` and records each search's filter.""" + + def __init__(self, entries: list[_Entry]) -> None: + self.entries = entries + self.result: dict[str, Any] | None = None # no referral + self.filters: list[str] = [] + + def search(self, **kwargs: Any) -> bool: + self.filters.append(kwargs["search_filter"]) + return True + + +_ROOT_ALICE = _Entry("alice", "CN=Alice Root,OU=Staff,DC=corp,DC=example") +_CHILD_ALICE = _Entry("alice", "CN=Alice Child,OU=Staff,DC=child,DC=corp,DC=example") +#: Holds the UPN alice@corp.example under another sAMAccountName, as a renamed account may. +_UPN_ONLY = _Entry("asmith", "CN=A Smith,OU=Staff,DC=corp,DC=example") + + +_REALM = "CORP.EXAMPLE" + + +def _authenticator() -> LdapAuthenticator: + return LdapAuthenticator( + AuthSettings( + ad_enabled=True, + ad_server="ldaps://dc.test.invalid", + ad_user_search_base="DC=corp,DC=example", + ad_bind_dn="CN=svc,DC=corp,DC=example", + ad_bind_password="synthetic", + ad_domain="corp.example", + ) + ) + + +def _kerberos(conn: _Conn, name: str, realm: str = _REALM) -> _Lookup: + return _authenticator()._lookup_by_name(conn, name, kerberos_realm=realm) + + +@pytest.fixture(autouse=True) +def _fresh_warning_latch(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(ldap_mod, "_object_guid_shapes_warned", set()) + + +# --- the DN's realm ----------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("dn", "realm"), + [ + ("CN=a,OU=Staff,DC=child,DC=corp,DC=example", "child.corp.example"), + ("cn=a,dc=CORP,dc=Example", "corp.example"), + ("CN=a, DC=corp , DC=example", "corp.example"), + # The type spelled as its name or its OID reads the same, and does not end the run. + ("CN=a,domainComponent=corp,DC=example", "corp.example"), + ("CN=a,0.9.2342.19200300.100.1.25=child,DC=corp,DC=example", "child.corp.example"), + # Only the trailing run counts: a DC= above an OU adds nothing. + ("CN=a,DC=evil,OU=x,DC=corp,DC=example", "corp.example"), + # A multi-valued RDN ends the run. + ("CN=a,DC=evil+OU=x,DC=corp,DC=example", "corp.example"), + # A label holding a dot, escaped or not, is not the RDNs a domain is written as. + ("CN=a,DC=corp.example", None), + ("CN=a,DC=corp\\2Eexample", None), + ("CN=a,DC=child.corp,DC=example", None), + ("CN=a,OU=Staff,O=example", None), + ("CN=a,DC=corp,OU=Staff", None), + ("not a dn", None), + ("", None), + ], +) +def test_the_dn_realm_is_the_trailing_dc_run(dn: str, realm: str | None) -> None: + assert ldap_mod._dn_realm(dn) == realm + + +def test_a_non_ascii_dc_never_equals_an_ascii_realm() -> None: + # The Kelvin sign lowers to an ASCII k; the canonical form escapes it instead. + assert ldap_mod._dn_realm("CN=a,DC=\N{KELVIN SIGN}orp,DC=example") != "korp.example" + + +def test_the_group_dn_form_is_unchanged_by_the_shared_parser() -> None: + """The parser was split out of ``canonical_group_dn``; its answers must not move.""" + assert ldap_mod.canonical_group_dn("CN=C\\23 Developers,DC=x") == "cn=c# developers,dc=x" + assert ldap_mod.canonical_group_dn("CN=Admins") is None # one RDN is still refused + assert ldap_mod._canonical_rdns("CN=Admins") == [["cn=admins"]] + + +# --- the cross-realm collision ------------------------------------------------------------------ + + +def test_a_root_ticket_resolves_to_the_root_account_under_a_forest_wide_base() -> None: + found = _kerberos(_Conn([_CHILD_ALICE, _ROOT_ALICE]), "alice") + assert found.answer is DirectoryAnswer.FOUND + assert found.info is not None and found.info["dn"] == _ROOT_ALICE.entry_dn + + +def test_a_root_ticket_never_resolves_to_a_child_account_alone() -> None: + """The finding's probe: before the fix this answered the CHILD alice.""" + conn = _Conn([_CHILD_ALICE]) + assert _authenticator()._lookup_by_name(conn, "alice").answer is DirectoryAnswer.FOUND + found = _kerberos(conn, "alice") + assert found.answer is DirectoryAnswer.NOT_FOUND and found.info is None + + +def test_a_child_realm_resolves_to_the_child_account() -> None: + found = _kerberos(_Conn([_ROOT_ALICE, _CHILD_ALICE]), "alice", "CHILD.CORP.EXAMPLE") + assert found.info is not None and found.info["dn"] == _CHILD_ALICE.entry_dn + + +def test_the_realm_compare_ignores_ascii_case_as_the_ticket_compare_does() -> None: + assert _kerberos(_Conn([_ROOT_ALICE]), "alice", "corp.EXAMPLE").answer is DirectoryAnswer.FOUND + + +def test_the_name_lookup_the_other_callers_keep_still_refuses_the_pair() -> None: + """Control: without ``kerberos_realm`` the two same-named entries are still ambiguous.""" + found = _authenticator()._lookup_by_name(_Conn([_CHILD_ALICE, _ROOT_ALICE]), "alice") + assert found.answer is DirectoryAnswer.AMBIGUOUS + + +def test_a_dropped_entry_is_logged_at_debug_by_label_and_count( + caplog: pytest.LogCaptureFixture, +) -> None: + """DEBUG, not WARNING: under the global catalog a name held in several domains drops entries + on every sign-in, which is routine rather than a fault to clear.""" + with caplog.at_level("DEBUG", logger="messagefoundry.auth.ldap"): + _kerberos(_Conn([_CHILD_ALICE, _ROOT_ALICE]), "alice") + messages = [ + r.getMessage() + for r in caplog.records + if r.name == "messagefoundry.auth.ldap" and r.getMessage().startswith("Kerberos lookup") + ] + assert len(messages) == 1 and "kept 1 of 2" in messages[0] + assert all(r.levelname == "DEBUG" for r in caplog.records if "Kerberos lookup" in r.message) + assert "alice" not in messages[0].lower() + assert "child" not in messages[0].lower() + + +# --- the UPN-only match ------------------------------------------------------------------------- + + +def test_a_ticket_never_resolves_to_an_entry_holding_only_the_upn() -> None: + conn = _Conn([_UPN_ONLY]) + # Control: the password path's lookup still takes the single UPN match, as it did. + assert _authenticator()._lookup_by_name(conn, "alice").answer is DirectoryAnswer.FOUND + assert _kerberos(conn, "alice").answer is DirectoryAnswer.NOT_FOUND + + +def test_an_entry_with_no_readable_name_is_not_the_holder() -> None: + found = _kerberos(_Conn([_Entry(None, "CN=x,DC=corp,DC=example")]), "alice") + assert found.answer is DirectoryAnswer.NOT_FOUND + + +def test_the_kerberos_filter_asks_for_a_person_by_sam_account_name_only() -> None: + conn = _Conn([_ROOT_ALICE]) + _kerberos(conn, "al*ce") + assert conn.filters == ["(&(objectCategory=person)(objectClass=user)(sAMAccountName=al\\2ace))"] + assert "userPrincipalName" not in conn.filters[0] + + +# --- machine and trust accounts, and the realm, before any session ------------------------------- + + +class _NoSession(LdapAuthenticator): + """Fails the test if a session is opened: these refusals need no directory.""" + + def _service_session(self) -> Any: + raise AssertionError("a directory session was opened") + + +def _no_session() -> _NoSession: + return _NoSession(_authenticator()._s) + + +@pytest.mark.parametrize("name", ["WS01$", "CHILD$", "$"]) +def test_a_dollar_name_is_not_found_without_a_session(name: str) -> None: + probe = _no_session().probe_principal(name, kerberos_realm=_REALM) + assert probe.answer is DirectoryAnswer.NOT_FOUND and probe.principal is None + + +@pytest.mark.parametrize("name", ["WS01$", "CHILD$"]) +def test_the_kerberos_lookup_itself_never_searches_a_dollar_name(name: str) -> None: + """Where the filter is built, too, so a caller that skips ``probe_principal`` is covered: a + trust account is a person-category user the filter alone would return.""" + conn = _Conn([_Entry(name, "CN=CHILD$,CN=Users,DC=corp,DC=example")]) + assert _kerberos(conn, name).answer is DirectoryAnswer.NOT_FOUND and conn.filters == [] + + +def test_the_kerberos_lookup_itself_refuses_an_empty_realm() -> None: + conn = _Conn([_ROOT_ALICE]) + with pytest.raises(LdapError, match="kerberos_realm must be"): + _kerberos(conn, "alice", "") + assert conn.filters == [] + + +def test_an_in_realm_entry_whose_dn_the_parser_refuses_is_dropped() -> None: + """Fails closed: an unescaped quote is a shape the shared DN parser refuses.""" + quoted = _Entry("alice", 'CN=Alice "Al" Root,OU=Staff,DC=corp,DC=example') + assert ldap_mod._dn_realm(str(quoted.entry_dn)) is None + assert _kerberos(_Conn([quoted]), "alice").answer is DirectoryAnswer.NOT_FOUND + + +def test_the_name_lookup_the_other_callers_keep_still_searches_a_dollar_name() -> None: + """Control: without ``kerberos_realm`` a ``$`` name is searched and found as before.""" + conn = _Conn([_Entry("WS01$", "CN=WS01,OU=Computers,DC=corp,DC=example")]) + assert _authenticator()._lookup_by_name(conn, "WS01$").answer is DirectoryAnswer.FOUND + + +@pytest.mark.parametrize("realm", ["", "CORP EXAMPLE", "alice@CORP.EXAMPLE"]) +def test_an_empty_or_malformed_realm_raises_rather_than_dropping_the_check(realm: str) -> None: + with pytest.raises(LdapError, match="kerberos_realm must be"): + _no_session().probe_principal("alice", kerberos_realm=realm) + + +def test_kerberos_with_an_object_id_is_a_programming_error() -> None: + with pytest.raises(ValueError, match="object_id or kerberos_realm"): + _no_session().probe_principal("alice", object_id="x", kerberos_realm=_REALM) + + +# --- the service -------------------------------------------------------------------------------- + + +class _RecordingDirectory: + def __init__(self) -> None: + self.calls: list[tuple[str, dict[str, object]]] = [] + + def resolve_principal(self, username: str, **kwargs: object) -> Any: + self.calls.append((username, kwargs)) + return None + + +async def test_the_kerberos_sign_in_asks_the_narrow_lookup_in_the_checked_realm( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + async def no_sleep(_deadline: float) -> None: + return None + + class _Server: + client_principal = "alice@corp.example" + complete = True + + def step(self, _token: bytes) -> None: + return None + + monkeypatch.setattr("messagefoundry.auth.service._sleep_until", no_sleep) + monkeypatch.setattr(spnego, "server", lambda **_: _Server()) + monkeypatch.setattr(ldap_mod, "_kerberos_capable", lambda: True) + directory = _RecordingDirectory() + settings = AuthSettings( + ad_enabled=True, + ad_server="ldaps://dc.test.invalid", + ad_user_search_base="DC=corp,DC=example", + ad_bind_dn="CN=svc,DC=corp,DC=example", + ad_bind_password="synthetic", + kerberos_enabled=True, + kerberos_realm=_REALM, + login_rate_limit_enabled=False, + require_mfa=False, + ) + store = await MessageStore.open(tmp_path / "kerberos_realm_binding.db") + try: + service = AuthService(store, settings, ldap=directory) # type: ignore[arg-type] + await service.initialize() + outcome = await service.authenticate_kerberos(b"token", client="192.0.2.7") + finally: + await store.close() + assert not outcome.ok + # The realm handed over is the configured one the ticket was checked against. + assert directory.calls == [("alice", {"tie_break_object_id": None, "kerberos_realm": _REALM})]