fix(opcua): credential lockout counts per credential identity, ignores transient denials (#844, #845)
#844: a success cleared the whole per-client count, so a client holding a valid key could make four guesses at another key id, sign in with its own, and repeat forever. Failures are now charged to the (client, credential identity) pair -- IOpcUaUserAuthenticator.DescribeCredential, key:<keyId> for API keys -- and to the client as a whole. A success clears only its own identity's count; the per-identity threshold locks that identity; a new per-client cap (OpcUa:CredentialLockout:MaxFailedAttemptsPerClient, default 2 x MaxFailedAttempts) that a success never resets bounds spraying across key ids and locks every credential. Slots are bounded on both counts; a waiter whose identity has room is not held behind one whose identity has none. #845: (1) store timeouts, miss-budget refusals, store/authenticator exceptions, an unset pepper and cancellation are reported Transient (OpcUaUserAuthResult.Unavailable) and released uncounted, so a ConfigDb stall can no longer lock every keyed client out; the client still sees the same opaque denial. (2) a full 4096-entry table defers its next prune until the earliest entry could age out instead of rescanning under the lock per failure. (3) ApplicationUri deliberately NOT added to the key: on a None channel it is a free string, so it would let an attacker reset the count per guess -- documented. (4) wire tests: distinct client certificates on a Sign endpoint are locked out separately; the ApplicationConfigPath branch keeps the SDK lockout off (falsified by removing the loaded-branch disable).
This commit is contained in:
@@ -272,22 +272,30 @@ public sealed class OpcUaApplicationHost : IAsyncDisposable
|
||||
// lmxopcua#833 — only credential-bearing (UserName) activations are counted and refused. Anonymous
|
||||
// never consults the lockout, so failed sign-ins cannot lock a client (or its NAT neighbours) out of
|
||||
// anonymous access the way the SDK's own lockout did.
|
||||
// The ApplicationUri is deliberately NOT part of the key (lmxopcua#845): on a None channel it is a free,
|
||||
// unauthenticated string, so an attacker could reset its count by varying it.
|
||||
var lockoutKey = tokenType == UserTokenType.UserName
|
||||
? FailedCredentialLockout.KeyFor(context.ChannelCertificate?.Thumbprint, peer)
|
||||
: null;
|
||||
// lmxopcua#844 — failures are counted per (client, credential identity) as well as per client, so a
|
||||
// success clears only its own identity's count.
|
||||
var credentialIdentity = lockoutKey is null
|
||||
? FailedCredentialLockout.NoIdentity
|
||||
: DescribeCredential(host._userAuthenticator, args.UserIdentityTokenHandler);
|
||||
if (lockoutKey is not null)
|
||||
{
|
||||
// Waits (bounded) for one of this client's verification slots — parallel activations queue, they are
|
||||
// never refused for parallelism. Refused only when locked out, or (uncounted) when no slot freed in time.
|
||||
var decision = await host._credentialLockout.BeginAsync(lockoutKey, ct).ConfigureAwait(false);
|
||||
var decision = await host._credentialLockout.BeginAsync(lockoutKey, credentialIdentity, ct).ConfigureAwait(false);
|
||||
if (decision.Verdict == CredentialLockoutVerdict.LockedOut)
|
||||
{
|
||||
// Logged once per lockout episode at Information; every further refusal at Debug, so a client
|
||||
// hammering a lockout cannot flood the log (#833 review).
|
||||
var seconds = (long)Math.Ceiling(decision.Remaining.TotalSeconds);
|
||||
host._logger.Log(decision.FirstRefusal ? LogLevel.Information : LogLevel.Debug,
|
||||
"OpcUaApplicationHost: UserName activation refused — client {Client} is locked out for {Seconds}s more",
|
||||
lockoutKey, seconds);
|
||||
"OpcUaApplicationHost: UserName activation refused — client {Client} is locked out ({Scope}: {Identity}) for {Seconds}s more",
|
||||
lockoutKey, decision.Scope,
|
||||
decision.Scope == CredentialLockoutScope.Client ? "every credential" : credentialIdentity, seconds);
|
||||
return AuthenticationResult.Reject(ServiceResult.Create(StatusCodes.BadUserAccessDenied,
|
||||
$"Too many failed authentication attempts. Try again in {seconds} seconds."));
|
||||
}
|
||||
@@ -309,8 +317,9 @@ public sealed class OpcUaApplicationHost : IAsyncDisposable
|
||||
try
|
||||
{
|
||||
// Port zero is only an adapter for the existing IP-budget seam: the SDK exposes no peer port.
|
||||
await HandleImpersonationAsync(host._userAuthenticator, args, host._logger, host._options.AllowAnonymous,
|
||||
peer is null ? null : new System.Net.IPEndPoint(peer, 0), ct).ConfigureAwait(false);
|
||||
var transient = await HandleImpersonationAsync(host._userAuthenticator, args, host._logger,
|
||||
host._options.AllowAnonymous, peer is null ? null : new System.Net.IPEndPoint(peer, 0), ct)
|
||||
.ConfigureAwait(false);
|
||||
var result = ServiceResult.IsBad(args.IdentityValidationError)
|
||||
? AuthenticationResult.Reject(args.IdentityValidationError)
|
||||
: args.Identity is { } identity
|
||||
@@ -321,19 +330,29 @@ public sealed class OpcUaApplicationHost : IAsyncDisposable
|
||||
{
|
||||
var admitted = args.Identity is not null && !ServiceResult.IsBad(args.IdentityValidationError);
|
||||
completed = true;
|
||||
if (host._credentialLockout.Complete(lockoutKey, admitted))
|
||||
if (!admitted && transient)
|
||||
{
|
||||
// lmxopcua#845 — a store timeout / miss-budget refusal / authenticator fault is not a bad
|
||||
// credential: release the slot uncounted.
|
||||
host._credentialLockout.Abandon(lockoutKey, credentialIdentity);
|
||||
}
|
||||
else if (host._credentialLockout.Complete(lockoutKey, credentialIdentity, admitted) is var scope
|
||||
&& scope != CredentialLockoutScope.None)
|
||||
{
|
||||
host._logger.LogWarning(
|
||||
"OpcUaApplicationHost: client {Client} locked out of UserName activation for {Seconds}s after "
|
||||
+ "{Attempts} failed attempts (OpcUa:CredentialLockout); anonymous activation is unaffected",
|
||||
lockoutKey, host._options.CredentialLockout.LockoutSeconds, host._options.CredentialLockout.MaxFailedAttempts);
|
||||
"OpcUaApplicationHost: client {Client} locked out of UserName activation ({Scope}: {Identity}) "
|
||||
+ "for {Seconds}s after repeated failed attempts (OpcUa:CredentialLockout: {PerCredential} per "
|
||||
+ "credential, {PerClient} per client); anonymous activation is unaffected",
|
||||
lockoutKey, scope, scope == CredentialLockoutScope.Client ? "every credential" : credentialIdentity,
|
||||
host._options.CredentialLockout.LockoutSeconds, host._options.CredentialLockout.MaxFailedAttempts,
|
||||
host._credentialLockout.ClientThreshold);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (lockoutKey is not null && !completed) host._credentialLockout.Abandon(lockoutKey);
|
||||
if (lockoutKey is not null && !completed) host._credentialLockout.Abandon(lockoutKey, credentialIdentity);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -407,7 +426,10 @@ public sealed class OpcUaApplicationHost : IAsyncDisposable
|
||||
/// <param name="allowAnonymous">Whether anonymous sessions may connect.</param>
|
||||
/// <param name="remoteEndpoint">The activating client's IP endpoint when known (lmxopcua#751), handed to
|
||||
/// the authenticator for per-client accounting; null when it could not be resolved.</param>
|
||||
internal static void HandleImpersonation(
|
||||
/// <returns><see langword="true"/> when a UserName denial was TRANSIENT — not a verdict on the credential
|
||||
/// (the authenticator threw or reported <see cref="OpcUaUserAuthResult.Transient"/>), so the failed-credential
|
||||
/// lockout must not count it (lmxopcua#845).</returns>
|
||||
internal static bool HandleImpersonation(
|
||||
IOpcUaUserAuthenticator authenticator,
|
||||
ImpersonateEventArgs args,
|
||||
ILogger logger,
|
||||
@@ -416,7 +438,7 @@ public sealed class OpcUaApplicationHost : IAsyncDisposable
|
||||
=> HandleImpersonationAsync(authenticator, args, logger, allowAnonymous, remoteEndpoint)
|
||||
.AsTask().GetAwaiter().GetResult();
|
||||
|
||||
private static async ValueTask HandleImpersonationAsync(
|
||||
private static async ValueTask<bool> HandleImpersonationAsync(
|
||||
IOpcUaUserAuthenticator authenticator, ImpersonateEventArgs args, ILogger logger,
|
||||
bool allowAnonymous = true, System.Net.IPEndPoint? remoteEndpoint = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
@@ -424,13 +446,13 @@ public sealed class OpcUaApplicationHost : IAsyncDisposable
|
||||
if (args.UserIdentityTokenHandler.Token is AnonymousIdentityToken anonymousToken)
|
||||
{
|
||||
await HandleAnonymousImpersonationAsync(authenticator, args, logger, allowAnonymous, anonymousToken, cancellationToken).ConfigureAwait(false);
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
|
||||
if (args.UserIdentityTokenHandler.Token is not UserNameIdentityToken token)
|
||||
{
|
||||
// X509 tokens — let the SDK's default validation stand.
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
|
||||
string password;
|
||||
@@ -444,7 +466,7 @@ public sealed class OpcUaApplicationHost : IAsyncDisposable
|
||||
{
|
||||
logger.LogWarning(ex, "OpcUaApplicationHost: failed to decrypt UserName token");
|
||||
args.IdentityValidationError = ServiceResult.Create(StatusCodes.BadIdentityTokenRejected, "UserName token decryption failed");
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
|
||||
OpcUaUserAuthResult result;
|
||||
@@ -456,22 +478,45 @@ public sealed class OpcUaApplicationHost : IAsyncDisposable
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// Includes cancellation: neither says anything about the credential (lmxopcua#845).
|
||||
logger.LogError(ex, "OpcUaApplicationHost: UserName authenticator threw for {User}", token.UserName);
|
||||
args.IdentityValidationError = ServiceResult.Create(StatusCodes.BadIdentityTokenRejected, "Authentication failed");
|
||||
return;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!result.Success)
|
||||
{
|
||||
logger.LogInformation("OpcUaApplicationHost: UserName auth denied for {User}: {Error}",
|
||||
token.UserName, result.Error);
|
||||
logger.LogInformation("OpcUaApplicationHost: UserName auth denied for {User}{Transient}: {Error}",
|
||||
token.UserName, result.Transient ? " (transient, not counted toward the lockout)" : string.Empty, result.Error);
|
||||
args.IdentityValidationError = ServiceResult.Create(StatusCodes.BadIdentityTokenRejected, result.Error ?? "Invalid credentials");
|
||||
return;
|
||||
return result.Transient;
|
||||
}
|
||||
|
||||
args.Identity = new RoleCarryingUserIdentity(token, result.Roles, result.Principal, result.ApiKeyId);
|
||||
logger.LogInformation("OpcUaApplicationHost: UserName auth granted for {User} as {Principal} ({Roles})",
|
||||
token.UserName, result.Principal, string.Join(",", result.Roles));
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The credential identity a UserName activation presents, for the lockout's per-identity count
|
||||
/// (lmxopcua#844): <see cref="IOpcUaUserAuthenticator.DescribeCredential"/> over the decrypted token. Never
|
||||
/// throws: an unreadable token or a faulting implementation falls back to the username.
|
||||
/// </summary>
|
||||
internal static string DescribeCredential(IOpcUaUserAuthenticator authenticator, IUserIdentityTokenHandler handler)
|
||||
{
|
||||
if (handler.Token is not UserNameIdentityToken token) return FailedCredentialLockout.NoIdentity;
|
||||
var username = token.UserName ?? string.Empty;
|
||||
try
|
||||
{
|
||||
var decrypted = (handler as UserNameIdentityTokenHandler)?.DecryptedPassword;
|
||||
var password = decrypted is null ? string.Empty : Encoding.UTF8.GetString(decrypted);
|
||||
return authenticator.DescribeCredential(username, password) ?? "user:" + username;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return "user:" + username;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
Reference in New Issue
Block a user