Files
scadaproj/ZB.MOM.WW.Auth/src/ZB.MOM.WW.Auth.Ldap/LdapAuthService.cs
T
Joseph Doherty f5ef0efedd feat(auth): 0.5.0 passwordless group lookup ILdapGroupLookup (ScadaBridge#46)
ILdapGroupLookup.GetUserGroupsAsync(username, ct) re-reads a known user's
groups with the service account: same extraction, canonicalisation, endpoint
walk (FallbackServers), timeouts and TLS policy as AuthenticateAsync, via one
shared WalkEndpoints<T>. Explicit statuses: Found, UserNotFound, UserDisabled
(AD userAccountControl), AmbiguousUser, DirectoryUnavailable, NotSupported
(BindMode=User / no service account / foreign ILdapAuthService),
ProviderDisabled. AddZbLdapAuth registers it as the same singleton.

0.5.0 is the first published version carrying 0.4.2-0.4.4; scadaproj#51 was
live-verified against the NAM AD (24/24, identity check mutation-proven).

Claude-Session: https://claude.ai/code/session_01GT67ACmpMR7b9LGRPLijMi
2026-11-12 20:11:16 -05:00

831 lines
40 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using Microsoft.Extensions.Logging;
using Novell.Directory.Ldap;
using ZB.MOM.WW.Auth.Abstractions.Ldap;
using ZB.MOM.WW.Auth.Ldap.Internal;
namespace ZB.MOM.WW.Auth.Ldap;
/// <summary>
/// Authenticates a user against an LDAP directory using the bind-then-search idiom:
/// bind as the service account, search for the user entry, then re-bind as the user
/// to verify their password. Connection mechanics are delegated to an
/// <see cref="ILdapConnection"/> so the logic is unit-testable without a live server.
/// </summary>
/// <remarks>
/// <para>
/// Fully fail-closed: authentication never throws to the caller — every error, expected
/// or unexpected, is mapped to a structured <see cref="LdapAuthResult.Fail(LdapAuthFailure)"/>.
/// A success is only returned for a user that resolved to exactly one entry, whose password
/// verified, AND who has at least one group (zero groups is never admitted as success).
/// Service-account bind failures (<see cref="LdapAuthFailure.ServiceAccountBindFailed"/>) are
/// kept distinct from end-user bind failures (<see cref="LdapAuthFailure.BadCredentials"/>) so
/// a system misconfiguration is not mistaken for bad user input.
/// </para>
/// <para>
/// When <see cref="LdapOptions.FallbackServers"/> is non-empty the flow above runs against
/// an ordered endpoint list (primary first, then fallbacks in declared order) and moves on
/// to the next endpoint ONLY on a system-side failure — connect/TLS, service-account bind,
/// or search — i.e. when the endpoint gave no authoritative answer. Any answer from a healthy
/// directory (success, or a user-side failure such as
/// <see cref="LdapAuthFailure.BadCredentials"/> / <see cref="LdapAuthFailure.UserNotFound"/>)
/// is final and is never retried elsewhere: retrying a rejected password against a second DC
/// would turn one bad-password event into several, tripping account lockouts. Endpoint
/// preference is sticky — the last endpoint that answered is tried first next time — so a
/// primary outage costs its connect timeout once, not once per login.
/// </para>
/// <para>
/// The service is safe to share (it is registered as a singleton). The sticky index is the
/// only mutable state; concurrent logins may race on it, which is benign — the worst outcome
/// is one login starting at a stale endpoint and walking on.
/// </para>
/// <para>
/// With <c>BindMode = User</c> the service-account bind and the user re-bind are replaced by a
/// single bind as the user (<see cref="LdapOptions.UserBindTemplate"/>); see <see cref="CompleteAsUser"/>.
/// </para>
/// </remarks>
public sealed class LdapAuthService : ILdapAuthService, ILdapGroupLookup
{
private readonly LdapOptions _options;
private readonly ILdapConnectionFactory _connectionFactory;
private readonly IReadOnlyList<LdapEndpoint> _endpoints;
private readonly ILogger<LdapAuthService>? _logger;
/// <summary>
/// Index into <see cref="_endpoints"/> of the endpoint tried first. Written on any
/// authoritative answer from a non-preferred endpoint. Accessed via
/// <see cref="Volatile"/> only; benign races are accepted (see the type remarks).
/// </summary>
private int _preferredIndex;
/// <summary>
/// Production constructor: binds against a live directory via the real
/// Novell-backed connection factory. The TLS server-certificate validation policy
/// (<see cref="LdapOptions.ServerCertificateValidationCallback"/> or the
/// <see cref="LdapOptions.AllowInsecure"/> bypass) is carried into the factory so each
/// connection is built with it.
/// </summary>
/// <param name="options">The directory connection and search settings.</param>
/// <param name="logger">
/// Optional. When supplied, endpoint failover is made visible: a Warning per failed
/// endpoint hop and an Information line when the sticky preference moves. Omitting it
/// (the default) leaves the service silent — hosts without logging still work.
/// </param>
public LdapAuthService(LdapOptions options, ILogger<LdapAuthService>? logger = null)
: this(options, new NovellLdapConnectionFactory(
options.AllowInsecure, options.ServerCertificateValidationCallback), logger)
{
}
/// <summary>
/// Test/seam constructor: accepts an injected <see cref="ILdapConnectionFactory"/>
/// so the bind/search logic can be exercised without a live directory. Internal
/// because the connection seam is an implementation detail.
/// </summary>
internal LdapAuthService(
LdapOptions options,
ILdapConnectionFactory connectionFactory,
ILogger<LdapAuthService>? logger = null)
{
_options = options;
_connectionFactory = connectionFactory;
_logger = logger;
_endpoints = BuildEndpoints(options);
}
/// <summary>
/// Primary first, then fallbacks in declared order. The validator rejects malformed
/// entries at boot; unparseable entries are skipped defensively here so a service
/// constructed without options validation degrades to the parseable subset rather
/// than throwing from a constructor.
/// </summary>
private static IReadOnlyList<LdapEndpoint> BuildEndpoints(LdapOptions options)
{
var endpoints = new List<LdapEndpoint> { new(options.Server, options.Port) };
foreach (var entry in options.FallbackServers)
{
if (LdapEndpointParser.TryParse(entry, options.Port, out var endpoint, out _))
endpoints.Add(endpoint);
}
return endpoints;
}
/// <inheritdoc />
/// <remarks>
/// Fail-closed contract: this method never throws to the caller. Every stage of the
/// bind-then-search-then-bind flow is wrapped so that any error — expected or unexpected —
/// is mapped to a structured <see cref="LdapAuthResult.Fail(LdapAuthFailure)"/>. A
/// <c>Succeeded == true</c> result is only ever returned when the user resolved to exactly
/// one entry, their password verified, AND at least one group was extracted. With
/// <see cref="LdapOptions.FallbackServers"/> configured the flow may run against more than
/// one endpoint before answering — see the type-level remarks for the walk and its
/// system-side-only failover rule.
/// </remarks>
public Task<LdapAuthResult> AuthenticateAsync(string username, string password, CancellationToken ct)
{
// The Novell calls behind ILdapConnection are synchronous and blocking, so the token
// cannot interrupt an in-progress operation; it is only observed here at entry, before
// any work begins.
ct.ThrowIfCancellationRequested();
return Task.FromResult(Authenticate(username, password));
}
private LdapAuthResult Authenticate(string username, string password)
{
// 1. Feature gate: an explicitly disabled provider must never touch the network.
if (!_options.Enabled)
return LdapAuthResult.Fail(LdapAuthFailure.Disabled);
// 2. Reject a missing username before anything else — guarding here means a null
// username can't NRE into the catch-all and surface as a system-side failure.
if (string.IsNullOrWhiteSpace(username))
return LdapAuthResult.Fail(LdapAuthFailure.BadCredentials);
// 3. Normalise once, up front, so the same canonical value flows into the LDAP
// filter and the returned result (avoids two identities for one person).
username = username.Trim();
// 3b. An empty password must never reach the directory, in EITHER bind mode: AD answers a
// simple bind with an empty password as an UNAUTHENTICATED bind and reports success —
// the user bind (or the ServiceAccount-mode re-bind as the user's DN) would admit anyone.
// Refused here, before any network call, so no consumer depends on its own edge check.
if (string.IsNullOrEmpty(password))
return LdapAuthResult.Fail(LdapAuthFailure.BadCredentials);
// 3c. User-bind mode: reduce the name to the bare account name the bind template and the
// search filter share. (The returned username is canonicalised from the entry later.)
if (_options.BindMode == LdapBindMode.User
&& !LdapUserName.TryNormalize(username, _options.AcceptDomainQualifiedNames, out username))
{
return LdapAuthResult.Fail(LdapAuthFailure.BadCredentials);
}
// 4. Walk the endpoint list, preferred one first. A single-endpoint configuration
// (no FallbackServers) collapses to exactly one attempt — unchanged behaviour.
// ServiceAccountBindFailed is the (sole) system-side bucket: that endpoint gave no
// authoritative answer, so try the next one. Every other outcome — success, or a
// user-side failure like UserNotFound/BadCredentials — came from a healthy directory
// and is FINAL: re-asking a second DC about a rejected password would multiply one
// bad-password event into several against the account lockout policy.
// Seeded so an exhausted walk still returns the conservative system-side bucket
// even in the impossible case of an empty endpoint list.
return WalkEndpoints(
endpoint => AuthenticateAgainst(endpoint, username, password),
result => result.Failure == LdapAuthFailure.ServiceAccountBindFailed,
LdapAuthResult.Fail(LdapAuthFailure.ServiceAccountBindFailed));
}
/// <summary>
/// Runs <paramref name="attempt"/> against the endpoints, preferred one first, moving on only
/// while <paramref name="isSystemSide"/> says the endpoint gave no authoritative answer. The
/// first authoritative answer is returned and, if it came from a non-preferred endpoint, makes
/// that endpoint the sticky preference. An exhausted walk returns the last system-side result
/// (or <paramref name="exhausted"/>) and leaves the preference untouched: a total outage says
/// nothing about which endpoint to prefer once one recovers.
/// </summary>
private T WalkEndpoints<T>(Func<LdapEndpoint, T> attempt, Func<T, bool> isSystemSide, T exhausted)
{
var preferred = Volatile.Read(ref _preferredIndex);
if ((uint)preferred >= (uint)_endpoints.Count)
preferred = 0; // defensive: the list is immutable, but never index out of it
var last = exhausted;
foreach (var index in WalkOrder(_endpoints.Count, preferred))
{
var result = attempt(_endpoints[index]);
if (isSystemSide(result))
{
last = result;
continue;
}
// Sticky preference: any authoritative answer proves this endpoint healthy.
// Updating only on success would re-pay the dead primary's connect timeout on
// every mistyped password (or every refresh of a deleted user) for the whole outage.
if (index != preferred)
{
Volatile.Write(ref _preferredIndex, index);
_logger?.LogInformation("LDAP sticky preference moved to {Endpoint}.", _endpoints[index]);
}
return result;
}
return last;
}
/// <summary>Preferred endpoint first, then every other endpoint in declared order.</summary>
private static IEnumerable<int> WalkOrder(int count, int preferred)
{
yield return preferred;
for (var i = 0; i < count; i++)
{
if (i != preferred)
yield return i;
}
}
/// <summary>
/// Runs one full bind-then-search-then-bind attempt against a single endpoint on a fresh
/// connection. The fail-closed contract holds per attempt: this never throws, and it
/// returns <see cref="LdapAuthFailure.ServiceAccountBindFailed"/> for — and only for —
/// system-side faults, which is what the caller reads as "no authoritative answer, try
/// the next endpoint".
/// </summary>
private LdapAuthResult AuthenticateAgainst(LdapEndpoint endpoint, string username, string password)
{
// The whole flow runs inside an outer fail-closed guard: a StageFailure carries an
// already-mapped failure out of a stage, and any OTHER unexpected exception defaults to
// the most conservative system-side bucket. Either way the caller gets a structured result.
try
{
// A fresh connection per attempt: a Novell connection that has failed to connect
// or bind is not safely reusable against another host.
using var conn = _connectionFactory.Create();
// 5. Open the connection (transport/TLS handling lives in the adapter). The
// per-operation timeout (ConnectionTimeoutMs) is applied by the adapter here.
// A failure to connect/upgrade means this endpoint is unreachable — a
// system-side fault, not the user's, so map it to ServiceAccountBindFailed
// and let the caller try the next endpoint.
// NOTE: the LdapAuthFailure enum has no dedicated DirectoryUnavailable value;
// ServiceAccountBindFailed is the closest system-side bucket. A future
// Abstractions change could add DirectoryUnavailable to disambiguate.
ConnectTo(conn, endpoint);
return _options.BindMode == LdapBindMode.User
? CompleteAsUser(conn, username, password)
: CompleteWithServiceAccount(conn, username, password);
}
catch (StageFailure stage)
{
// A stage mapped its own failure; surface it as a structured result. Log at Warning
// so a silent failover — the failure mode this feature exists to survive — is
// visible in the host's log rather than only in a latency graph.
_logger?.LogWarning(
"LDAP endpoint {Endpoint} failed system-side at {Stage}; treating as no answer.",
endpoint, stage.Stage);
return LdapAuthResult.Fail(stage.Failure);
}
catch (Exception ex)
{
// Belt-and-braces: ANY unexpected exception fails closed to the most conservative
// system-side bucket rather than propagating to the caller.
_logger?.LogWarning(ex, "LDAP endpoint {Endpoint} failed system-side with an unexpected error.", endpoint);
return LdapAuthResult.Fail(LdapAuthFailure.ServiceAccountBindFailed);
}
}
/// <inheritdoc />
/// <remarks>
/// Fail-closed like <see cref="AuthenticateAsync"/>: never throws to the caller (cancellation is
/// observed at entry only). Uses the service account in every case, so it is
/// <see cref="LdapGroupLookupStatus.NotSupported"/> in <see cref="LdapBindMode.User"/> mode. The
/// name is normalised exactly as <see cref="AuthenticateAsync"/> normalises it in
/// <see cref="LdapBindMode.ServiceAccount"/> mode (trimmed, otherwise verbatim), so a name a session
/// was issued for resolves to the same entry. The endpoint walk, sticky preference, timeouts and
/// TLS policy are shared with authentication; only a system-side failure moves to the next
/// endpoint. Credentials are never logged.
/// </remarks>
public Task<LdapGroupLookupResult> GetUserGroupsAsync(string username, CancellationToken ct)
{
ct.ThrowIfCancellationRequested();
return Task.FromResult(LookupGroups(username));
}
private LdapGroupLookupResult LookupGroups(string username)
{
if (!_options.Enabled)
return LdapGroupLookupResult.Of(LdapGroupLookupStatus.ProviderDisabled);
// User mode has no service account to search with, and a blank service-account DN would bind
// anonymously — the validator refuses that at boot; refuse it here too for unvalidated hosts.
if (_options.BindMode == LdapBindMode.User || string.IsNullOrWhiteSpace(_options.ServiceAccountDn))
return LdapGroupLookupResult.Of(LdapGroupLookupStatus.NotSupported);
if (string.IsNullOrWhiteSpace(username))
return LdapGroupLookupResult.Of(LdapGroupLookupStatus.UserNotFound);
username = username.Trim();
return WalkEndpoints(
endpoint => LookupAgainst(endpoint, username),
result => result.Status == LdapGroupLookupStatus.DirectoryUnavailable,
LdapGroupLookupResult.Of(LdapGroupLookupStatus.DirectoryUnavailable));
}
/// <summary>
/// One lookup attempt against one endpoint on a fresh connection: connect, service-account bind,
/// search. A fault in any of those is <see cref="LdapGroupLookupStatus.DirectoryUnavailable"/> (try
/// the next endpoint); every other status is the directory's answer.
/// </summary>
private LdapGroupLookupResult LookupAgainst(LdapEndpoint endpoint, string username)
{
try
{
using var conn = _connectionFactory.Create();
ConnectTo(conn, endpoint);
try
{
conn.Bind(_options.ServiceAccountDn, _options.ServiceAccountPassword);
}
catch (LdapException)
{
throw new StageFailure(LdapAuthFailure.ServiceAccountBindFailed, "service-bind");
}
var entries = SearchUser(conn, username, UserAccountControlAttribute);
if (entries.Count == 0)
return LdapGroupLookupResult.Of(LdapGroupLookupStatus.UserNotFound);
if (entries.Count >= 2)
return LdapGroupLookupResult.Of(LdapGroupLookupStatus.AmbiguousUser);
var entry = entries[0];
if (IsAccountDisabled(entry))
return LdapGroupLookupResult.Of(LdapGroupLookupStatus.UserDisabled);
var canonical = ExtractUserName(entry, username);
return LdapGroupLookupResult.Found(canonical, ExtractDisplayName(entry, canonical), ExtractGroups(entry));
}
catch (StageFailure stage)
{
_logger?.LogWarning(
"LDAP endpoint {Endpoint} failed system-side at {Stage} during a group lookup; treating as no answer.",
endpoint, stage.Stage);
return LdapGroupLookupResult.Of(LdapGroupLookupStatus.DirectoryUnavailable);
}
catch (Exception ex)
{
_logger?.LogWarning(ex, "LDAP endpoint {Endpoint} failed system-side with an unexpected error during a group lookup.", endpoint);
return LdapGroupLookupResult.Of(LdapGroupLookupStatus.DirectoryUnavailable);
}
}
/// <summary>AD's account-flags attribute; absent on directories that do not model it (GLAuth, OpenLDAP).</summary>
private const string UserAccountControlAttribute = "userAccountControl";
/// <summary>AD <c>userAccountControl</c> ACCOUNTDISABLE flag.</summary>
private const int AccountDisableFlag = 0x2;
/// <summary>
/// <see langword="true"/> when the entry carries AD's <c>userAccountControl</c> with ACCOUNTDISABLE set.
/// An absent or unparseable value is "not disabled": directories without the attribute have no such
/// state, and a password bind is what refuses a disabled account at sign-in anyway.
/// </summary>
private static bool IsAccountDisabled(LdapSearchEntry entry)
=> entry.Attributes.TryGetValue(UserAccountControlAttribute, out var values)
&& values.Count > 0
&& int.TryParse(values[0], System.Globalization.NumberStyles.Integer,
System.Globalization.CultureInfo.InvariantCulture, out var flags)
&& (flags & AccountDisableFlag) != 0;
/// <summary>Opens the connection; a connect/TLS fault means this endpoint is unreachable (system-side).</summary>
private void ConnectTo(ZB.MOM.WW.Auth.Ldap.Internal.ILdapConnection conn, LdapEndpoint endpoint)
{
try
{
conn.Connect(
endpoint.Host,
endpoint.Port,
_options.Transport,
_options.AllowInsecure,
_options.ConnectionTimeoutMs,
_options.ServerCertificateValidationCallback);
}
catch (LdapException)
{
throw new StageFailure(LdapAuthFailure.ServiceAccountBindFailed, "connect");
}
}
/// <summary>Steps 6–11 of the 0.3.0 flow: service-account bind, search, user re-bind, groups.</summary>
private LdapAuthResult CompleteWithServiceAccount(ZB.MOM.WW.Auth.Ldap.Internal.ILdapConnection conn, string username, string password)
{
// 6. Service-account bind so we can search for the user's DN. A bind failure here is a
// service-account misconfiguration — DISTINCT from a user-credential failure — so it
// maps to ServiceAccountBindFailed.
try
{
conn.Bind(_options.ServiceAccountDn, _options.ServiceAccountPassword);
}
catch (LdapException)
{
throw new StageFailure(LdapAuthFailure.ServiceAccountBindFailed, "service-bind");
}
// 7–8. Require exactly one match. Zero -> UserNotFound; two or more -> AmbiguousUser.
// Both are authoritative answers from a healthy directory, so they end the walk.
// We never attempt a user bind against an ambiguous DN.
var entries = SearchUser(conn, username);
if (entries.Count == 0)
return LdapAuthResult.Fail(LdapAuthFailure.UserNotFound);
if (entries.Count >= 2)
return LdapAuthResult.Fail(LdapAuthFailure.AmbiguousUser);
var entry = entries[0];
// 9. User bind: re-bind as the resolved DN to verify the password. A bind failure here is
// the end user's bad credentials — the directory answered, so this is returned directly
// and never retried against another endpoint.
try
{
conn.Bind(entry.Dn, password);
}
catch (LdapException)
{
return LdapAuthResult.Fail(LdapAuthFailure.BadCredentials);
}
return SucceedFromEntry(entry, username);
}
/// <summary>
/// <see cref="LdapBindMode.User"/>: the user's own bind is the authentication; the same
/// connection then reads their entry. Only result 49 (invalid credentials — AD's answer for a
/// 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 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);
}
catch (LdapException ex) when (ex.ResultCode == LdapException.InvalidCredentials)
{
return LdapAuthResult.Fail(LdapAuthFailure.BadCredentials);
}
catch (LdapException)
{
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, bound.AccountName is null ? null : SamAccountNameAttribute);
if (entries.Count != 1)
return LdapAuthResult.Fail(LdapAuthFailure.GroupLookupFailed);
if (!IsBoundAccount(conn, entries[0], bound, username))
{
_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>AD's constructed attribute holding a principal's <c>DOMAIN\name</c>, derived from its <c>objectSid</c>.</summary>
private const string PrincipalNameAttribute = "msDS-PrincipalName";
/// <summary>
/// The account a user bind authenticated: either its DN, or (AD's Who-am-I form) its
/// <c>sAMAccountName</c> plus, when the answer carried one, its NetBIOS <see cref="Domain"/>.
/// Exactly one of <see cref="Dn"/> / <see cref="AccountName"/> is set.
/// </summary>
private sealed record BoundIdentity(string? Dn, string? AccountName, string? Domain = null)
{
public override string ToString() =>
Dn is not null ? $"dn:{Dn}" : Domain is null ? $"u:{AccountName}" : $@"u:{Domain}\{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:&lt;dn&gt;</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();
string? domain = null;
var slash = account.LastIndexOf('\\');
if (slash >= 0)
{
domain = account[..slash].Trim();
account = account[(slash + 1)..];
}
if (account.Length > 0)
return new BoundIdentity(null, account, string.IsNullOrEmpty(domain) ? null : domain);
}
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
/// — for AD's <c>u:DOMAIN\name</c> answer — it is provably that domain's account of that name
/// (see <see cref="IsBoundAdAccount"/>).
/// </summary>
private bool IsBoundAccount(
ZB.MOM.WW.Auth.Ldap.Internal.ILdapConnection conn, LdapSearchEntry entry, BoundIdentity bound, string username)
{
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 IsBoundAdAccount(conn, entry, bound, username);
}
/// <summary>
/// The <c>u:DOMAIN\name</c> case. A matching <c>sAMAccountName</c> is necessary but not enough:
/// <c>sAMAccountName</c> is unique per DOMAIN, so a search base that spans a forest (a Global
/// Catalog) can find another domain's account of the same name and hand back its groups
/// (scadaproj#50). In order of strength:
/// <list type="number">
/// <item>Where the directory offers AD's constructed <c>msDS-PrincipalName</c> for the entry —
/// its <c>DOMAIN\name</c>, computed from the entry's <c>objectSid</c> — it must equal the
/// Who-am-I answer, domain included. That is the decisive, SID-anchored check. (The bound
/// account's own <c>objectSid</c> cannot be compared directly: Who-am-I does not return it.)</item>
/// <item>Otherwise the name must have exactly ONE holder under <see cref="LdapOptions.SearchBase"/>,
/// and that holder's DN must be the entry's: two holders mean which one bound cannot be proven,
/// so the sign-in fails closed. The user search already proves this when it was itself
/// <c>(sAMAccountName=&lt;the bound name&gt;)</c> and found one entry, so no second search is
/// made then. Residual: a search base that covers another domain's holder but NOT the bound
/// account's own domain is not detectable without <c>msDS-PrincipalName</c>.</item>
/// </list>
/// </summary>
private bool IsBoundAdAccount(
ZB.MOM.WW.Auth.Ldap.Internal.ILdapConnection conn, LdapSearchEntry entry, BoundIdentity bound, string username)
{
if (!entry.Attributes.TryGetValue(SamAccountNameAttribute, out var values)
|| values.Count != 1
|| !string.Equals(values[0], bound.AccountName, StringComparison.OrdinalIgnoreCase))
{
return false;
}
if (bound.Domain is not null && ReadPrincipalName(conn, entry.Dn) is { } principal)
return string.Equals(principal, $@"{bound.Domain}\{bound.AccountName}", StringComparison.OrdinalIgnoreCase);
var searchedOnTheBoundName =
string.Equals(_options.UserNameAttribute, SamAccountNameAttribute, StringComparison.OrdinalIgnoreCase)
&& string.Equals(username, bound.AccountName, StringComparison.OrdinalIgnoreCase);
if (searchedOnTheBoundName)
return true;
IReadOnlyList<LdapSearchEntry> holders;
try
{
holders = conn.Search(
_options.SearchBase,
$"({SamAccountNameAttribute}={LdapEscaping.Filter(bound.AccountName!)})",
new[] { SamAccountNameAttribute });
}
catch (LdapException)
{
// Same bucket as the user search: the directory could not answer, which is system-side.
throw new StageFailure(LdapAuthFailure.ServiceAccountBindFailed, "search");
}
if (holders.Count != 1)
return false;
try
{
return LdapDn.Equals(holders[0].Dn, entry.Dn);
}
catch (Exception)
{
return false;
}
}
/// <summary>
/// The entry's <c>msDS-PrincipalName</c> when the directory computes one in <c>DOMAIN\name</c>
/// form; <see langword="null"/> when it is absent, unreadable, or a SID string (AD's form for a
/// principal it cannot name) — all of which mean "not available", never "mismatch".
/// </summary>
private static string? ReadPrincipalName(ZB.MOM.WW.Auth.Ldap.Internal.ILdapConnection conn, string dn)
{
try
{
var read = conn.Read(dn, new[] { PrincipalNameAttribute });
if (read is not null
&& read.Attributes.TryGetValue(PrincipalNameAttribute, out var values)
&& values.Count == 1
&& values[0].Contains('\\', StringComparison.Ordinal))
{
return values[0].Trim();
}
}
catch (LdapException)
{
// Not offered, or not readable by this account: fall back to the uniqueness check.
}
return null;
}
/// <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, 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
// to ServiceAccountBindFailed, the closest system-side bucket (same limitation as
// Connect), until a DirectoryUnavailable value exists.
try
{
var filter = $"({_options.UserNameAttribute}={LdapEscaping.Filter(username)})";
return conn.Search(_options.SearchBase, filter, BuildSearchAttributes(extraAttribute));
}
catch (LdapException)
{
throw new StageFailure(LdapAuthFailure.ServiceAccountBindFailed, "search");
}
}
/// <summary>
/// Steps 10–11: fail-closed group extraction, then success. The returned username is the
/// entry's own <see cref="LdapOptions.UserNameAttribute"/> value (the directory's spelling), so
/// <c>JDoe</c> and <c>jdoe</c> sign in as one identity; the typed (normalised) name is the
/// fallback when the entry carries no such value.
/// </summary>
private LdapAuthResult SucceedFromEntry(LdapSearchEntry entry, string username)
{
IReadOnlyList<string> groups;
try
{
groups = ExtractGroups(entry);
}
catch
{
return LdapAuthResult.Fail(LdapAuthFailure.GroupLookupFailed);
}
if (groups.Count == 0)
return LdapAuthResult.Fail(LdapAuthFailure.GroupLookupFailed);
var canonical = ExtractUserName(entry, username);
return LdapAuthResult.Success(canonical, ExtractDisplayName(entry, canonical), groups);
}
/// <summary>
/// Internal control-flow exception that carries an already-mapped <see cref="LdapAuthFailure"/>
/// out of a stage to the single fail-closed catch site. Never escapes this type.
/// </summary>
private sealed class StageFailure : Exception
{
public StageFailure(LdapAuthFailure failure, string stage)
{
Failure = failure;
Stage = stage;
}
public LdapAuthFailure Failure { get; }
/// <summary>Which stage faulted (<c>connect</c> / <c>service-bind</c> / <c>user-bind</c> / <c>search</c>), for diagnostics.</summary>
public string Stage { get; }
}
/// <summary>
/// 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(string? extraAttribute = null)
{
var attributes = new List<string>(4);
foreach (var name in new[] { _options.DisplayNameAttribute, _options.GroupAttribute, _options.UserNameAttribute, extraAttribute })
{
if (name is not null && !attributes.Contains(name, StringComparer.OrdinalIgnoreCase))
attributes.Add(name);
}
return attributes;
}
/// <summary>
/// Returns the directory's spelling of the name the user matched on: the value of the configured
/// username attribute that equals the typed (already normalised) name ignoring case. Only when no
/// value does is the first non-blank value used, and only when there is none the typed name.
/// </summary>
/// <remarks>
/// The attribute can be multi-valued — the default <c>cn</c> is, and OpenLDAP / 389-DS entries
/// routinely carry both <c>cn: John Smith</c> and <c>cn: jsmith</c>. 0.4.1 returned whichever
/// value the server listed first, so <c>jsmith</c> could sign in as <c>John Smith</c> depending on
/// attribute ordering (Auth-009). Matching ordinal-ignore-case still canonicalises case
/// (<c>JSMITH</c> → <c>jsmith</c>), which is what 0.4.1 set out to do.
/// </remarks>
private string ExtractUserName(LdapSearchEntry entry, string username)
{
if (!entry.Attributes.TryGetValue(_options.UserNameAttribute, out var values) || values.Count == 0)
return username;
foreach (var value in values)
{
if (string.Equals(value, username, StringComparison.OrdinalIgnoreCase))
return value;
}
return string.IsNullOrWhiteSpace(values[0]) ? username : values[0];
}
/// <summary>
/// Returns the first value of the configured display-name attribute, falling back to
/// the (already normalised) username when the directory entry has no such attribute.
/// </summary>
private string ExtractDisplayName(LdapSearchEntry entry, string username)
{
if (entry.Attributes.TryGetValue(_options.DisplayNameAttribute, out var values) && values.Count > 0)
return values[0];
return username;
}
/// <summary>
/// Extracts group short names from the configured group attribute. Each value is a
/// group DN (e.g. <c>cn=Engineers,ou=g,dc=x</c>); the first RDN's value is returned
/// (e.g. <c>Engineers</c>), RFC 4514 escape-aware so an escaped comma in the CN is
/// preserved rather than truncating the name.
/// </summary>
private IReadOnlyList<string> ExtractGroups(LdapSearchEntry entry)
{
if (!entry.Attributes.TryGetValue(_options.GroupAttribute, out var values) || values.Count == 0)
return Array.Empty<string>();
var groups = new List<string>(values.Count);
foreach (var value in values)
groups.Add(ToGroupShortName(value));
return groups;
}
/// <summary>
/// Yields a group's short name from its DN by returning the value of the first RDN
/// (e.g. <c>cn=Engineers,ou=g,dc=x</c> → <c>Engineers</c>). The extraction is RFC 4514
/// escape-aware (<see cref="LdapEscaping.FirstRdnValue"/>), so a CN that legitimately
/// contains an escaped comma — <c>cn=Eng\,ineers,...</c> or <c>cn=A\2cB,...</c> — is
/// returned intact rather than truncated at the escaped comma. Values with no <c>=</c>
/// are returned unchanged.
/// </summary>
private static string ToGroupShortName(string groupDn)
=> LdapEscaping.FirstRdnValue(groupDn);
}