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:
@@ -45,10 +45,17 @@ public sealed record LdapOptions
|
||||
/// normalised login name. Must contain <c>{0}</c> exactly once.
|
||||
/// <para>
|
||||
/// Prefer the down-level form <c>EXAMPLE\{0}</c>: it maps exactly to the <c>sAMAccountName</c> the
|
||||
/// group search uses, so the account that binds is the account whose groups are read. A UPN
|
||||
/// template (<c>{0}@example.com</c>) is only correct where every account's UPN prefix equals its
|
||||
/// <c>sAMAccountName</c> — AD resolves a UPN bind against the explicit <c>userPrincipalName</c>, so
|
||||
/// a mismatch can fail sign-in or bind a different account than the one whose groups are read.
|
||||
/// group search uses. A UPN template (<c>{0}@example.com</c>) only signs in accounts whose UPN
|
||||
/// prefix equals their <c>sAMAccountName</c> — AD resolves a UPN bind against the explicit
|
||||
/// <c>userPrincipalName</c>, so it can bind a different account than the one the search finds.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Since 0.4.4 the service proves the entry it reads is the account that bound, and refuses the
|
||||
/// sign-in (<see cref="LdapAuthFailure.GroupLookupFailed"/>) otherwise. It asks the directory
|
||||
/// (RFC 4532 "Who am I?") and compares the answer with the entry's DN or, for AD's
|
||||
/// <c>u:DOMAIN\name</c> answer, its <c>sAMAccountName</c>. A server without Who-am-I (e.g. GLAuth)
|
||||
/// is only supported with a DN template (containing <c>=</c>), which must produce the entry's DN
|
||||
/// exactly as the search reports it; <c>{0}</c> is RFC 4514-escaped in a DN template.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public string UserBindTemplate { get; init; } = "";
|
||||
|
||||
@@ -45,6 +45,14 @@ internal interface ILdapConnection : IDisposable
|
||||
|
||||
/// <summary>Executes a subtree search and returns all matching entries.</summary>
|
||||
IReadOnlyList<LdapSearchEntry> Search(string searchBase, string filter, IReadOnlyList<string> attributes);
|
||||
|
||||
/// <summary>
|
||||
/// RFC 4532 "Who am I?": the authorization identity the directory associates with the current
|
||||
/// bind, as the server sends it (<c>dn:<dn></c>, <c>u:DOMAIN\name</c>, or empty for an
|
||||
/// anonymous bind). Throws <c>LdapException</c> when the server does not support the operation
|
||||
/// (GLAuth answers protocol error 2).
|
||||
/// </summary>
|
||||
string WhoAmI();
|
||||
}
|
||||
|
||||
/// <summary>Factory that produces <see cref="ILdapConnection"/> instances.</summary>
|
||||
|
||||
@@ -102,6 +102,19 @@ internal sealed class NovellLdapConnection : ILdapConnection
|
||||
return ReadEntries(results);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public string WhoAmI()
|
||||
{
|
||||
// ExtendedOperation throws LdapException on a non-success result (e.g. protocol error 2
|
||||
// from a server without RFC 4532 support), which the caller treats as "no answer".
|
||||
var response = _conn.ExtendedOperation(new LdapWhoAmIOperation());
|
||||
if (response is LdapWhoAmIResponse whoAmI)
|
||||
return whoAmI.AuthzId ?? "";
|
||||
|
||||
var value = response.Value;
|
||||
return value is null ? "" : System.Text.Encoding.UTF8.GetString(value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Drains a result set into entries, <b>skipping continuation referrals</b>.
|
||||
/// </summary>
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
@@ -74,8 +74,8 @@ public sealed class LdapOptionsValidator : IValidateOptions<LdapOptions>
|
||||
{
|
||||
return ValidateOptionsResult.Fail(
|
||||
$"{nameof(LdapOptions.UserBindTemplate)} must contain {{0}} exactly once when " +
|
||||
$"{nameof(LdapOptions.BindMode)} is {nameof(LdapBindMode.User)} — e.g. \"{{0}}@example.com\" " +
|
||||
"or \"EXAMPLE\\{0}\".");
|
||||
$"{nameof(LdapOptions.BindMode)} is {nameof(LdapBindMode.User)} — e.g. \"EXAMPLE\\{{0}}\" " +
|
||||
"(preferred) or \"{0}@example.com\".");
|
||||
}
|
||||
}
|
||||
else if (string.IsNullOrWhiteSpace(options.ServiceAccountDn))
|
||||
|
||||
Reference in New Issue
Block a user