From 08d5255acd0a54865c4fde4b4238ea2e0087bdb9 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 09:02:15 -0600 Subject: [PATCH 1/4] Kerberos sign-in: bind the realm to the directory entry, drop UPN and machine matches 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. resolve_principal and probe_principal take kerberos=True, which only the Kerberos sign-in passes. That lookup: - filters on objectCategory=person, objectClass=user and sAMAccountName only, with no userPrincipalName arm; - answers NOT_FOUND for a name ending in $ before any search (machine and interdomain trust accounts); - keeps only entries whose own sAMAccountName is the name and whose DN ends in the DC= RDNs of the realm's domain, up to ASCII case. The DN parser behind canonical_group_dn is split out as _canonical_rdns so _dn_realm reads a DN the same way. The realm is read from the authenticator's own settings and an unset one raises LdapError. test_ad_ambiguous_name's Windows SSO tie-break test now sets the realm to X, the domain its entries sit under. BACKLOG #4846 --- messagefoundry/auth/ldap.py | 170 ++++++++++++++-- messagefoundry/auth/service.py | 1 + tests/test_ad_ambiguous_name.py | 8 +- tests/test_kerberos_realm_binding.py | 291 +++++++++++++++++++++++++++ 4 files changed, 449 insertions(+), 21 deletions(-) create mode 100644 tests/test_kerberos_realm_binding.py diff --git a/messagefoundry/auth/ldap.py b/messagefoundry/auth/ldap.py index 36480c3648..53e7d4cf83 100644 --- a/messagefoundry/auth/ldap.py +++ b/messagefoundry/auth/ldap.py @@ -756,6 +756,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 +831,28 @@ def close_ava() -> bool: if not close_ava(): return None rdns.append(sorted(avas)) - if len(rdns) < _GROUP_DN_MIN_RDNS: + return rdns + + +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. ``None`` when ``dn`` does + not parse or ends in no ``DC=`` RDN. The value is canonical (:func:`_canonical_value`), so ASCII + letters are lower-case and any other character is a ``\\xx`` escape that no realm, which is + printable ASCII (``check_kerberos_realm``), can equal. + """ + 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 or not rdn[0].startswith("dc="): + break + labels.append(rdn[0][3:]) + return ".".join(reversed(labels)) or None def is_group_dn(value: str) -> bool: @@ -1955,6 +1988,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,6 +2004,10 @@ 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. + 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 @@ -1998,11 +2036,14 @@ 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: + if len(entries) > 1: # Vault BACKLOG #2778. The name filter matches sAMAccountName OR userPrincipalName, 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 @@ -2015,29 +2056,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 (_attr(x, "sAMAccountName") or "").lower() == 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 +2084,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 +2126,56 @@ 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``, compared with ``lower()`` as the ambiguity check + does. The Kerberos filter asks for nothing else, so this only re-reads what the directory + answered; an entry with no readable name is not shown to be the holder; + - the ``DC=`` suffix of its DN is 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. A directory whose DNs do not follow + that, such as a realm trusted from outside AD, matches no entry, which fails closed. + A dropped entry is logged once per name, with a label for it and the counts only. + """ + domain = realm.lower() + held = name.lower() + kept = [ + x + for x in entries + if (_attr(x, "sAMAccountName") or "").lower() == held + and _dn_realm(str(x.entry_dn)) == domain + ] + if len(kept) < len(entries): + label = safe_name(name) + _warn_once( + f"kerberos-outside-realm:{label}", + "Kerberos lookup for %s kept %d of %d directory entries; the rest are outside " + "[auth].kerberos_realm's domain or do not hold the name (logged once per name)", + label, + 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: bool = False, ) -> _Lookup: """Find a user by name. ``tie_break_object_id`` only chooses among several matches. @@ -2100,7 +2184,41 @@ 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`` asks the narrower question a ticket answers (BACKLOG #4846).** A ticket for + ``alice`` in ``[auth].kerberos_realm`` proves only that its holder is the person account + whose ``sAMAccountName`` is ``alice`` in that 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@`` and another name answered the ticket alone, so a renamed account + that kept its old UPN signed 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; + - a name ending in ``$`` is answered NOT_FOUND before any search. An interdomain trust + account is a person-category ``user`` named ``CHILD$``, so the filter alone would find it. + No person account's name needs the ``$``; + - only entries in the realm's domain, holding the name, are read (:meth:`_kerberos_holders`). + + The realm is read from this authenticator's own settings, as :func:`kerberos_principal` + reads it, and an unset one raises :class:`LdapError` rather than dropping the check. """ + if kerberos: + realm = _configured_kerberos_realm(self._s) + if username.endswith("$"): + return _Lookup(DirectoryAnswer.NOT_FOUND) + return self._search_user( + conn, + ( + "(&(objectCategory=person)(objectClass=user)" + f"(sAMAccountName={_escape_filter(username)}))" + ), + fallback_username=username, + tie_break_object_id=normalise_object_guid(tie_break_object_id), + kerberos_realm=realm, + ) upn = f"{username}@{self._s.ad_domain}" if self._s.ad_domain else username return self._search_user( conn, @@ -2286,6 +2404,7 @@ def resolve_principal( *, object_id: str | None = None, tie_break_object_id: str | None = None, + kerberos: bool = False, ) -> AdPrincipal | None: """Look a user up + resolve groups *without* a password. Uses the service-account bind only. @@ -2313,9 +2432,17 @@ 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`` is for the Kerberos sign-in alone: ``username`` is a ticket's account name, and + the lookup asks only what that 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=kerberos, ).principal def probe_principal( @@ -2324,6 +2451,7 @@ def probe_principal( *, object_id: str | None = None, tie_break_object_id: str | None = None, + kerberos: bool = False, ) -> DirectoryProbe: """:meth:`resolve_principal`, also saying WHY an account did not resolve (ADR 0195). @@ -2340,13 +2468,15 @@ 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: + raise ValueError("pass object_id or kerberos, not both") 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=kerberos ) ) info = found.info @@ -2527,7 +2657,9 @@ 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=True`` (: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 diff --git a/messagefoundry/auth/service.py b/messagefoundry/auth/service.py index 692c4e0fc4..06a510667c 100644 --- a/messagefoundry/auth/service.py +++ b/messagefoundry/auth/service.py @@ -7078,6 +7078,7 @@ async def _authenticate_kerberos( self._ldap.resolve_principal, username, tie_break_object_id=await self._stored_directory_object_id(username), + kerberos=True, # only what the ticket proves (BACKLOG #4846) ) 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..e3a9e45508 100644 --- a/tests/test_ad_ambiguous_name.py +++ b/tests/test_ad_ambiguous_name.py @@ -318,7 +318,11 @@ 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. 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 +339,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") diff --git a/tests/test_kerberos_realm_binding.py b/tests/test_kerberos_realm_binding.py new file mode 100644 index 0000000000..0d8a26a310 --- /dev/null +++ b/tests/test_kerberos_realm_binding.py @@ -0,0 +1,291 @@ +# 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: + +* under a forest-wide base or the global catalog, ``alice@CORP.EXAMPLE`` resolved to the CHILD + domain's ``alice`` when the root held none, and was refused as ambiguous when both held one; +* a single entry holding only the UPN ``alice@``, under another ``sAMAccountName``, + answered a ticket for ``alice``; +* a machine's ticket (``WS01$``) or a trust account's (``CHILD$``) 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 collections.abc import AsyncIterator +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 +from messagefoundry.auth.service import AuthService +from messagefoundry.config.settings import AuthSettings, EgressSettings +from messagefoundry.pipeline import Engine + + +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") + + +def _authenticator(realm: str | None = "CORP.EXAMPLE") -> 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", + 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"), + # 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"), + ("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 = _authenticator()._lookup_by_name( + _Conn([_CHILD_ALICE, _ROOT_ALICE]), "alice", kerberos=True + ) + 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 = _authenticator()._lookup_by_name(conn, "alice", kerberos=True) + assert found.answer is DirectoryAnswer.NOT_FOUND and found.info is None + + +def test_a_child_realm_resolves_to_the_child_account() -> None: + found = _authenticator("CHILD.CORP.EXAMPLE")._lookup_by_name( + _Conn([_ROOT_ALICE, _CHILD_ALICE]), "alice", kerberos=True + ) + 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: + found = _authenticator("corp.EXAMPLE")._lookup_by_name( + _Conn([_ROOT_ALICE]), "alice", kerberos=True + ) + assert found.answer is DirectoryAnswer.FOUND + + +def test_the_name_lookup_the_other_callers_keep_still_refuses_the_pair() -> None: + """Control: without ``kerberos`` 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_by_label_and_count(caplog: pytest.LogCaptureFixture) -> None: + with caplog.at_level("WARNING", logger="messagefoundry.auth.ldap"): + _authenticator()._lookup_by_name(_Conn([_CHILD_ALICE, _ROOT_ALICE]), "alice", kerberos=True) + 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 "alice" not in messages[0].lower().replace("kerberos", "") + 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 + found = _authenticator()._lookup_by_name(conn, "alice", kerberos=True) + assert found.answer is DirectoryAnswer.NOT_FOUND + + +def test_an_entry_with_no_readable_name_is_not_the_holder() -> None: + found = _authenticator()._lookup_by_name( + _Conn([_Entry(None, "CN=x,DC=corp,DC=example")]), "alice", kerberos=True + ) + 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]) + _authenticator()._lookup_by_name(conn, "al*ce", kerberos=True) + assert conn.filters == ["(&(objectCategory=person)(objectClass=user)(sAMAccountName=al\\2ace))"] + assert "userPrincipalName" not in conn.filters[0] + + +# --- machine and trust accounts ----------------------------------------------------------------- + + +@pytest.mark.parametrize("name", ["WS01$", "CHILD$", "$"]) +def test_a_dollar_name_is_not_found_without_a_search(name: str) -> None: + conn = _Conn([_Entry(name, "CN=WS01,OU=Computers,DC=corp,DC=example")]) + # Control: the name lookup the other callers keep still searches and finds it. + assert _authenticator()._lookup_by_name(conn, name).answer is DirectoryAnswer.FOUND + conn.filters.clear() + found = _authenticator()._lookup_by_name(conn, name, kerberos=True) + assert found.answer is DirectoryAnswer.NOT_FOUND and conn.filters == [] + + +# --- fail closed ---------------------------------------------------------------------------------- + + +def test_an_unset_realm_raises_rather_than_dropping_the_check() -> None: + conn = _Conn([_ROOT_ALICE]) + with pytest.raises(LdapError, match="kerberos_realm is not set"): + _authenticator(realm=None)._lookup_by_name(conn, "alice", kerberos=True) + assert conn.filters == [] + + +def test_kerberos_with_an_object_id_is_a_programming_error() -> None: + with pytest.raises(ValueError, match="object_id or kerberos"): + _authenticator().probe_principal("alice", object_id="x", kerberos=True) + + +# --- the service -------------------------------------------------------------------------------- + + +@pytest.fixture +async def engine(tmp_path: Path) -> AsyncIterator[Engine]: + eng = await Engine.create( + tmp_path / "kerberos_realm_binding.db", + poll_interval=0.02, + egress_settings=EgressSettings(deny_by_default=False), + ) + yield eng + await eng.stop() + + +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( + engine: Engine, monkeypatch: pytest.MonkeyPatch +) -> 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="CORP.EXAMPLE", + login_rate_limit_enabled=False, + require_mfa=False, + ) + service = AuthService(engine.store, settings, ldap=directory) # type: ignore[arg-type] + await service.initialize() + outcome = await service.authenticate_kerberos(b"token", client="192.0.2.7") + assert not outcome.ok + assert directory.calls == [("alice", {"tie_break_object_id": None, "kerberos": True})] From d2c225cee6423b3917f8d49a8bffc27d4ad2d74e Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 09:04:31 -0600 Subject: [PATCH 2/4] Docs: the Kerberos lookup binds the realm to the entry; changelog fragment SECURITY.md's Kerberos realm paragraph says what the narrowed lookup asks, what it refuses, and the Active Directory assumption it rests on. BACKLOG #4846 --- .../4846-kerberos-realm-bound-to-entry.security.md | 10 ++++++++++ docs/SECURITY.md | 11 +++++++++++ 2 files changed, 21 insertions(+) create mode 100644 changelog.d/4846-kerberos-realm-bound-to-entry.security.md 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..fa8a0960c5 --- /dev/null +++ b/changelog.d/4846-kerberos-realm-bound-to-entry.security.md @@ -0,0 +1,10 @@ +- **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 ends in the realm's `DC=` RDNs, 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. 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..55d628fac1 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -5431,6 +5431,17 @@ 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 ends in the `DC=` RDNs of 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; a realm whose users sit under other DNs + matches no entry, and the sign-in is refused as `not_in_directory`. The password sign-in and the + other name-keyed lookups are unchanged. ### AD-group → role mapping From 836bb06405a6cc2d9acad236bb531f9ab683349d Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 09:37:57 -0600 Subject: [PATCH 3/4] Kerberos lookup: take the checked realm, refuse dotted DC labels, refuse early Review round 1 on the realm binding: - the lookup takes kerberos_realm from the caller, the same settings value kerberos_principal checked the ticket against, instead of the authenticator's own copy; an empty or malformed one raises LdapError; - _dn_realm refuses a DC label holding a dot, escaped or not, and reads the domainComponent name and OID as dc; - the $ refusal and the realm check run in probe_principal before the service session opens; - one _search_user call site; docstrings, SECURITY.md and the changelog say what the lookup now reads, including that a ticket naming an implicit UPN finds nothing; - stale Kerberos wording in test_ad_ambiguous_name is corrected. BACKLOG #4846 --- ...-kerberos-realm-bound-to-entry.security.md | 4 +- docs/SECURITY.md | 9 +- messagefoundry/auth/ldap.py | 128 +++++++++++------- messagefoundry/auth/service.py | 4 +- tests/test_ad_ambiguous_name.py | 19 ++- tests/test_kerberos_realm_binding.py | 127 ++++++++--------- 6 files changed, 167 insertions(+), 124 deletions(-) diff --git a/changelog.d/4846-kerberos-realm-bound-to-entry.security.md b/changelog.d/4846-kerberos-realm-bound-to-entry.security.md index fa8a0960c5..53a59db7d3 100644 --- a/changelog.d/4846-kerberos-realm-bound-to-entry.security.md +++ b/changelog.d/4846-kerberos-realm-bound-to-entry.security.md @@ -6,5 +6,7 @@ (`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 ends in the realm's `DC=` RDNs, 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. The password sign-in is unchanged. See + 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 55d628fac1..b0364f0ad7 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -5439,9 +5439,12 @@ Both kinds of user share one identity model (`users.auth_provider` is `local` or 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; a realm whose users sit under other DNs - matches no entry, and the sign-in is refused as `not_in_directory`. The password sign-in and the - other name-keyed lookups are unchanged. + DNS name and its naming context that name's `DC=` RDNs. An entry whose DN does not end in the + realm's `DC=` RDNs, one label each, matches nothing, and the sign-in is 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 53e7d4cf83..86cd39bbe6 100644 --- a/messagefoundry/auth/ldap.py +++ b/messagefoundry/auth/ldap.py @@ -834,24 +834,38 @@ def close_ava() -> bool: 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. ``None`` when ``dn`` does - not parse or ends in no ``DC=`` RDN. The value is canonical (:func:`_canonical_value`), so ASCII + 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`), so ASCII letters are lower-case and any other character is a ``\\xx`` escape that no realm, which is printable ASCII (``check_kerberos_realm``), can equal. + + ``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 labels: list[str] = [] for rdn in reversed(rdns): - if len(rdn) != 1 or not rdn[0].startswith("dc="): + if len(rdn) != 1: break - labels.append(rdn[0][3:]) + 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 @@ -2006,12 +2020,15 @@ def _search_user( ``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. + :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 @@ -2044,7 +2061,8 @@ def _search_user( e = entries[0] own: str | None = None if len(entries) > 1: - # Vault BACKLOG #2778. The name filter matches sAMAccountName OR userPrincipalName, and + # 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: @@ -2143,7 +2161,8 @@ def _kerberos_holders(entries: list[Any], name: str, realm: str) -> list[Any]: 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. A directory whose DNs do not follow - that, such as a realm trusted from outside AD, matches no entry, which fails closed. + that, so that its users' DNs do not end in the realm's ``DC=`` RDNs, matches no entry, which + fails closed. A dropped entry is logged once per name, with a label for it and the counts only. """ domain = realm.lower() @@ -2175,7 +2194,7 @@ def _lookup_by_name( username: str, *, tie_break_object_id: str | None = None, - kerberos: bool = False, + kerberos_realm: str | None = None, ) -> _Lookup: """Find a user by name. ``tie_break_object_id`` only chooses among several matches. @@ -2185,49 +2204,39 @@ def _lookup_by_name( 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`` asks the narrower question a ticket answers (BACKLOG #4846).** A ticket for - ``alice`` in ``[auth].kerberos_realm`` proves only that its holder is the person account - whose ``sAMAccountName`` is ``alice`` in that realm's domain, so the lookup asks for that - and nothing wider: + **``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@`` and another name answered the ticket alone, so a renamed account + ``alice@`` under another name answered the ticket alone, so a renamed account that kept its old UPN signed 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; - - a name ending in ``$`` is answered NOT_FOUND before any search. An interdomain trust - account is a person-category ``user`` named ``CHILD$``, so the filter alone would find it. - No person account's name needs the ``$``; - only entries in the realm's domain, holding the name, are read (:meth:`_kerberos_holders`). - The realm is read from this authenticator's own settings, as :func:`kerberos_principal` - reads it, and an unset one raises :class:`LdapError` rather than dropping the check. + A name ending in ``$`` is refused before this, by :meth:`probe_principal`. """ - if kerberos: - realm = _configured_kerberos_realm(self._s) - if username.endswith("$"): - return _Lookup(DirectoryAnswer.NOT_FOUND) - return self._search_user( - conn, - ( - "(&(objectCategory=person)(objectClass=user)" - f"(sAMAccountName={_escape_filter(username)}))" - ), - fallback_username=username, - tie_break_object_id=normalise_object_guid(tie_break_object_id), - kerberos_realm=realm, + if kerberos_realm is not None: + search_filter = ( + "(&(objectCategory=person)(objectClass=user)" + f"(sAMAccountName={_escape_filter(username)}))" ) - upn = f"{username}@{self._s.ad_domain}" if self._s.ad_domain else username - return self._search_user( - conn, - ( + 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: @@ -2404,7 +2413,7 @@ def resolve_principal( *, object_id: str | None = None, tie_break_object_id: str | None = None, - kerberos: bool = False, + kerberos_realm: str | None = None, ) -> AdPrincipal | None: """Look a user up + resolve groups *without* a password. Uses the service-account bind only. @@ -2433,16 +2442,17 @@ def resolve_principal( (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`` is for the Kerberos sign-in alone: ``username`` is a ticket's account name, and - the lookup asks only what that 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. + ``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, - kerberos=kerberos, + kerberos_realm=kerberos_realm, ).principal def probe_principal( @@ -2451,7 +2461,7 @@ def probe_principal( *, object_id: str | None = None, tie_break_object_id: str | None = None, - kerberos: bool = False, + kerberos_realm: str | None = None, ) -> DirectoryProbe: """:meth:`resolve_principal`, also saying WHY an account did not resolve (ADR 0195). @@ -2468,15 +2478,30 @@ 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: - raise ValueError("pass object_id or kerberos, not both") + if object_id is not None and kerberos_realm is not None: + raise ValueError("pass object_id or kerberos_realm, not both") + if kerberos_realm is not None: + # Before the session opens, since neither needs the directory (BACKLOG #4846). The + # realm is checked again, as _configured_kerberos_realm does: an empty or malformed one + # is a configuration fault, never a reason to drop the binding. + try: + kerberos_realm = check_kerberos_realm(kerberos_realm) + except ValueError as exc: + raise LdapError(str(exc)) from exc + if username.endswith("$"): + # A machine account's name, and an interdomain trust account's, which is a + # person-category user that the filter alone would find. No person needs the $. + 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, kerberos=kerberos + svc, + username, + tie_break_object_id=tie_break_object_id, + kerberos_realm=kerberos_realm, ) ) info = found.info @@ -2658,8 +2683,9 @@ def kerberos_principal(token: bytes, settings: AuthSettings) -> str | None: 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). The realm is dropped from the answer, so the caller must look - the name up with ``kerberos=True`` (:meth:`LdapAuthenticator.resolve_principal`), which binds - it to an entry in that realm's domain again (BACKLOG #4846). + 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 diff --git a/messagefoundry/auth/service.py b/messagefoundry/auth/service.py index 06a510667c..3f042bac89 100644 --- a/messagefoundry/auth/service.py +++ b/messagefoundry/auth/service.py @@ -7078,7 +7078,9 @@ async def _authenticate_kerberos( self._ldap.resolve_principal, username, tie_break_object_id=await self._stored_directory_object_id(username), - kerberos=True, # only what the ticket proves (BACKLOG #4846) + # 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 e3a9e45508..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)) @@ -321,8 +324,9 @@ async def test_windows_sso_signs_a_bound_account_in_past_a_colliding_entry( 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. The realm is ``X`` because the - entries sit under ``DC=x``: that lookup keeps only entries in the realm's domain.""" + 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 @@ -354,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 index 0d8a26a310..eec6d4124d 100644 --- a/tests/test_kerberos_realm_binding.py +++ b/tests/test_kerberos_realm_binding.py @@ -21,7 +21,6 @@ from __future__ import annotations -from collections.abc import AsyncIterator from pathlib import Path from typing import Any @@ -29,10 +28,10 @@ import spnego from messagefoundry.auth import ldap as ldap_mod -from messagefoundry.auth.ldap import DirectoryAnswer, LdapAuthenticator, LdapError +from messagefoundry.auth.ldap import DirectoryAnswer, LdapAuthenticator, LdapError, _Lookup from messagefoundry.auth.service import AuthService -from messagefoundry.config.settings import AuthSettings, EgressSettings -from messagefoundry.pipeline import Engine +from messagefoundry.config.settings import AuthSettings +from messagefoundry.store.store import MessageStore class _Attr: @@ -74,7 +73,10 @@ def search(self, **kwargs: Any) -> bool: _UPN_ONLY = _Entry("asmith", "CN=A Smith,OU=Staff,DC=corp,DC=example") -def _authenticator(realm: str | None = "CORP.EXAMPLE") -> LdapAuthenticator: +_REALM = "CORP.EXAMPLE" + + +def _authenticator() -> LdapAuthenticator: return LdapAuthenticator( AuthSettings( ad_enabled=True, @@ -83,11 +85,14 @@ def _authenticator(realm: str | None = "CORP.EXAMPLE") -> LdapAuthenticator: ad_bind_dn="CN=svc,DC=corp,DC=example", ad_bind_password="synthetic", ad_domain="corp.example", - kerberos_realm=realm, ) ) +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()) @@ -102,10 +107,17 @@ def _fresh_warning_latch(monkeypatch: pytest.MonkeyPatch) -> None: ("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), @@ -132,9 +144,7 @@ def test_the_group_dn_form_is_unchanged_by_the_shared_parser() -> None: def test_a_root_ticket_resolves_to_the_root_account_under_a_forest_wide_base() -> None: - found = _authenticator()._lookup_by_name( - _Conn([_CHILD_ALICE, _ROOT_ALICE]), "alice", kerberos=True - ) + 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 @@ -143,40 +153,35 @@ 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 = _authenticator()._lookup_by_name(conn, "alice", kerberos=True) + 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 = _authenticator("CHILD.CORP.EXAMPLE")._lookup_by_name( - _Conn([_ROOT_ALICE, _CHILD_ALICE]), "alice", kerberos=True - ) + 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: - found = _authenticator("corp.EXAMPLE")._lookup_by_name( - _Conn([_ROOT_ALICE]), "alice", kerberos=True - ) - assert found.answer is DirectoryAnswer.FOUND + 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`` the two same-named entries are still ambiguous.""" + """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_by_label_and_count(caplog: pytest.LogCaptureFixture) -> None: with caplog.at_level("WARNING", logger="messagefoundry.auth.ldap"): - _authenticator()._lookup_by_name(_Conn([_CHILD_ALICE, _ROOT_ALICE]), "alice", kerberos=True) + _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 "alice" not in messages[0].lower().replace("kerberos", "") + assert "alice" not in messages[0].lower() assert "child" not in messages[0].lower() @@ -187,66 +192,61 @@ 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 - found = _authenticator()._lookup_by_name(conn, "alice", kerberos=True) - assert found.answer is DirectoryAnswer.NOT_FOUND + assert _kerberos(conn, "alice").answer is DirectoryAnswer.NOT_FOUND def test_an_entry_with_no_readable_name_is_not_the_holder() -> None: - found = _authenticator()._lookup_by_name( - _Conn([_Entry(None, "CN=x,DC=corp,DC=example")]), "alice", kerberos=True - ) + 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]) - _authenticator()._lookup_by_name(conn, "al*ce", kerberos=True) + _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 ----------------------------------------------------------------- +# --- 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_search(name: str) -> None: - conn = _Conn([_Entry(name, "CN=WS01,OU=Computers,DC=corp,DC=example")]) - # Control: the name lookup the other callers keep still searches and finds it. - assert _authenticator()._lookup_by_name(conn, name).answer is DirectoryAnswer.FOUND - conn.filters.clear() - found = _authenticator()._lookup_by_name(conn, name, kerberos=True) - assert found.answer is DirectoryAnswer.NOT_FOUND and conn.filters == [] +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 -# --- fail closed ---------------------------------------------------------------------------------- +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 -def test_an_unset_realm_raises_rather_than_dropping_the_check() -> None: - conn = _Conn([_ROOT_ALICE]) - with pytest.raises(LdapError, match="kerberos_realm is not set"): - _authenticator(realm=None)._lookup_by_name(conn, "alice", kerberos=True) - assert conn.filters == [] +@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"): - _authenticator().probe_principal("alice", object_id="x", kerberos=True) + with pytest.raises(ValueError, match="object_id or kerberos_realm"): + _no_session().probe_principal("alice", object_id="x", kerberos_realm=_REALM) # --- the service -------------------------------------------------------------------------------- -@pytest.fixture -async def engine(tmp_path: Path) -> AsyncIterator[Engine]: - eng = await Engine.create( - tmp_path / "kerberos_realm_binding.db", - poll_interval=0.02, - egress_settings=EgressSettings(deny_by_default=False), - ) - yield eng - await eng.stop() - - class _RecordingDirectory: def __init__(self) -> None: self.calls: list[tuple[str, dict[str, object]]] = [] @@ -256,14 +256,14 @@ def resolve_principal(self, username: str, **kwargs: object) -> Any: return None -async def test_the_kerberos_sign_in_asks_the_narrow_lookup( - engine: Engine, monkeypatch: pytest.MonkeyPatch +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" + client_principal = "alice@corp.example" complete = True def step(self, _token: bytes) -> None: @@ -280,12 +280,17 @@ def step(self, _token: bytes) -> None: ad_bind_dn="CN=svc,DC=corp,DC=example", ad_bind_password="synthetic", kerberos_enabled=True, - kerberos_realm="CORP.EXAMPLE", + kerberos_realm=_REALM, login_rate_limit_enabled=False, require_mfa=False, ) - service = AuthService(engine.store, settings, ldap=directory) # type: ignore[arg-type] - await service.initialize() - outcome = await service.authenticate_kerberos(b"token", client="192.0.2.7") + 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 - assert directory.calls == [("alice", {"tie_break_object_id": None, "kerberos": True})] + # 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})] From 7239655b6fd5781f5e3c0eaf3b2739168cb7104a Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 10:04:15 -0600 Subject: [PATCH 4/4] Kerberos lookup: guard where the filter is built, one name rule, DEBUG drops Review round 2 on the realm binding: - _kerberos_lookup_realm checks the realm and refuses a $ name, asked by both probe_principal (before the session) and _lookup_by_name (where the filter is built), so neither guard rests on the call path; - _checked_kerberos_realm is the one ValueError-to-LdapError mapping; - _holds_name is the one sAMAccountName rule for the ambiguity check and the Kerberos narrowing; - a dropped entry logs at DEBUG: under the global catalog it is routine; - SECURITY.md, the changelog and the docstrings state the binding as the whole trailing DC= run equalling the realm, name the parser-refused DN case, and use the conditional for beta defects. BACKLOG #4846 --- ...-kerberos-realm-bound-to-entry.security.md | 10 +- docs/SECURITY.md | 10 +- messagefoundry/auth/ldap.py | 109 +++++++++++------- tests/test_kerberos_realm_binding.py | 42 +++++-- 4 files changed, 111 insertions(+), 60 deletions(-) diff --git a/changelog.d/4846-kerberos-realm-bound-to-entry.security.md b/changelog.d/4846-kerberos-realm-bound-to-entry.security.md index 53a59db7d3..682c223665 100644 --- a/changelog.d/4846-kerberos-realm-bound-to-entry.security.md +++ b/changelog.d/4846-kerberos-realm-bound-to-entry.security.md @@ -4,9 +4,9 @@ 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 ends in the realm's `DC=` RDNs, 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 + 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 b0364f0ad7..f4b59f31da 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -5433,15 +5433,15 @@ Both kinds of user share one identity model (`users.auth_provider` is `local` or 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 ends in the `DC=` RDNs of the realm's - domain, compared up to ASCII case as the ticket's realm is. So under a forest-wide base or the + `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 DN does not end in the - realm's `DC=` RDNs, one label each, matches nothing, and the sign-in is refused as - `not_in_directory`. So does a ticket naming the account by an implicit UPN rather than 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. diff --git a/messagefoundry/auth/ldap.py b/messagefoundry/auth/ldap.py index 86cd39bbe6..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 [] @@ -845,9 +855,10 @@ def _dn_realm(dn: str) -> str | 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`), so ASCII - letters are lower-case and any other character is a ``\\xx`` escape that no realm, which is - printable ASCII (``check_kerberos_realm``), can equal. + 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 @@ -2089,7 +2100,7 @@ def _search_user( # 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 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 @@ -2151,35 +2162,33 @@ def _kerberos_holders(entries: list[Any], name: str, realm: str) -> list[Any]: 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``, compared with ``lower()`` as the ambiguity check - does. The Kerberos filter asks for nothing else, so this only re-reads what the directory - answered; an entry with no readable name is not shown to be the holder; - - the ``DC=`` suffix of its DN is 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. + - 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. A directory whose DNs do not follow - that, so that its users' DNs do not end in the realm's ``DC=`` RDNs, matches no entry, which - fails closed. - A dropped entry is logged once per name, with a label for it and the counts only. + 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 (_attr(x, "sAMAccountName") or "").lower() == held - and _dn_realm(str(x.entry_dn)) == domain - ] + kept = [x for x in entries if _holds_name(x, held) and _dn_realm(str(x.entry_dn)) == domain] if len(kept) < len(entries): - label = safe_name(name) - _warn_once( - f"kerberos-outside-realm:{label}", - "Kerberos lookup for %s kept %d of %d directory entries; the rest are outside " - "[auth].kerberos_realm's domain or do not hold the name (logged once per name)", - label, + 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), ) @@ -2210,17 +2219,21 @@ def _lookup_by_name( nothing wider: - the filter has no ``userPrincipalName`` arm. With one, a single entry holding the UPN - ``alice@`` under another name answered the ticket alone, so a renamed account - that kept its old UPN signed in for whoever was later given the old name; + ``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 refused before this, by :meth:`probe_principal`. + A name ending in ``$`` is NOT_FOUND without a search, and a malformed realm raises + (:func:`_kerberos_lookup_realm`). """ 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)}))" @@ -2480,18 +2493,9 @@ def probe_principal( 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") - if kerberos_realm is not None: - # Before the session opens, since neither needs the directory (BACKLOG #4846). The - # realm is checked again, as _configured_kerberos_realm does: an empty or malformed one - # is a configuration fault, never a reason to drop the binding. - try: - kerberos_realm = check_kerberos_realm(kerberos_realm) - except ValueError as exc: - raise LdapError(str(exc)) from exc - if username.endswith("$"): - # A machine account's name, and an interdomain trust account's, which is a - # person-category user that the filter alone would find. No person needs the $. - return DirectoryProbe(DirectoryAnswer.NOT_FOUND) + # 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 = ( @@ -2742,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/tests/test_kerberos_realm_binding.py b/tests/test_kerberos_realm_binding.py index eec6d4124d..f8e5c48530 100644 --- a/tests/test_kerberos_realm_binding.py +++ b/tests/test_kerberos_realm_binding.py @@ -3,13 +3,14 @@ """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: +(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`` resolved to the CHILD - domain's ``alice`` when the root held none, and was refused as ambiguous when both held one; +* 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``, - answered a ticket for ``alice``; -* a machine's ticket (``WS01$``) or a trust account's (``CHILD$``) looked up like a person's. + 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. @@ -172,8 +173,12 @@ def test_the_name_lookup_the_other_callers_keep_still_refuses_the_pair() -> None assert found.answer is DirectoryAnswer.AMBIGUOUS -def test_a_dropped_entry_is_logged_by_label_and_count(caplog: pytest.LogCaptureFixture) -> None: - with caplog.at_level("WARNING", logger="messagefoundry.auth.ldap"): +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() @@ -181,6 +186,7 @@ def test_a_dropped_entry_is_logged_by_label_and_count(caplog: pytest.LogCaptureF 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() @@ -227,6 +233,28 @@ def test_a_dollar_name_is_not_found_without_a_session(name: str) -> None: 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")])