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:
@@ -324,9 +324,23 @@ public sealed class LdapAuthService : ILdapAuthService
|
||||
/// wrong password AND for unknown, locked, disabled or expired accounts) is the user's failure
|
||||
/// and final; any other bind error means this endpoint gave no answer, so the walk moves on.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The bind name (from <see cref="LdapOptions.UserBindTemplate"/>) and the search filter
|
||||
/// (<see cref="LdapOptions.UserNameAttribute"/>) are resolved by two different directory
|
||||
/// lookups, so they can name two different accounts — e.g. a UPN bind that AD resolves to the
|
||||
/// account whose explicit <c>userPrincipalName</c> is <c>jsmith@corp</c> while the search finds
|
||||
/// the account whose <c>sAMAccountName</c> is <c>jsmith</c> (Auth-007). The entry is therefore
|
||||
/// only accepted when it is provably the account that bound: see <see cref="ResolveBoundIdentity"/>
|
||||
/// and <see cref="IsBoundAccount"/>. Anything else is <see cref="LdapAuthFailure.GroupLookupFailed"/>.
|
||||
/// </remarks>
|
||||
private LdapAuthResult CompleteAsUser(ZB.MOM.WW.Auth.Ldap.Internal.ILdapConnection conn, string username, string password)
|
||||
{
|
||||
var bindName = _options.UserBindTemplate.Replace("{0}", username, StringComparison.Ordinal);
|
||||
var dnTemplate = IsDnTemplate(_options.UserBindTemplate);
|
||||
|
||||
// A DN template splices the name into a DN, so the name is RFC 4514-escaped: unescaped, a
|
||||
// name like "x,ou=other" would bind a DN of the caller's choosing.
|
||||
var bindName = _options.UserBindTemplate.Replace(
|
||||
"{0}", dnTemplate ? LdapEscaping.Dn(username) : username, StringComparison.Ordinal);
|
||||
try
|
||||
{
|
||||
conn.Bind(bindName, password);
|
||||
@@ -340,17 +354,114 @@ public sealed class LdapAuthService : ILdapAuthService
|
||||
throw new StageFailure(LdapAuthFailure.ServiceAccountBindFailed, "user-bind");
|
||||
}
|
||||
|
||||
var bound = ResolveBoundIdentity(conn, bindName, dnTemplate);
|
||||
if (bound is null)
|
||||
{
|
||||
_logger?.LogWarning(
|
||||
"LDAP user bind succeeded but the bound identity could not be established (no RFC 4532 " +
|
||||
"Who-am-I answer and UserBindTemplate is not a DN); refusing the sign-in.");
|
||||
return LdapAuthResult.Fail(LdapAuthFailure.GroupLookupFailed);
|
||||
}
|
||||
|
||||
// After a good bind, anything but exactly one readable entry is a failure to establish the
|
||||
// user's groups — never a success, and never UserNotFound (the directory just accepted them).
|
||||
var entries = SearchUser(conn, username);
|
||||
var entries = SearchUser(conn, username, bound.AccountName is null ? null : SamAccountNameAttribute);
|
||||
if (entries.Count != 1)
|
||||
return LdapAuthResult.Fail(LdapAuthFailure.GroupLookupFailed);
|
||||
|
||||
if (!IsBoundAccount(entries[0], bound))
|
||||
{
|
||||
_logger?.LogWarning(
|
||||
"LDAP user bind authenticated {BoundIdentity} but the entry found for the typed name is " +
|
||||
"{EntryDn}; refusing the sign-in rather than returning another account's groups.",
|
||||
bound, entries[0].Dn);
|
||||
return LdapAuthResult.Fail(LdapAuthFailure.GroupLookupFailed);
|
||||
}
|
||||
|
||||
return SucceedFromEntry(entries[0], username);
|
||||
}
|
||||
|
||||
/// <summary>The AD attribute that an RFC 4532 <c>u:DOMAIN\name</c> authorization identity names.</summary>
|
||||
private const string SamAccountNameAttribute = "sAMAccountName";
|
||||
|
||||
/// <summary>
|
||||
/// The account a user bind authenticated: either its DN, or (AD's Who-am-I form) its
|
||||
/// <c>sAMAccountName</c>. Exactly one member is set.
|
||||
/// </summary>
|
||||
private sealed record BoundIdentity(string? Dn, string? AccountName)
|
||||
{
|
||||
public override string ToString() => Dn is not null ? $"dn:{Dn}" : $"u:{AccountName}";
|
||||
}
|
||||
|
||||
/// <summary>A template is a DN template when it contains an attribute assertion (<c>=</c>); UPN and down-level forms never do.</summary>
|
||||
private static bool IsDnTemplate(string template) => template.Contains('=', StringComparison.Ordinal);
|
||||
|
||||
/// <summary>
|
||||
/// Establishes which account the bind authenticated. The directory's own answer wins: RFC 4532
|
||||
/// Who-am-I (<c>dn:<dn></c>, or AD's <c>u:DOMAIN\name</c>). Without one — the server does
|
||||
/// not support the operation (GLAuth), or answers empty — a DN template is still provable,
|
||||
/// because the directory accepted exactly that DN; a UPN or down-level template is not, so the
|
||||
/// result is <see langword="null"/> and the sign-in fails closed.
|
||||
/// </summary>
|
||||
private static BoundIdentity? ResolveBoundIdentity(
|
||||
ZB.MOM.WW.Auth.Ldap.Internal.ILdapConnection conn, string bindName, bool dnTemplate)
|
||||
{
|
||||
string authzId;
|
||||
try
|
||||
{
|
||||
authzId = conn.WhoAmI()?.Trim() ?? "";
|
||||
}
|
||||
catch (LdapException)
|
||||
{
|
||||
// Unsupported (protocol error / unwilling) or a transport fault. Either way there is no
|
||||
// answer; a dead connection will fail the following search, which is system-side.
|
||||
authzId = "";
|
||||
}
|
||||
|
||||
if (authzId.StartsWith("dn:", StringComparison.OrdinalIgnoreCase) && authzId.Length > 3)
|
||||
return new BoundIdentity(authzId[3..].Trim(), null);
|
||||
|
||||
if (authzId.StartsWith("u:", StringComparison.OrdinalIgnoreCase) && authzId.Length > 2)
|
||||
{
|
||||
var account = authzId[2..].Trim();
|
||||
var slash = account.LastIndexOf('\\');
|
||||
if (slash >= 0)
|
||||
account = account[(slash + 1)..];
|
||||
if (account.Length > 0)
|
||||
return new BoundIdentity(null, account);
|
||||
}
|
||||
|
||||
return dnTemplate ? new BoundIdentity(bindName, null) : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <see langword="true"/> only when <paramref name="entry"/> is the account that bound: its DN
|
||||
/// equals the bound DN (RFC 4514 <c>distinguishedNameMatch</c>, case- and space-insensitive), or
|
||||
/// its <c>sAMAccountName</c> equals the Who-am-I account name (case-insensitive, as AD compares it).
|
||||
/// </summary>
|
||||
private static bool IsBoundAccount(LdapSearchEntry entry, BoundIdentity bound)
|
||||
{
|
||||
if (bound.Dn is not null)
|
||||
{
|
||||
try
|
||||
{
|
||||
return LdapDn.Equals(entry.Dn, bound.Dn);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// An unparseable DN on either side cannot be proven equal.
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return entry.Attributes.TryGetValue(SamAccountNameAttribute, out var values)
|
||||
&& values.Count == 1
|
||||
&& string.Equals(values[0], bound.AccountName, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>Step 7: search for the user entry; a search fault is system-side.</summary>
|
||||
private IReadOnlyList<LdapSearchEntry> SearchUser(ZB.MOM.WW.Auth.Ldap.Internal.ILdapConnection conn, string username)
|
||||
private IReadOnlyList<LdapSearchEntry> SearchUser(
|
||||
ZB.MOM.WW.Auth.Ldap.Internal.ILdapConnection conn, string username, string? extraAttribute = null)
|
||||
{
|
||||
// A search failure is infrastructure (directory unreachable / unhealthy) — system-side.
|
||||
// NOTE: the LdapAuthFailure enum has no DirectoryUnavailable value, so a failed search maps
|
||||
@@ -359,7 +470,7 @@ public sealed class LdapAuthService : ILdapAuthService
|
||||
try
|
||||
{
|
||||
var filter = $"({_options.UserNameAttribute}={LdapEscaping.Filter(username)})";
|
||||
return conn.Search(_options.SearchBase, filter, BuildSearchAttributes());
|
||||
return conn.Search(_options.SearchBase, filter, BuildSearchAttributes(extraAttribute));
|
||||
}
|
||||
catch (LdapException)
|
||||
{
|
||||
@@ -411,17 +522,18 @@ public sealed class LdapAuthService : ILdapAuthService
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the distinct attribute list requested from the directory: display name, groups and
|
||||
/// the username attribute (read back as the canonical username). They are de-duplicated,
|
||||
/// Builds the distinct attribute list requested from the directory: display name, groups,
|
||||
/// the username attribute (read back as the canonical username) and, when the user-bind
|
||||
/// identity check needs it, <paramref name="extraAttribute"/>. They are de-duplicated,
|
||||
/// case-insensitively, so we never request the same attribute twice when an operator
|
||||
/// configures two of them to the same value.
|
||||
/// </summary>
|
||||
private IReadOnlyList<string> BuildSearchAttributes()
|
||||
private IReadOnlyList<string> BuildSearchAttributes(string? extraAttribute = null)
|
||||
{
|
||||
var attributes = new List<string>(3);
|
||||
foreach (var name in new[] { _options.DisplayNameAttribute, _options.GroupAttribute, _options.UserNameAttribute })
|
||||
var attributes = new List<string>(4);
|
||||
foreach (var name in new[] { _options.DisplayNameAttribute, _options.GroupAttribute, _options.UserNameAttribute, extraAttribute })
|
||||
{
|
||||
if (!attributes.Contains(name, StringComparer.OrdinalIgnoreCase))
|
||||
if (name is not null && !attributes.Contains(name, StringComparer.OrdinalIgnoreCase))
|
||||
attributes.Add(name);
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user