fix(auth): prove the AD domain of a u:DOMAIN\name user bind

Auth-007's sAMAccountName match assumed the search base covers one AD
domain; across a forest (Global Catalog) it could accept another domain's
same-named account and return its groups. For a u:DOMAIN\name Who-am-I
answer the entry must now also be that domain's account: AD's
msDS-PrincipalName (objectSid-derived DOMAIN\name, read by a base search
through the new ILdapConnection.Read) must equal the answer where offered;
otherwise the name must have exactly one holder under SearchBase and it must
be the entry found. Three forest cases fail pre-fix; single-domain and
sAMAccountName-search compat cases pass both ways. README notes this and
Auth-009.

(scadaproj#50)

Claude-Session: https://claude.ai/code/session_01GT67AEHd2Acv1YPwGfXEoV
This commit is contained in:
Joseph Doherty
2026-11-09 15:18:46 -05:00
parent 9ec0da1b2c
commit b8d3fa2ba1
6 changed files with 281 additions and 11 deletions
@@ -19,6 +19,9 @@ internal sealed class FakeLdapConnection : ILdapConnection
private int? _firstBindResultCode;
private bool _throwOnSearch;
private string? _whoAmI;
private string? _principalName;
private bool _throwOnRead;
private readonly Dictionary<string, List<LdapSearchEntry>> _filterResults = new(StringComparer.Ordinal);
// ---- observation -----
@@ -123,6 +126,39 @@ internal sealed class FakeLdapConnection : ILdapConnection
return this;
}
/// <summary>
/// Scripts AD's constructed <c>msDS-PrincipalName</c> (<c>DOMAIN\name</c>) that a base
/// <see cref="Read"/> of any DN returns. Unscripted, <see cref="Read"/> returns the entry without it.
/// </summary>
public FakeLdapConnection WithPrincipalName(string value)
{
_principalName = value;
return this;
}
/// <summary>Throw <see cref="Novell.Directory.Ldap.LdapException"/> from <see cref="Read"/>.</summary>
public FakeLdapConnection ThrowOnRead()
{
_throwOnRead = true;
return this;
}
/// <summary>
/// Scripts the entries a <see cref="Search"/> with exactly <paramref name="filter"/> returns, each
/// carrying the given <c>sAMAccountName</c>. Other filters still return the
/// <see cref="WithUserEntry"/> entries.
/// </summary>
public FakeLdapConnection WithSearchResult(string filter, params (string Dn, string Sam)[] entries)
{
_filterResults[filter] = entries
.Select(e => new LdapSearchEntry(e.Dn, new Dictionary<string, IReadOnlyList<string>>(StringComparer.OrdinalIgnoreCase)
{
["sAMAccountName"] = new[] { e.Sam },
}))
.ToList();
return this;
}
/// <summary>Throw <see cref="Novell.Directory.Ldap.LdapException"/> from <see cref="Search"/> (unhealthy directory).</summary>
public FakeLdapConnection ThrowOnSearch()
{
@@ -205,7 +241,19 @@ internal sealed class FakeLdapConnection : ILdapConnection
if (_throwOnSearch)
throw new Novell.Directory.Ldap.LdapException(
"Search failed", Novell.Directory.Ldap.LdapException.Unavailable, searchBase);
return _scriptedEntries.AsReadOnly();
return _filterResults.TryGetValue(filter, out var scripted) ? scripted : _scriptedEntries.AsReadOnly();
}
public LdapSearchEntry? Read(string dn, IReadOnlyList<string> attributes)
{
Calls.Add($"read:{dn}");
if (_throwOnRead)
throw new Novell.Directory.Ldap.LdapException(
"Read failed", Novell.Directory.Ldap.LdapException.InsufficientAccessRights, dn);
var attrs = new Dictionary<string, IReadOnlyList<string>>(StringComparer.OrdinalIgnoreCase);
if (_principalName is not null)
attrs["msDS-PrincipalName"] = new[] { _principalName };
return new LdapSearchEntry(dn, attrs);
}
public string WhoAmI()
@@ -288,6 +288,95 @@ public class LdapAuthServiceUserBindTests
Assert.Equal(LdapAuthFailure.GroupLookupFailed, result.Failure);
}
// ---- scadaproj#50: an AD forest — the same sAMAccountName in two domains ----------------------
// A Global Catalog search base spans every domain in the forest. CORP\jsmith binds; the search
// (here on mail, so the filter is not sAMAccountName) finds OTHER\jsmith, whose sAMAccountName is
// also "jsmith". 0.4.4 compared sAMAccountName alone and returned OTHER\jsmith's groups.
private const string OtherDn = "CN=J Smith,OU=u,DC=other,DC=forest";
private const string CorpDn = "CN=John Smith,OU=u,DC=corp,DC=forest";
private static FakeLdapConnection ForestSearchFinding(string dn) => new FakeLdapConnection()
.WithWhoAmI(@"u:CORP\jsmith")
.WithUserEntry(dn, new[] { "CN=UG_Admins,OU=g,DC=other,DC=forest" }, "J Smith",
new Dictionary<string, string[]> { ["sAMAccountName"] = new[] { "jsmith" }, ["mail"] = new[] { "jsmith" } });
private static LdapOptions ForestOpts() => Opts() with { UserNameAttribute = "mail", SearchBase = "DC=forest" };
[Fact]
public async Task Forest_PrincipalNameInAnotherDomain_FailsClosed()
{
var fake = ForestSearchFinding(OtherDn).WithPrincipalName(@"OTHER\jsmith");
var result = await Login(new LdapAuthService(ForestOpts(), new SequenceLdapConnectionFactory(fake)), "jsmith");
Assert.Equal(LdapAuthFailure.GroupLookupFailed, result.Failure);
Assert.Empty(result.Groups);
Assert.Contains("read:" + OtherDn, fake.Calls);
}
[Fact]
public async Task Forest_PrincipalNameInTheBoundDomain_Succeeds()
{
var fake = ForestSearchFinding(CorpDn).WithPrincipalName(@"corp\JSMITH");
var result = await Login(new LdapAuthService(ForestOpts(), new SequenceLdapConnectionFactory(fake)), "jsmith");
Assert.True(result.Succeeded);
}
[Fact]
public async Task Forest_NoPrincipalName_AndTheNameIsHeldInTwoDomains_FailsClosed()
{
// The directory offers no msDS-PrincipalName, so which jsmith bound cannot be proven; with two
// holders of the name in scope the sign-in is refused rather than guessed.
var fake = ForestSearchFinding(OtherDn)
.WithSearchResult("(sAMAccountName=jsmith)", (CorpDn, "jsmith"), (OtherDn, "jsmith"));
var result = await Login(new LdapAuthService(ForestOpts(), new SequenceLdapConnectionFactory(fake)), "jsmith");
Assert.Equal(LdapAuthFailure.GroupLookupFailed, result.Failure);
}
[Fact]
public async Task Forest_NoPrincipalName_AndTheReadFails_StillFallsBackToTheUniquenessCheck()
{
var fake = ForestSearchFinding(OtherDn).ThrowOnRead()
.WithSearchResult("(sAMAccountName=jsmith)", (CorpDn, "jsmith"), (OtherDn, "jsmith"));
var result = await Login(new LdapAuthService(ForestOpts(), new SequenceLdapConnectionFactory(fake)), "jsmith");
Assert.Equal(LdapAuthFailure.GroupLookupFailed, result.Failure);
}
[Fact]
public async Task SingleDomain_NoPrincipalName_UniqueName_Succeeds()
{
// Compatibility: a single-domain directory without msDS-PrincipalName still signs in — the
// name has exactly one holder in scope, and it is the entry found.
var fake = ForestSearchFinding(CorpDn).WithSearchResult("(sAMAccountName=jsmith)", (CorpDn, "jsmith"));
var result = await Login(new LdapAuthService(ForestOpts(), new SequenceLdapConnectionFactory(fake)), "jsmith");
Assert.True(result.Succeeded);
}
[Fact]
public async Task SamAccountNameSearch_ForTheBoundName_NeedsNoSecondSearch()
{
// When the user search itself was (sAMAccountName=<the bound name>) and found exactly one
// entry, the name is already proven unique in scope.
var fake = new FakeLdapConnection()
.WithWhoAmI(@"u:CORP\jdoe")
.WithUserEntry(JaneDn, new[] { "CN=UG_A,OU=g,DC=x" }, "Jane Doe",
new Dictionary<string, string[]> { ["sAMAccountName"] = new[] { "jdoe" } });
var result = await Login(new LdapAuthService(Opts(), new SequenceLdapConnectionFactory(fake)), "jdoe");
Assert.True(result.Succeeded);
Assert.Single(fake.Calls, c => c.StartsWith("search:", StringComparison.Ordinal));
}
[Fact]
public async Task WhoAmIDn_NamingAnotherEntry_FailsClosed()
{