fix(auth): user bind proves the bound account is the entry whose groups it returns (scadaproj#40)

BindMode=User bound as UserBindTemplate({0}) and then returned the groups of
whatever entry (UserNameAttribute={0}) found - two directory lookups that can
name two accounts (Auth-007). Reproduced live against GLAuth: mallory bound as
herself and signed in with boss's Admins group.

After the bind the service now asks RFC 4532 Who-am-I and requires the entry
to be that account (dn: -> DN match; AD u:DOMAIN\name -> sAMAccountName match).
Without a Who-am-I answer only a DN template is provable (bind DN must equal
the entry DN); anything else fails closed as GroupLookupFailed. {0} is
RFC 4514-escaped in DN templates; validator message leads with EXAMPLE\{0}.

Auth 0.4.3 -> 0.4.4 (unpublished).

Claude-Session: https://claude.ai/code/session_01GT67AEHd2Acv1YPwGfXEoV
This commit is contained in:
Joseph Doherty
2026-11-09 14:46:25 -05:00
parent 5f5d684c44
commit d549a782fd
15 changed files with 530 additions and 31 deletions
@@ -18,6 +18,7 @@ internal sealed class FakeLdapConnection : ILdapConnection
private bool _throwOnUserBind;
private int? _firstBindResultCode;
private bool _throwOnSearch;
private string? _whoAmI;
// ---- observation -----
@@ -112,6 +113,16 @@ internal sealed class FakeLdapConnection : ILdapConnection
return this;
}
/// <summary>
/// Scripts the RFC 4532 Who-am-I answer (e.g. <c>dn:CN=Jane,DC=x</c> or <c>u:CORP\jane</c>).
/// Unscripted, <see cref="WhoAmI"/> throws protocol error 2 — what GLAuth answers.
/// </summary>
public FakeLdapConnection WithWhoAmI(string authzId)
{
_whoAmI = authzId;
return this;
}
/// <summary>Throw <see cref="Novell.Directory.Ldap.LdapException"/> from <see cref="Search"/> (unhealthy directory).</summary>
public FakeLdapConnection ThrowOnSearch()
{
@@ -197,6 +208,13 @@ internal sealed class FakeLdapConnection : ILdapConnection
return _scriptedEntries.AsReadOnly();
}
public string WhoAmI()
{
Calls.Add("whoami");
return _whoAmI ?? throw new Novell.Directory.Ldap.LdapException(
"Protocol Error", Novell.Directory.Ldap.LdapException.ProtocolError, null);
}
public void Dispose() { /* nothing to clean up */ }
}
@@ -0,0 +1,85 @@
// Live user-bind identity test (Auth-007, scadaproj#40) — opt-in only.
//
// Start the throwaway fixture (NOT the shared rig — it needs users that can search):
// cd tests/ZB.MOM.WW.Auth.Ldap.Tests/Integration/glauth-userbind && docker compose up -d
// Run:
// ZB_LDAP_USERBIND_IT=1 dotnet test tests/ZB.MOM.WW.Auth.Ldap.Tests \
// --filter "FullyQualifiedName~GLAuthUserBindIdentityTests"
// Optional: ZB_LDAP_USERBIND_SERVER (default localhost), ZB_LDAP_USERBIND_PORT (default 3897).
//
// GLAuth does not implement RFC 4532 Who-am-I (it answers protocol error 2), so these tests also
// prove the DN-template fallback path against a real directory.
using System.Net.Sockets;
using ZB.MOM.WW.Auth.Abstractions.Ldap;
namespace ZB.MOM.WW.Auth.Ldap.Tests.Integration;
public sealed class GLAuthUserBindIdentityTests
{
private static LdapOptions Options(string template, string userNameAttribute)
{
var server = Environment.GetEnvironmentVariable("ZB_LDAP_USERBIND_SERVER") ?? "localhost";
var port = int.TryParse(Environment.GetEnvironmentVariable("ZB_LDAP_USERBIND_PORT"), out var p) ? p : 3897;
try
{
using var tcp = new TcpClient();
if (!tcp.ConnectAsync(server, port).Wait(TimeSpan.FromSeconds(3)))
Skip.If(true, $"GLAuth fixture not reachable at {server}:{port}.");
}
catch (Exception ex)
{
Skip.If(true, $"GLAuth fixture not reachable at {server}:{port}: {ex.Message}");
}
return new LdapOptions
{
Server = server,
Port = port,
Transport = LdapTransport.None,
AllowInsecure = true,
SearchBase = "dc=zb,dc=local",
BindMode = LdapBindMode.User,
UserBindTemplate = template,
UserNameAttribute = userNameAttribute,
GroupAttribute = "memberOf",
ConnectionTimeoutMs = 3000,
};
}
/// <summary>
/// mallory binds with her own password; <c>(mail=mallory)</c> finds the <c>boss</c> entry, which
/// is in Admins. Before the fix this signed mallory in with boss's groups.
/// </summary>
[SkippableFact]
public async Task BoundAccount_DifferentFromTheSearchedEntry_IsRefused()
{
Skip.IfNot(Environment.GetEnvironmentVariable("ZB_LDAP_USERBIND_IT") == "1",
"Set ZB_LDAP_USERBIND_IT=1 and start Integration/glauth-userbind to run.");
var svc = new LdapAuthService(Options("cn={0},ou=Users,dc=zb,dc=local", "mail"));
var result = await svc.AuthenticateAsync("mallory", "password", CancellationToken.None);
Assert.False(result.Succeeded, $"signed in as {result.Username} with [{string.Join(",", result.Groups)}]");
Assert.Equal(LdapAuthFailure.GroupLookupFailed, result.Failure);
Assert.DoesNotContain("Admins", result.Groups);
}
/// <summary>Positive control: the same mechanism admits a user whose bind DN is the entry's DN.</summary>
[SkippableFact]
public async Task BoundAccount_SameAsTheSearchedEntry_Succeeds()
{
Skip.IfNot(Environment.GetEnvironmentVariable("ZB_LDAP_USERBIND_IT") == "1",
"Set ZB_LDAP_USERBIND_IT=1 and start Integration/glauth-userbind to run.");
// GLAuth reports search DNs as cn=<user>,ou=<group>,ou=users,<base>; it also accepts that
// form as a bind DN, so this template binds the exact DN the search returns.
var svc = new LdapAuthService(Options("cn={0},ou=Users,ou=users,dc=zb,dc=local", "cn"));
var result = await svc.AuthenticateAsync("boss", "password", CancellationToken.None);
Assert.True(result.Succeeded, $"failed: {result.Failure}");
Assert.Equal("boss", result.Username);
Assert.Contains("Admins", result.Groups);
}
}
@@ -0,0 +1,49 @@
# GLAuth fixture for the user-bind identity test (Auth-007, scadaproj#40).
# Start: docker compose up -d (listens on localhost:3897)
# All passwords are "password" (sha256 below).
#
# mallory binds as herself (cn=mallory,ou=Users,...). The admin entry carries mail=mallory,
# so with UserNameAttribute=mail a search for the typed name "mallory" finds the ADMIN — the
# account that bound and the account searched for differ. The library must refuse.
[ldap]
enabled = true
listen = "0.0.0.0:3893"
[ldaps]
enabled = false
[backend]
datastore = "config"
baseDN = "dc=zb,dc=local"
[behaviors]
LimitFailedBinds = false
[[groups]]
name = "Users"
gidnumber = 6001
[[groups]]
name = "Admins"
gidnumber = 6002
[[users]]
name = "mallory"
mail = "mallory-real@zb.local"
uidnumber = 6101
primarygroup = 6001
passsha256 = "5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8"
[[users.capabilities]]
action = "search"
object = "*"
[[users]]
name = "boss"
mail = "mallory"
uidnumber = 6102
primarygroup = 6001
othergroups = [6002]
passsha256 = "5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8"
[[users.capabilities]]
action = "search"
object = "*"
@@ -0,0 +1,10 @@
# Throwaway GLAuth for GLAuthUserBindIdentityTests (Auth-007). Not the shared rig.
name: zb-auth-userbind-it
services:
glauth:
image: glauth/glauth:latest
container_name: zb-auth-userbind-it
ports:
- "3897:3893"
volumes:
- ./config.toml:/app/config/config.cfg:ro
@@ -27,8 +27,11 @@ public class LdapAuthServiceUserBindTests
FallbackServers = fallbacks,
};
private const string JaneDn = "CN=Jane Doe,OU=u,DC=x";
private static FakeLdapConnection Jane() => new FakeLdapConnection()
.WithUserEntry("CN=Jane Doe,OU=u,DC=x", new[] { "CN=UG_A,OU=g,DC=x", "CN=UG_B,OU=g,DC=x" }, "Jane Doe");
.WithWhoAmI("dn:" + JaneDn)
.WithUserEntry(JaneDn, new[] { "CN=UG_A,OU=g,DC=x", "CN=UG_B,OU=g,DC=x" }, "Jane Doe");
private static Task<LdapAuthResult> Login(LdapAuthService svc, string user, string pw = "pw") =>
svc.AuthenticateAsync(user, pw, CancellationToken.None);
@@ -44,7 +47,7 @@ public class LdapAuthServiceUserBindTests
Assert.Equal("Jane Doe", result.DisplayName);
Assert.Equal(new[] { "UG_A", "UG_B" }, result.Groups);
var conn = Assert.Single(factory.Created);
Assert.Equal(new[] { "connect", "bind:jdoe@corp.test", "search:(sAMAccountName=jdoe)" }, conn.Calls);
Assert.Equal(new[] { "connect", "bind:jdoe@corp.test", "whoami", "search:(sAMAccountName=jdoe)" }, conn.Calls);
Assert.Equal(new[] { "jdoe@corp.test" }, conn.BoundDns);
}
@@ -153,7 +156,7 @@ public class LdapAuthServiceUserBindTests
[Fact]
public async Task NoEntryAfterAGoodBind_IsGroupLookupFailed()
{
var factory = new SequenceLdapConnectionFactory(new FakeLdapConnection().WithNoMatch());
var factory = new SequenceLdapConnectionFactory(new FakeLdapConnection().WithWhoAmI("dn:" + JaneDn).WithNoMatch());
var result = await Login(new LdapAuthService(Opts("dc2"), factory), "jdoe");
Assert.Equal(LdapAuthFailure.GroupLookupFailed, result.Failure);
@@ -163,7 +166,7 @@ public class LdapAuthServiceUserBindTests
[Fact]
public async Task TwoEntriesAfterAGoodBind_IsGroupLookupFailed()
{
var factory = new SequenceLdapConnectionFactory(new FakeLdapConnection().WithDuplicateMatch());
var factory = new SequenceLdapConnectionFactory(new FakeLdapConnection().WithWhoAmI("dn:cn=dup1,dc=x").WithDuplicateMatch());
var result = await Login(new LdapAuthService(Opts(), factory), "jdoe");
Assert.Equal(LdapAuthFailure.GroupLookupFailed, result.Failure);
@@ -173,7 +176,7 @@ public class LdapAuthServiceUserBindTests
public async Task NoGroups_IsGroupLookupFailed()
{
var factory = new SequenceLdapConnectionFactory(
new FakeLdapConnection().WithUserEntry("CN=Jane,DC=x", Array.Empty<string>(), "Jane"));
new FakeLdapConnection().WithWhoAmI("dn:CN=Jane,DC=x").WithUserEntry("CN=Jane,DC=x", Array.Empty<string>(), "Jane"));
var result = await Login(new LdapAuthService(Opts(), factory), "jdoe");
Assert.Equal(LdapAuthFailure.GroupLookupFailed, result.Failure);
@@ -182,7 +185,7 @@ public class LdapAuthServiceUserBindTests
[Fact]
public async Task Username_IsCanonicalisedFromTheEntry_NotTheTypedCase()
{
var factory = new SequenceLdapConnectionFactory(new FakeLdapConnection().WithUserEntry(
var factory = new SequenceLdapConnectionFactory(new FakeLdapConnection().WithWhoAmI(@"u:NAM\jdoe").WithUserEntry(
"CN=Jane Doe,OU=u,DC=x", new[] { "CN=UG_A,OU=g,DC=x" }, "Jane Doe",
new Dictionary<string, string[]> { ["sAMAccountName"] = new[] { "jdoe" } }));
var result = await Login(new LdapAuthService(Opts(), factory), @"NAM\JDOE");
@@ -219,4 +222,168 @@ public class LdapAuthServiceUserBindTests
Assert.Equal(new[] { "SAMACCOUNTNAME", "memberOf" }, factory.Created[0].SearchAttributes);
}
// ---- Auth-007 (scadaproj#40): the entry whose groups are returned must be the account that bound ----
/// <summary>
/// The review's scenario: a UPN bind for <c>jsmith</c> is resolved by AD to Mallory (explicit UPN
/// <c>jsmith@corp.test</c>, sAMAccountName <c>jsmith2</c>), while <c>(sAMAccountName=jsmith)</c>
/// finds the admin. Before the fix this returned the admin's groups to Mallory.
/// </summary>
[Fact]
public async Task UpnBind_ResolvedToAnotherAccount_DoesNotReturnTheSearchedEntrysGroups()
{
var fake = new FakeLdapConnection()
.WithWhoAmI(@"u:CORP\jsmith2")
.WithUserEntry("CN=Admin Smith,OU=u,DC=x", new[] { "CN=UG_Admins,OU=g,DC=x" }, "Admin Smith",
new Dictionary<string, string[]> { ["sAMAccountName"] = new[] { "jsmith" } });
var factory = new SequenceLdapConnectionFactory(fake);
var result = await Login(new LdapAuthService(Opts(), factory), "jsmith", "mallorys-own-password");
Assert.False(result.Succeeded);
Assert.Equal(LdapAuthFailure.GroupLookupFailed, result.Failure);
Assert.Empty(result.Groups);
Assert.Equal(new[] { "jsmith@corp.test" }, fake.BoundDns);
}
[Fact]
public async Task WhoAmIAccountName_MatchingTheEntry_Succeeds_AndRequestsSamAccountName()
{
var fake = new FakeLdapConnection()
.WithWhoAmI(@"u:CORP\JSmith")
.WithUserEntry("CN=John Smith,OU=u,DC=x", new[] { "CN=UG_A,OU=g,DC=x" }, "John Smith",
new Dictionary<string, string[]> { ["sAMAccountName"] = new[] { "jsmith" } });
var factory = new SequenceLdapConnectionFactory(fake);
var svc = new LdapAuthService(Opts() with { UserNameAttribute = "cn" }, factory);
var result = await Login(svc, "John Smith");
Assert.True(result.Succeeded);
Assert.Contains("sAMAccountName", fake.SearchAttributes!);
}
[Fact]
public async Task WhoAmIAccountName_WithoutDomain_IsAccepted()
{
var fake = new FakeLdapConnection()
.WithWhoAmI("u: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);
}
[Fact]
public async Task WhoAmIAccountName_EntryWithoutSamAccountName_FailsClosed()
{
var fake = new FakeLdapConnection()
.WithWhoAmI(@"u:CORP\jdoe")
.WithUserEntry(JaneDn, new[] { "CN=UG_A,OU=g,DC=x" }, "Jane Doe");
var result = await Login(new LdapAuthService(Opts(), new SequenceLdapConnectionFactory(fake)), "jdoe");
Assert.Equal(LdapAuthFailure.GroupLookupFailed, result.Failure);
}
[Fact]
public async Task WhoAmIDn_NamingAnotherEntry_FailsClosed()
{
var fake = new FakeLdapConnection()
.WithWhoAmI("dn:CN=Mallory,OU=u,DC=x")
.WithUserEntry("CN=Admin Smith,OU=u,DC=x", new[] { "CN=UG_Admins,OU=g,DC=x" }, "Admin Smith");
var result = await Login(new LdapAuthService(Opts(), new SequenceLdapConnectionFactory(fake)), "jsmith");
Assert.Equal(LdapAuthFailure.GroupLookupFailed, result.Failure);
Assert.Empty(result.Groups);
}
[Fact]
public async Task WhoAmIDn_IsComparedAsADn_NotAsAString()
{
var fake = new FakeLdapConnection()
.WithWhoAmI("dn:cn=jane doe, ou=U, dc=X")
.WithUserEntry(JaneDn, new[] { "CN=UG_A,OU=g,DC=x" }, "Jane Doe");
var result = await Login(new LdapAuthService(Opts(), new SequenceLdapConnectionFactory(fake)), "jdoe");
Assert.True(result.Succeeded);
}
[Theory]
[InlineData(null)] // server does not support Who-am-I (GLAuth: protocol error 2)
[InlineData("")] // anonymous / empty answer
[InlineData("x:garbage")]
public async Task UpnTemplate_WithoutAWhoAmIAnswer_FailsClosed_WithoutSearching(string? whoAmI)
{
var fake = new FakeLdapConnection()
.WithUserEntry(JaneDn, new[] { "CN=UG_A,OU=g,DC=x" }, "Jane Doe");
if (whoAmI is not null)
fake.WithWhoAmI(whoAmI);
var result = await Login(new LdapAuthService(Opts(), new SequenceLdapConnectionFactory(fake)), "jdoe");
Assert.Equal(LdapAuthFailure.GroupLookupFailed, result.Failure);
Assert.DoesNotContain(fake.Calls, c => c.StartsWith("search:", StringComparison.Ordinal));
}
[Fact]
public async Task DownLevelTemplate_WithoutAWhoAmIAnswer_FailsClosed()
{
var fake = new FakeLdapConnection()
.WithUserEntry(JaneDn, new[] { "CN=UG_A,OU=g,DC=x" }, "Jane Doe");
var svc = new LdapAuthService(Opts() with { UserBindTemplate = @"CORP\{0}" }, new SequenceLdapConnectionFactory(fake));
var result = await Login(svc, "jdoe");
Assert.Equal(LdapAuthFailure.GroupLookupFailed, result.Failure);
}
[Fact]
public async Task DnTemplate_WithoutWhoAmI_AcceptsTheEntryAtTheBoundDn()
{
var fake = new FakeLdapConnection()
.WithUserEntry("cn=jdoe,ou=Users,dc=x", new[] { "cn=UG_A,ou=g,dc=x" }, "Jane Doe");
var svc = new LdapAuthService(
Opts() with { UserBindTemplate = "cn={0},ou=users,dc=x", UserNameAttribute = "cn" },
new SequenceLdapConnectionFactory(fake));
var result = await Login(svc, "jdoe");
Assert.True(result.Succeeded);
}
[Fact]
public async Task DnTemplate_WithoutWhoAmI_RefusesAnEntryAtAnotherDn()
{
// Mallory binds as cn=mallory with her own password; (mail=mallory) finds the admin.
var fake = new FakeLdapConnection()
.WithUserEntry("cn=admin,ou=Users,dc=x", new[] { "cn=UG_Admins,ou=g,dc=x" }, "Admin");
var svc = new LdapAuthService(
Opts() with { UserBindTemplate = "cn={0},ou=users,dc=x", UserNameAttribute = "mail" },
new SequenceLdapConnectionFactory(fake));
var result = await Login(svc, "mallory");
Assert.Equal(LdapAuthFailure.GroupLookupFailed, result.Failure);
Assert.Equal(new[] { "cn=mallory,ou=users,dc=x" }, fake.BoundDns);
}
[Fact]
public async Task DnTemplate_EscapesTheName_SoItCannotRewriteTheBindDn()
{
var fake = new FakeLdapConnection()
.WithUserEntry("cn=admin,ou=Admins,dc=x", new[] { "cn=UG_Admins,ou=g,dc=x" }, "Admin");
var svc = new LdapAuthService(
Opts() with { UserBindTemplate = "cn={0},ou=users,dc=x", UserNameAttribute = "cn" },
new SequenceLdapConnectionFactory(fake));
var result = await Login(svc, "admin,ou=Admins");
Assert.Equal(new[] { @"cn=admin\,ou=Admins,ou=users,dc=x" }, fake.BoundDns);
Assert.False(result.Succeeded);
}
}