Merge security review fixes: sandbox refuses async/stackalloc/MethodImpl, unwinding-overflow guard, deep-data types (#971); T-SQL ScriptDom single-SELECT guard (#974); Auth 0.5.0 directory re-query on revalidation (#975); fleet-diagnostics target check (#973)

This commit is contained in:
Joseph Doherty
2026-12-03 12:27:35 -05:00
25 changed files with 1299 additions and 71 deletions
+4 -2
View File
@@ -242,8 +242,10 @@ scripted-alarm predicates) runs scripts through the shared `ScriptRunGuard`:
`ScriptStackExhaustedException` (Bad, script log) instead of overflowing the
stack, which would terminate the whole server. The runtime compile inserts a
stack check at the entry of the script and of every lambda, anonymous method
and local function (lmxopcua#779); the editor does not show it and does not
flag recursion, and bounded recursion still works.
and local function (lmxopcua#779), and guards every `catch` / `finally` so a
handler that throws on every frame cannot overflow the stack while unwinding
(lmxopcua#971 review); the editor does not show it and does not flag
recursion, and bounded recursion still works.
- **Configuration keys and their ranges.** All four knobs are node-wide (the
`Scripting` appsettings section, shared by virtual tags, Calculation tags and
scripted alarms) and are clamped when bound, with one startup Warning per
+6 -4
View File
@@ -36,13 +36,15 @@ Until 2026-12 the analyzer was a **deny-list** over the whole BCL (namespaces `S
A script may name only:
- **The `ctx` API** — `ScriptContext` and its subclasses (`ctx.GetTag` / `SetVirtualTag` / `Now` / `Logger` / `CancellationToken`, `ScriptContext.Deadband`), `DataValueSnapshot`, `DriverDataType`, and `Serilog.ILogger` + `LogEventLevel` for `ctx.Logger`. Nothing else from the OtOpcUa assemblies (the host's `CredentialFilePaths`, `PollGroupEngine`, … used to be reachable).
- **Value types and helpers** — the primitives, `string`, `decimal`, `Guid`, `DateTime` / `DateTimeOffset` / `TimeSpan` / `DateOnly` / `TimeOnly` / `TimeZoneInfo`, `Math` / `MathF` / `Convert` / `BitConverter` / `BinaryPrimitives` / `BitOperations` / `Random`, `Enum`, `Nullable`, `Array`, `Span` / `Memory`, tuples, `Index` / `Range`, `HashCode`, `Lazy`, the delegate types `Func` / `Action` / `Predicate` / `Comparison` / `Converter`, and `System.Exception` plus every exception type in `System`.
- **Collections and LINQ-to-objects** — the whole of `System.Collections`, `System.Collections.Generic` and `System.Collections.ObjectModel`; `System.Linq.Enumerable` (not `ParallelEnumerable` / `Queryable`).
- **Value types and helpers** — the primitives, `string`, `decimal`, `Guid`, `DateTime` / `DateTimeOffset` / `TimeSpan` / `DateOnly` / `TimeOnly` / `TimeZoneInfo`, `Math` / `MathF` / `Convert` / `BitConverter` / `BinaryPrimitives` / `BitOperations` / `Random`, `Enum`, `Nullable`, `Array`, `Span` / `Memory`, tuples, `Index` / `Range`, `HashCode`, the delegate types `Func` / `Action` / `Predicate` / `Converter`, and `System.Exception` plus every exception type in `System` except `AggregateException`.
- **Collections and LINQ-to-objects** — `System.Collections`, `System.Collections.Generic` and `System.Collections.ObjectModel` (except `StructuralComparisons`, `IStructuralEquatable`, `IStructuralComparable` and `DictionaryEntry`); `System.Linq.Enumerable` (not `ParallelEnumerable` / `Queryable`).
- **Text** — `StringBuilder`, `Encoding`, `Rune`, `System.Text.RegularExpressions` (`Regex` / `Match` / `Group` / …), and the formatting types of `System.Globalization` (`CultureInfo`, `NumberStyles`, `DateTimeStyles`, `NumberFormatInfo`, …).
- `Interlocked` / `Volatile`, and `[MethodImpl]` on a local function.
- **`System.Type` and `CancellationToken` as values, with a member allow-list** (`ForbiddenTypeAnalyzer.RestrictedTypeMembers`): `typeof(x)`, `o.GetType() == typeof(double)`, `t.Name` / `FullName` / `IsValueType` / `IsEnum` … work; `Assembly`, `Module`, `TypeHandle`, `GetMethod`, `MakeGenericType` do not. `ctx.CancellationToken` may be polled (`IsCancellationRequested`, `ThrowIfCancellationRequested`) but not `Register`ed against or waited on.
The rules (`ForbiddenTypeAnalyzer`): every type a script names, and every type an expression evaluates or converts to, must be allowed (generic arguments and array elements included); every member used must be declared on an allowed type (or be in `AllowedMembers`), must not be in `ForbiddenMembers` (`CultureInfo.CurrentCulture` and the other ambient-culture setters, `TimeZoneInfo.ClearCachedData`, `Encoding.RegisterProvider`, `Regex.CacheSize`), and its return type must be allowed — which is what keeps reflection handles out of reach (`Exception.TargetSite` is a member of an allowed type but returns a `MethodBase`; `Delegate.Method` / `DynamicInvoke` are declared on the un-listed `System.Delegate`). `__makeref` / `__refvalue` / `__reftype` / `__arglist`, `lock`, and `extern` local functions are refused syntactically. Pre-imported namespaces are unchanged (`System`, `System.Linq`, `ZB.MOM.WW.OtOpcUa.Core.Abstractions`, `ZB.MOM.WW.OtOpcUa.Core.Scripting`) — a collection still needs its full name (`System.Collections.Generic.List<int>`).
The rules (`ForbiddenTypeAnalyzer`): every type a script names, and every type an expression evaluates or converts to, must be allowed (generic arguments and array elements included); every member used must be declared on an allowed type (or be in `AllowedMembers`), must not be in `ForbiddenMembers` (`CultureInfo.CurrentCulture` and the other ambient-culture setters, `TimeZoneInfo.ClearCachedData`, `Encoding.RegisterProvider`, `Regex.CacheSize`), and its return type must be allowed — which is what keeps reflection handles out of reach (`Exception.TargetSite` is a member of an allowed type but returns a `MethodBase`; `Delegate.Method` / `DynamicInvoke` are declared on the un-listed `System.Delegate`). `__makeref` / `__refvalue` / `__reftype` / `__arglist`, `lock`, and `extern` local functions are refused syntactically, and so — since the 2026-12-02 security review — are **`async` lambdas / anonymous methods / local functions** and **`stackalloc`**: each compiled through the allow-list *and* the deploy gate and then terminated the host (exit 134). An `async void` body's exception is rethrown on the thread pool by a compiler-synthesized builder no allow-list check sees, and one over-sized `stackalloc` overflows the stack inside a single frame, before any stack guard runs. `[MethodImpl]` on a local function may set only the JIT hints (`NoInlining` / `NoOptimization` / `AggressiveInlining` / `AggressiveOptimization`): `InternalCall` passed the gate and then failed to load, and `Synchronized` is a `lock`. Members the compiler calls without a name in the source — query operators, `foreach`'s enumerator pattern, `Deconstruct`, a collection initializer's `Add` — are checked like named ones. Pre-imported namespaces are unchanged (`System`, `System.Linq`, `ZB.MOM.WW.OtOpcUa.Core.Abstractions`, `ZB.MOM.WW.OtOpcUa.Core.Scripting`) — a collection still needs its full name (`System.Collections.Generic.List<int>`).
**Deep or cyclic data (2026-12-02 review, lmxopcua#971).** Some BCL and compiler-synthesized members recurse over a value's contents with no script frame for the stack guard to check, so a structure a script nests a million deep in a loop — or makes cyclic — overflowed the stack inside `ToString` / `Equals` / `GetHashCode` / `CompareTo` / `Message` and terminated the host (in the script, or later in host code that logs or publishes the value). The analyzer refuses what builds one: a `Tuple` / `ValueTuple` / `KeyValuePair` / anonymous type with an *open* element (`object`, `ValueType`, an interface, a type parameter) — give it a concrete type, e.g. `Convert.ToDouble(v.Value)`; a tuple literal that is only deconstructed (`var (v, q) = (t.Value, t.StatusCode)`) is fine; `Lazy` (its `ToString` renders `Value`, which can be itself); `StructuralComparisons` / `IStructuralEquatable` / `IStructuralComparable` (an array that contains itself); `DictionaryEntry`; exception constructors taking an inner exception or an `object` (a million-deep chain), and `AggregateException`; an interpolated string held as a `FormattableString` / `IFormattable` (only `FormattableString.Invariant($"…")` is allowed, which formats at once); constructing or `with`-copying a host record with an `object` member (`DataValueSnapshot`); and an array whose element type can hold an array (`object[]`, `Array[]`, an interface) plus `Array.CreateInstance` — the *host* copies a returned array recursively (`OwnedDataSample.CopyLegacy`) and compares it structurally (`VirtualTagActor.SameValue`), so a nested or self-containing `object[]` overflowed the host's stack after the run (typed and jagged arrays are fine; an implicit `params object[]`, as in `ctx.Logger.Information("{A}", v)`, is not a script-held array). `System.Comparison` is off the list for a related reason: `Array` / `List` `Sort` and `BinarySearch` rethrow a comparer's exception from a catch block, so a comparer that recursed through `Sort` overflowed while unwinding — order with `OrderBy` / `ThenBy`. Iterators, `goto`, `checked`, exception filters, collection expressions, interpolation handlers, `params Span`, `using` and deconstruction were reviewed and are safe: their lowered code runs on the evaluating thread under the guard. A script that returns a lazy sequence (an iterator, an un-materialised LINQ query) hands the host an object whose code runs only if the host enumerates it, which the publish path does not.
`ScriptSandbox.Build` compiles against the pinned OtOpcUa assemblies (`Core.Abstractions`, `Core.Scripting.Abstractions`, `Serilog`, the context type's assembly) plus only the BCL assemblies in `ScriptSandbox.BclAssemblyNames` — `System.Private.CoreLib`, `System.Runtime`, `netstandard`, `System.Collections`, `System.Collections.NonGeneric`, `System.ObjectModel`, `System.Linq`, `System.Text.RegularExpressions` — so most refused APIs (XML, archives, networking, expression trees, crypto, the console, processes) do not even bind and are reported as compile errors. That is defence in depth, not the gate: `System.Private.CoreLib` carries `File`, `Thread`, `Assembly` and `Environment`, so the analyzer decides. `ForbiddenTypeAnalyzerTests` compiles every K-1 bypass against *every* assembly the test host can load and asserts the analyzer alone rejects it, and enumerates every public type of the reference set to pin that nothing from a flagged namespace is allowed.
@@ -70,7 +72,7 @@ Absent, blank or unrecognised values mean `Error` — a typo never silently weak
#### Known resource limits (accepted trade-offs)
The sandbox cannot pre-empt a script. **Memory:** each run's own-thread allocation is sampled (`GC.GetAllocatedBytesForCurrentThread`) and a run over `Scripting:MaxAllocBytesPerRun` (default 64 MB) quarantines the script — but the sample is taken after the run returns, so a script that allocates fast enough (`new byte[int.MaxValue]` in a loop) can still OOM the process first. **CPU:** a tight loop keeps its pool thread after the timeout fires; `ScriptRunGuard` bounds that to one orphan per script by refusing further runs while it spins (Bad `"previous evaluation still running"`) and quarantines after three consecutive timeouts (a refusal is not a strike) — or immediately on a refusal behind an orphan that has run longer than `Scripting:StuckOrphanQuarantineFactor` (default 10) × the timeout, which is what quarantines a never-returning `while(true)`. Both are mitigations; pre-emptive CPU/memory limits need the out-of-process runner (→ #750 design, #780; opt-in via `Scripting:Runner=OutOfProcess`, below). **Stack:** unbounded recursion used to terminate the whole server — a `StackOverflowException` cannot be caught, and lmxopcua#779 reproduced it out of process (local function, mutual recursion, self-referencing `Func<>`, anonymous self-application, recursion through LINQ: the child process died with "Stack overflow." / SIGABRT). `ScriptEvaluator.Compile` now rewrites the script so the body and every lambda, anonymous method and local function starts with `ScriptStackGuard.Check()` (`RuntimeHelpers.TryEnsureSufficientExecutionStack`), so the recursion fails the script with `ScriptStackExhaustedException` — Bad quality and a script-log entry like any throwing script — while there is still stack left. A runtime check rather than an analyzer rule because recursion is not decidable from syntax (anonymous self-application never names itself); bounded recursion keeps working. Limits: the depth reached depends on the evaluating thread's stack size; a recursion that never re-enters script code is not seen (the sandbox exposes no such API); a script can catch the exception, which only unwinds it. Pinned by `ScriptRecursionContainmentTests` (one child process per shape) and `ScriptStackGuardInjectionTests`. Script authoring is gated by the AdminUI `ConfigEditor` policy — **`Administrator` or `Designer`**, not Administrator alone — and that same policy gates deploy, so a Designer can author a script and put it into production; that gate is the primary control (AdminUI-001 deliberately admitted Designers to the script pages and `/api/script-analysis/*`; lmxopcua#779 corrected this sentence, which used to say Admin-only). See `docs/ScriptEditor.md` §"Runtime safety".
The sandbox cannot pre-empt a script. **Memory:** each run's own-thread allocation is sampled (`GC.GetAllocatedBytesForCurrentThread`) and a run over `Scripting:MaxAllocBytesPerRun` (default 64 MB) quarantines the script — but the sample is taken after the run returns, so a script that allocates fast enough (`new byte[int.MaxValue]` in a loop) can still OOM the process first. **CPU:** a tight loop keeps its pool thread after the timeout fires; `ScriptRunGuard` bounds that to one orphan per script by refusing further runs while it spins (Bad `"previous evaluation still running"`) and quarantines after three consecutive timeouts (a refusal is not a strike) — or immediately on a refusal behind an orphan that has run longer than `Scripting:StuckOrphanQuarantineFactor` (default 10) × the timeout, which is what quarantines a never-returning `while(true)`. Both are mitigations; pre-emptive CPU/memory limits need the out-of-process runner (→ #750 design, #780; opt-in via `Scripting:Runner=OutOfProcess`, below). **Stack:** unbounded recursion used to terminate the whole server — a `StackOverflowException` cannot be caught, and lmxopcua#779 reproduced it out of process (local function, mutual recursion, self-referencing `Func<>`, anonymous self-application, recursion through LINQ: the child process died with "Stack overflow." / SIGABRT). `ScriptEvaluator.Compile` now rewrites the script so the body and every lambda, anonymous method and local function starts with `ScriptStackGuard.Check()` (`RuntimeHelpers.TryEnsureSufficientExecutionStack`), so the recursion fails the script with `ScriptStackExhaustedException` — Bad quality and a script-log entry like any throwing script — while there is still stack left. A runtime check rather than an analyzer rule because recursion is not decidable from syntax (anonymous self-application never names itself); bounded recursion keeps working. Limits: the depth reached depends on the evaluating thread's stack size; a recursion that never re-enters script code is not seen — the review found BCL members that do exactly that over script-built data (see "Deep or cyclic data" in the sandbox section), and the analyzer now refuses the constructs that build it; a script can catch the exception, which only unwinds it. **Exception handlers (2026-12-02 review, lmxopcua#971):** a `catch` / `finally` runs as a funclet *on top of* the frames being unwound, so a handler that throws starts a nested dispatch deeper still (~6 KB a level) — `catch { throw; }` on every frame overflowed while unwinding from the guard's own exception, and 300 frames that each rethrow overflowed with no guard involvement. The rewrite therefore also gives every script `catch` the filter `when (ScriptStackGuard.CanHandle() && …)` and wraps every `finally` body in `if (ScriptStackGuard.CanHandle())`: once the stack is low, script handlers are skipped and the exception in flight reaches the host in one dispatch (the run fails with it). On a healthy stack both are no-ops. Pinned by `ScriptRecursionContainmentTests` (one child process per shape) and `ScriptStackGuardInjectionTests`. Script authoring is gated by the AdminUI `ConfigEditor` policy — **`Administrator` or `Designer`**, not Administrator alone — and that same policy gates deploy, so a Designer can author a script and put it into production; that gate is the primary control (AdminUI-001 deliberately admitted Designers to the script pages and `/api/script-analysis/*`; lmxopcua#779 corrected this sentence, which used to say Admin-only). See `docs/ScriptEditor.md` §"Runtime safety".
+18 -4
View File
@@ -214,6 +214,18 @@ row:
carriage return. T-SQL's `]]` inside `[ … ]` and MySQL's `#` comments are modelled. An **Odbc** driver's
backend is unknown, so its statement must lex identically under every dialect (so must a statement checked
without a provider). Changing the driver form's **Provider** re-validates the queries.
- **On SQL Server the statement is also parsed (2026-12-02 review).** `;` is not a statement boundary in
T-SQL — `SELECT 1 COMMIT KILL 55` is three statements to SQL Server and was one `SELECT` to the lexer, so
a `COMMIT` ending the rolled-back transaction followed by `DISABLE TRIGGER ALL ON DATABASE`, `KILL`,
`SHUTDOWN WITH NOWAIT` or `WRITETEXT` passed the guard. For **SqlServer** — and for **Odbc** and no
provider, whose backend may be SQL Server, so the strictest reading applies — the statement is parsed
with `Microsoft.SqlServer.TransactSql.ScriptDom` and must be exactly **one batch holding exactly one
`SELECT`**, with no `INTO` and no `OPENQUERY` / `OPENROWSET` / `OPENDATASOURCE` (they run text on another
server or read a file). CTEs, subqueries, window functions, `UNION`, `OPTION (…)` and `@name` parameters
are ordinary `SELECT`s and pass. An Odbc statement's positional `?` markers are read as variables for the
parse; anything else SQL Server's grammar does not accept — a PostgreSQL `::` cast, `LIMIT`, a T-SQL
reserved word used as a bare alias (`AS top`) — is refused on Odbc, so quote or rename it. The lexical
rules remain as a second, independent layer.
- **It executes in a read-only transaction where the provider has one** — always rolled back regardless:
PostgreSQL and Oracle `SET TRANSACTION READ ONLY`, MySQL a read-only **session** plus `START TRANSACTION
READ ONLY` (a smuggled `COMMIT` ends a transaction, not a session; the session is restored afterwards). A
@@ -223,8 +235,8 @@ row:
positional `$n` parameters (rewritten from your `@name` markers), which makes Npgsql pass the text unsplit
as one extended-protocol statement; the server rejects anything after a `;` itself. Oracle (ODP.NET)
refuses a second statement anyway. SQL Server and MySQL execute a multi-statement batch — there the
per-dialect guard is the line, and MySQL's read-only session is defence in depth that hidden text could
undo.
guard is the line (on SQL Server its T-SQL parse, above), and MySQL's read-only session is defence in depth
that hidden text could undo.
- None of this replaces the grant: a non-transactional side effect (an e-mail procedure, a call out to
another system, an autonomous transaction) is outside every layer — which is why a read-only driver
**must** connect with a `SELECT`-only login (see [Database login](#database-login-required)).
@@ -484,7 +496,9 @@ value. Writes never change driver health. Discovery advertises `Operate` only fo
two rows per changed row (#987). `NamedQueryBypassLiveTests` proves, per provider, that each smuggled-write
string is a working bypass the old way, that the guard refuses it, and that with the guard bypassed the
write still does not land (PostgreSQL, MySQL) — plus the MySQL session restore and an Oracle read under
`SET TRANSACTION READ ONLY`.
`SET TRANSACTION READ ONLY`. `SqlServerNamedQueryBatchLiveTests` does the same for SQL Server's `;`-less
batch (`SELECT 1 AS v COMMIT UPDATE …` commits the old way; the guard refuses it for SqlServer and Odbc) and
reads a CTE + window-function + subquery + parameter query Good through the driver.
## Database login (required)
@@ -494,7 +508,7 @@ The driver's own guards are not a substitute for the database's grants:
the tables and views its tags and named queries read, and nothing else. The named-query guard is a
per-dialect keyword check plus an always-rolled-back (read-only where the provider has one) transaction;
none of that can stop a **non-transactional** side effect — a function that sends mail or calls out,
autonomous transactions — and on SQL Server and MySQL a statement that got past the lexer would run as a
autonomous transactions — and on SQL Server and MySQL a statement that got past the guard would run as a
batch. Only the grant is a boundary.
- **A writable driver must connect with a login limited to its write targets** — `SELECT` as above,
plus exactly what its modes need on exactly the tables / procedures its writable tags name:
+4 -3
View File
@@ -1792,12 +1792,13 @@ Admin reads `LdapGroupRoleMapping` rows from the Config DB (`src/Core/ZB.MOM.WW.
Group→role resolution used to run once, in `/auth/login`, so a user removed from an admin group (or whose `/role-grants` row was deleted) kept every role while the sliding cookie renewed or a Blazor circuit stayed open. Roles are now re-validated on a timer:
- **Stamp.** `/auth/login` adds `otopcua:group` (the sign-in LDAP groups), `otopcua:preresolved-role` (roles granted outside the mapper — the DevStub Administrator), `otopcua:auth-time` and `otopcua:validated-at` (`Session/AdminSessionClaims.cs`).
- **Cookie.** `CookieAuthenticationEvents.OnValidatePrincipal` → `AdminSessionRevalidator`. Inside `Security:Cookie:RevalidateIntervalMinutes` (default 5) it is a timestamp comparison; past it, the stored groups are re-run through `IGroupRoleMapper<string>` (appsettings `GroupToRole` + DB `LdapGroupRoleMapping`). A changed role set replaces the principal and re-issues the cookie (promotions are picked up too); **no remaining role signs the user out**.
- **Cookie.** `CookieAuthenticationEvents.OnValidatePrincipal` → `AdminSessionRevalidator`. Inside `Security:Cookie:RevalidateIntervalMinutes` (default 5) it is a timestamp comparison; past it, the user's **current directory groups** are re-read (see below) and re-run through `IGroupRoleMapper<string>` (appsettings `GroupToRole` + DB `LdapGroupRoleMapping`). A changed role set replaces the principal and re-issues the cookie (promotions are picked up too); **no remaining role signs the user out**.
- **Circuits.** `RevalidatingAdminAuthenticationStateProvider` (a `RevalidatingServerAuthenticationStateProvider`, registered by `AddOtOpcUaAuth`) forces the same check each interval. A circuit cannot re-issue the cookie, so a changed or revoked state yields an anonymous principal and every `AuthorizeView`/policy fails closed until the page is reloaded.
- **No LDAP traffic.** The re-check reads ConfigDb only. ⚠️ Therefore a change to the user's **directory group membership** is NOT observed (the shared `ZB.MOM.WW.Auth.Ldap` client has no password-less group lookup); that window is bounded by `Security:Cookie:MaxSessionMinutes` (default 480, absolute from sign-in, `0` disables).
- **Directory groups are re-read (2026-12-02 review).** Each re-check asks the directory for the user's current groups through `ZB.MOM.WW.Auth` 0.5.0's passwordless `ILdapGroupLookup` (a service-account search by `UserNameAttribute`, no user password; `OtOpcUaLdapAuthService` implements it with the same `Enabled` / `DevStubMode` / transport rules as sign-in), then maps them — so removing a user from a directory group takes effect at the next interval, not at `MaxSessionMinutes`. The refreshed groups replace the session's `otopcua:group` claims. The account **not found, disabled, ambiguous, or in no group** ⇒ the session ends. Cost: one directory search + one ConfigDb read per interval per session. With `Security:Ldap:BindMode=User` (no service account), LDAP disabled, or a non-library LDAP service the lookup answers `NotSupported` and the sign-in groups are re-mapped as before; `Security:Cookie:MaxSessionMinutes` (default 480, absolute from sign-in, `0` disables) bounds that case.
- **Fail-soft on a directory outage.** `DirectoryUnavailable` (or a lookup fault) keeps the session on its last known groups — still re-mapped, so a `/role-grants` change applies — with a Warning; the absolute lifetime still caps it.
- **Fail-soft.** A role-map fault (ConfigDb down) keeps the session and retries on the next request rather than signing everyone out; the absolute lifetime still caps it.
- **Upgrade.** A cookie minted before this change carries no stamps and is refused once, forcing a re-login.
- **`Security:Auth:DisableLogin=true`** replaces the cookie handler with the auto-login handler, so none of this runs (and the circuit provider skips validation) — the docker-dev rig is unchanged.
- **`Security:Auth:DisableLogin=true`** replaces the cookie handler with the auto-login handler, so none of this runs (and the re-validator never queries the directory) (and the circuit provider skips validation) — the docker-dev rig is unchanged.
### Headless deploy API (`POST /api/deployments`)