From c00ebf1320e3919eab8863a670b308740f011e74 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 10:09:39 -0500 Subject: [PATCH] =?UTF-8?q?fix(scripting):=20#971=20the=20script=20sandbox?= =?UTF-8?q?=20is=20an=20allow-list=20=E2=80=94=20the=20K-1=20bypasses=20(C?= =?UTF-8?q?reateDelegate,=20Expressions,=20XML/Tar=20I/O,=20X509Store,=20T?= =?UTF-8?q?imers/BackgroundWorker/AsParallel,=20Serilog.Log)=20are=20refus?= =?UTF-8?q?ed?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ForbiddenTypeAnalyzer inverted from a BCL deny-list to an allow-list of types/members (ctx API, value/time/maths types, collections, LINQ-to-objects, string/Regex/formatting; System.Type and CancellationToken with member allow-lists). Every named type, expression type and used member (incl. return type and generic args) is checked; __makeref/__arglist, lock and extern local functions refused syntactically. ScriptSandbox references only eight BCL assemblies (defence in depth). The Monaco editor and the publish gate share both, so parity holds. Tests: theory over the K-1 snippets (publish gate + analyzer alone against the full host), every-public-type enumeration, shipped-sample + idiom regression, editor/publish parity. Differential over every script-shaped literal in src/tests: all 511 previously-compiling scripts still compile (one expression-tree test intentionally refused). PE cache signing by the host (option 4) deferred as a follow-up. Co-Authored-By: Claude --- docs/ScriptEditor.md | 32 +- docs/VirtualTags.md | 27 +- docs/security.md | 32 + .../ForbiddenTypeAnalyzer.cs | 770 +++++++++--------- .../ScriptEvaluator.cs | 12 +- .../ScriptSandbox.cs | 77 +- .../ForbiddenTypeAnalyzerTests.cs | 307 +++++++ .../ScriptAllowListRegressionTests.cs | 193 +++++ .../ScriptSandboxBuildTests.cs | 26 +- .../ScriptSandboxHardeningTests.cs | 10 +- .../ScriptSandboxTests.cs | 69 +- .../ScriptStackGuardInjectionTests.cs | 22 +- .../ScriptAnalysis/DiagnoseTests.cs | 49 ++ 13 files changed, 1149 insertions(+), 477 deletions(-) create mode 100644 tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ForbiddenTypeAnalyzerTests.cs create mode 100644 tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScriptAllowListRegressionTests.cs diff --git a/docs/ScriptEditor.md b/docs/ScriptEditor.md index e0c7b7b84..5bcb1b004 100644 --- a/docs/ScriptEditor.md +++ b/docs/ScriptEditor.md @@ -162,20 +162,21 @@ user's fault. ### 2. ForbiddenTypeAnalyzer `ForbiddenTypeAnalyzer.Analyze(compilation)` walks the wrapped syntax tree and -resolves every referenced symbol against the sandbox deny-list (namespace -prefixes `System.IO`, `System.Net`, `System.Diagnostics`, `System.Reflection`, -`System.Threading` — the whole namespace, with only `CancellationToken`, -`Interlocked` and `Volatile` allowed back in — `System.Threading.Tasks`, -`System.Runtime.InteropServices`, `System.Runtime.Loader`, `Microsoft.Win32`; -type-granular denials `System.Environment`, `System.AppDomain`, `System.GC`, -`System.Activator`, `System.Runtime.CompilerServices.Unsafe` / -`RuntimeHelpers`; and member-granular denials on `System.Type`'s by-name -reflection entry points — `GetType(string)`, `GetMethod(s)`, `InvokeMember`, -and the `GetProperty`/`GetField`/`GetMember`/`GetConstructor`/`GetEvent` -families). The runtime publish gate uses the same analyzer, so a deny-list -change needs a `DiagnoseTests` case to keep editor ⇔ publish parity. Each violation is mapped -via `tree.GetMappedLineSpan(span)` to user-source coordinates and emitted as an -error marker with code `OTSCRIPT_FORBIDDEN`. +checks every referenced symbol, expression type and invoked member against the +sandbox **allow-list** (lmxopcua#971): the `ctx` API, primitive / time / maths +value types, the collection namespaces, LINQ-to-objects (`Enumerable`), string / +`StringBuilder` / `Regex`, the formatting types of `System.Globalization`, and +`System.Type` / `CancellationToken` as values with a member allow-list. Anything +else is refused — see `docs/VirtualTags.md` §"The sandbox is an allow-list" for +the full list and the rules. Because the reference set (`ScriptSandbox.BclAssemblyNames`) +is narrowed too, an API whose assembly is not referenced (XML, archives, +networking, expression trees, the console, processes) shows as an ordinary +**compiler** error rather than `OTSCRIPT_FORBIDDEN`, and is no longer offered by +completion. The runtime publish gate uses the same analyzer and the same +reference set, so an allow-list change needs a `DiagnoseTests` case to keep +editor ⇔ publish parity (`Editor_and_publish_gate_agree`). Each violation is +mapped via `tree.GetMappedLineSpan(span)` to user-source coordinates and emitted +as an error marker with code `OTSCRIPT_FORBIDDEN`. ### Runtime safety (what happens after publish) @@ -208,7 +209,8 @@ scripted-alarm predicates) runs scripts through the shared `ScriptRunGuard`: `ctx.CancellationToken.ThrowIfCancellationRequested()`) ends its own abandoned run and frees the slot, instead of holding a pool thread until it returns. A script that ignores the token is still an orphan. The editor completes the member, and - `CancellationToken` is on the sandbox allow-list. + `CancellationToken` is on the sandbox allow-list — for polling only: `Register` + and `WaitHandle` are refused (a callback or a wait outlives the evaluation). - **Allocation budget.** A single run allocating more than `Scripting:MaxAllocBytesPerRun` (64 MB) is quarantined. This is sampled after the run returns, so a run that OOMs the process first is not stopped — that needs an diff --git a/docs/VirtualTags.md b/docs/VirtualTags.md index 05845b0ad..80b2e39fd 100644 --- a/docs/VirtualTags.md +++ b/docs/VirtualTags.md @@ -25,21 +25,36 @@ User scripts are compiled via `Microsoft.CodeAnalysis.CSharp` (regular compiler, 1. **Injection guard** — `EnforceSingleRunMember` parses the synthesized wrapper and rejects sources whose brace structure would inject sibling methods or type declarations alongside the `CompiledScript.Run` wrapper method. Throws `CompilationErrorException` with diagnostic id `LMX001`/`LMX002` (Core.Scripting-013). 2. **Roslyn compile** against `ScriptSandbox.Build(contextType)`. Throws `CompilationErrorException` on syntax / type errors. -3. **`ForbiddenTypeAnalyzer.Analyze`** walks the syntax tree post-compile and resolves every referenced symbol against the deny-list. Throws `ScriptSandboxViolationException` with every offending source span attached. This is defence-in-depth: `ScriptOptions` alone cannot block every BCL namespace because .NET type forwarding routes types through assemblies the allow-list does permit. +3. **`ForbiddenTypeAnalyzer.Analyze`** walks the syntax tree post-compile and resolves every referenced symbol, expression type and invoked member against the sandbox **allow-list** (below). Throws `ScriptSandboxViolationException` with every offending source span attached. This is the gate; the narrowed reference set in step 2 is defence in depth. 4. **PE emit** — `CSharpCompilation.Emit` writes the assembly to a `MemoryStream`. Failures here are Roslyn-internal; user scripts don't reach this step. 5. **ALC load + delegate bind** — loads the emitted assembly into a collectible `ScriptAssemblyLoadContext` and binds a typed `Func, TResult>` delegate to the `CompiledScript.Run` method. -`ScriptSandbox.Build` constructs the compile reference set in two parts. First, four pinned OtOpcUa assemblies are always included: `Core.Abstractions` (for `DataValueSnapshot` / `DriverDataType`), `Core.Scripting` (for `ScriptContext` + `Deadband`), `Serilog` (for `ILogger`), and the concrete context type's assembly. Second, the BCL subset is enumerated from the runtime's `TRUSTED_PLATFORM_ASSEMBLIES` list, restricted to filenames starting with `System.*` plus `netstandard.dll`, `mscorlib.dll`, and `Microsoft.Win32.Registry.dll` (the last needed so `ForbiddenTypeAnalyzer` can resolve and reject registry types). Pre-imported namespaces: `System`, `System.Linq`, `ZB.MOM.WW.OtOpcUa.Core.Abstractions`, `ZB.MOM.WW.OtOpcUa.Core.Scripting`. +### The sandbox is an allow-list (lmxopcua#971) -`ForbiddenTypeAnalyzer.ForbiddenNamespacePrefixes` denies `System.IO`, `System.Net`, `System.Diagnostics`, `System.Reflection`, `System.Threading` (the whole namespace — `ForbiddenTypeAnalyzer.AllowedTypesInForbiddenNamespaces` lets only `CancellationToken`, `Interlocked` and `Volatile` back in), `System.Threading.Tasks`, `System.Runtime.InteropServices`, `System.Runtime.Loader`, and `Microsoft.Win32`. Matching is by prefix against the resolved symbol's containing namespace, so `System.Net` catches `System.Net.Http.HttpClient` and every subnamespace. `System.Threading.Tasks` is denied because scripts are synchronous predicates with no legitimate need to start background tasks — a `Task.Run` fan-out would outlive the per-evaluation timeout entirely (Core.Scripting-003). `System.Runtime.Loader` is denied to block `AssemblyLoadContext` / `AssemblyDependencyResolver` — arbitrary DLL loads into the host process (Core.Scripting-012). +Until 2026-12 the analyzer was a **deny-list** over the whole BCL (namespaces `System.IO` / `System.Net` / `System.Reflection` / `System.Threading` …, a list of types such as `Environment` / `Activator` / `AppContext`, and `System.Type`'s by-name reflection members). The 2026-12-02 review (K-1) showed a deny-list over the BCL cannot be closed: `Delegate.CreateDelegate` and `System.Linq.Expressions` bound `Type.GetType` and `Process.Start` by name (a script started `/usr/bin/touch`), `System.Xml.Linq` and `System.Formats.Tar` read and wrote files, `System.Timers.Timer` / `BackgroundWorker` / `AsParallel` started background work that outlived the budget, and `Serilog.Log.Logger = …` replaced the process logger. Under the default `Scripting:Runner = InProcess`, **anyone who could author a script — `Administrator` or `Designer` — could run arbitrary code as the OtOpcUa service account.** The rule is now inverted: what is not listed is refused. + +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`). +- **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`). + +`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. + +**Adding to the list.** Add a type only if it has no I/O, no process-wide state, no background work, no blocking wait, and no member that returns or accepts a reflection handle; prefer a new `ScriptContext` helper to opening BCL surface. The editor's completions, diagnostics and the publish gate all follow the list automatically (one authority). + +**Upgrading.** A deployed script that used an API now off the list (the 2026-12 differential over every script in the repo found none apart from an expression-tree test) is refused when the upgraded node compiles it (the deploy gate does not compile scripts): a virtual tag or Calculation tag publishes Bad with `sandbox violation: …` and a Warning log line, and a scripted alarm's predicate fails to load. Re-run the analyzer over stored scripts before upgrading — open each in the script editor (same analyzer), or compile them through `ScriptEvaluator`. -`ForbiddenTypeAnalyzer.ForbiddenFullTypeNames` denies type-granularly: `System.Environment`, `System.AppDomain`, `System.GC`, `System.Activator`, `System.Runtime.CompilerServices.Unsafe`, `System.Runtime.CompilerServices.RuntimeHelpers`, and (lmxopcua#792, process-wide runtime configuration) `System.AppContext` (`SetSwitch`/`SetData` flip BCL switches for the whole process; `GetData`/`BaseDirectory` leak host paths), `System.Console` (redirects/writes the process streams — log through `ctx.Logger`), `System.Runtime.GCSettings`, `System.Runtime.ProfileOptimization`, `System.Text.EncodingProvider`/`CodePagesEncodingProvider`, `System.ComponentModel.TypeDescriptor` and `System.Security.Cryptography.CryptoConfig`. These live in namespaces that are otherwise allowed — `System` (primitives, `Math`) and `System.Runtime.CompilerServices` (compile-time attributes such as `CallerMemberNameAttribute`) — so a namespace-prefix rule cannot reach them. `Environment.Exit` / `FailFast` terminate the host process outright (Core.Scripting-001); `Unsafe.As` bypasses the type system; `RuntimeHelpers.GetUninitializedObject` builds an instance of any type without a constructor. `Thread` / `ThreadPool` / `Timer` / `SemaphoreSlim` and the rest of `System.Threading` are now caught by the namespace prefix above instead of being listed one by one — a script is a synchronous expression with no use for background work or blocking primitives (Core.Scripting-010 / -012, review R05:10). `ForbiddenTypeAnalyzer.ForbiddenMembers` additionally denies `System.Type`'s by-name reflection entry points (`GetType(string)`, `GetMethod(s)`, `InvokeMember`, and the `GetProperty`/`GetField`/`GetMember`/`GetConstructor`/`GetEvent` families), which would otherwise reach a forbidden type without naming it syntactically, and the ambient-state members `CultureInfo.DefaultThreadCurrentCulture` / `DefaultThreadCurrentUICulture` / `CurrentCulture` / `CurrentUICulture` and `TimeZoneInfo.ClearCachedData` (use `CultureInfo.InvariantCulture` / `GetCultureInfo(...)`). Scripts running in the out-of-process ScriptWorker are rejected by the same analyzer at compile. #### 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". -`System.Threading.Tasks` is denied (Core.Scripting-003), which prevents `Task.Run` / `Parallel` fan-out that would spawn background work outliving the timeout. #### Out-of-process runner (`Scripting:Runner`, lmxopcua#780) @@ -321,7 +336,7 @@ In the v2 actor system, virtual-tag engine composition is owned by the driver-ro - `src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptContext.cs` — abstract `ctx` API scripts see - `src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptGlobals.cs` — generic globals wrapper naming the field `ctx` - `src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptSandbox.cs` — assembly allow-list + imports -- `src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ForbiddenTypeAnalyzer.cs` — post-compile semantic deny-list +- `src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ForbiddenTypeAnalyzer.cs` — post-compile semantic allow-list (the sandbox gate, lmxopcua#971) - `src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptEvaluator.cs` — five-step compile pipeline (injection guard → Roslyn compile → ForbiddenTypeAnalyzer → PE emit → ALC load) - `src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/TimedScriptEvaluator.cs` — 250ms default timeout wrapper - `src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/CompiledScriptCache.cs` — SHA-256-keyed compile cache diff --git a/docs/security.md b/docs/security.md index 5a707880a..6333189fe 100644 --- a/docs/security.md +++ b/docs/security.md @@ -1891,6 +1891,38 @@ outage on top of it. --- +## Script sandbox — an allow-list (lmxopcua#971) + +Virtual-tag, Calculation and scripted-alarm scripts are C# authored under the AdminUI `ConfigEditor` policy — +**`Administrator` or `Designer`** — and that same policy deploys them. Under the default +`Scripting:Runner = InProcess` they run **inside the server process, as the service account**; under +`OutOfProcess` they run in `ScriptWorker` processes (as the same account unless `Scripting:Worker:Identity` +restricts it, `docs/ServiceHosting.md`). The script sandbox is therefore what stands between a Designer and +code execution on the server. + +**Until 2026-12 that sandbox was bypassable.** It was a deny-list over the whole BCL, and the 2026-12-02 review +(`docs/reviews/2026-12-02/06-core.md` K-1) compiled and ran scripts that started a process (`System.Linq.Expressions` +binding `Process.Start` by name), read and wrote files (`Delegate.CreateDelegate` → `File.ReadAllText`, +`System.Xml.Linq`, `System.Formats.Tar`), reached the certificate store, started background work, and replaced the +process logger. **Any build before lmxopcua#971 must be treated as granting Designers code execution as the +service account.** + +`ForbiddenTypeAnalyzer` is now an **allow-list**: a script may name only the `ctx` API, value / time / maths types, +the collection namespaces, LINQ-to-objects, string / `StringBuilder` / `Regex`, formatting types, and `System.Type` / +`CancellationToken` as values with a member allow-list; every member's return type must be allowed too, so no +reflection handle can be reached. `ScriptSandbox` compiles against eight BCL assemblies only, so most refused APIs do +not even bind. The publish gate and the script editor share both, so the editor shows exactly what publish refuses. +Full list and rules: `docs/VirtualTags.md` §"The sandbox is an allow-list". + +Residual exposure, by design: a script can still burn CPU and memory up to its budget (`ScriptRunGuard`; pre-emptive +limits need `OutOfProcess`), read any tag through `ctx.GetTag`, and write virtual tags. Extending the allow-list is a +security change — add only types with no I/O, process-wide state, background work, blocking wait or reflection +surface. The out-of-process runner's compiled-PE cache is still HMAC-signed by the **worker** with a key it is handed +in `Hello`; a worker that had escaped could forge entries for other scripts (follow-up from #971: move signing to the +host). + +--- + ## OTOPCUA0001 Analyzer — Compile-Time Guard Per-capability resilience (retry, timeout, circuit-breaker) is applied by `CapabilityInvoker` in `src/Core/ZB.MOM.WW.OtOpcUa.Core/Resilience/`. A driver-capability call made **outside** the invoker bypasses resilience entirely — which in production looks like inconsistent timeouts, un-wrapped retries, and unbounded blocking. diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ForbiddenTypeAnalyzer.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ForbiddenTypeAnalyzer.cs index 43358030d..21744aa9f 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ForbiddenTypeAnalyzer.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ForbiddenTypeAnalyzer.cs @@ -6,259 +6,204 @@ using Microsoft.CodeAnalysis.Text; namespace ZB.MOM.WW.OtOpcUa.Core.Scripting; /// -/// Post-compile sandbox guard. ScriptOptions alone can't reliably -/// constrain the type surface a script can reach because .NET 10's type-forwarding -/// system resolves many BCL types through multiple assemblies — restricting the -/// reference list doesn't stop System.Net.Http.HttpClient from being found if -/// any transitive reference forwards to System.Net.Http. This analyzer walks -/// the script's syntax tree after compile, uses the to -/// resolve every type / member reference, and rejects any whose containing namespace -/// matches a deny-list pattern. +/// The script sandbox gate: an allow-list over every symbol a user script names. After the script +/// compiles, the analyzer resolves every expression, type reference and invoked member through the +/// and rejects anything that is not explicitly allowed. The publish gate +/// () and the AdminUI Monaco editor's diagnostics +/// both call , so the editor accepts exactly what publish accepts. /// /// /// -/// Deny-list is the authoritative Phase 7 plan set, hardened since: -/// System.IO, System.Net, System.Diagnostics, -/// System.Reflection, System.Threading.Tasks and the whole of -/// System.Threading (scripts are synchronous predicates — no legitimate need -/// to start background work, and no blocking primitive may park the evaluation's pool -/// thread past its budget; CancellationToken / Interlocked / -/// Volatile are allow-listed back in), System.Runtime.InteropServices, -/// System.Runtime.Loader, Microsoft.Win32; plus the member-granular -/// (System.Type's reflection entry points). +/// Why an allow-list (lmxopcua#971, review 2026-12-02 K-1). The analyzer used to be a deny-list of +/// namespaces, types and System.Type members over the whole BCL. A deny-list over the BCL cannot be +/// closed: Delegate.CreateDelegate and System.Linq.Expressions bound Type.GetType and +/// Process.Start by name without naming either, System.Xml.Linq / System.Formats.Tar +/// read and wrote files, System.Timers / BackgroundWorker / AsParallel started +/// background work, and Serilog.Log.Logger replaced the process logger. A Designer's script ran +/// arbitrary code as the service account. The rule is now inverted: what is not listed here is refused. /// /// -/// Deny-list prefix match. System.Net catches System.Net.Http, -/// System.Net.Sockets, System.Net.NetworkInformation, etc. — every -/// subnamespace. If a script needs something under a denied prefix, Phase 7's -/// operator audience authors it through a helper the plan team adds as part of -/// the surface, not by unlocking the namespace. +/// What a script may name. +/// +/// The ctx API — and its subclasses, ScriptGlobals<T>, +/// DataValueSnapshot / DriverDataType, and Serilog.ILogger (+ LogEventLevel) +/// for ctx.Logger. +/// Primitive and value types, Math, Convert, BitConverter, string, +/// DateTime/DateTimeOffset/TimeSpan/TimeZoneInfo, tuples, delegates +/// (Func/Action/…), System.Exception and its System subclasses — see +/// . +/// The collection namespaces (), LINQ-to-objects +/// (System.Linq.Enumerable — not ParallelEnumerable or Queryable), +/// StringBuilder / Encoding, System.Text.RegularExpressions, and the read-only +/// formatting types of System.Globalization. +/// System.Type and CancellationToken as values, but only the members listed in +/// — typeof(x).Name works, typeof(x).Assembly does +/// not. +/// /// /// -/// A namespace-prefix deny-list is necessary but not sufficient: dangerous types -/// such as System.Environment, System.AppDomain, System.GC, -/// and System.Activator live directly in the System -/// namespace inside System.Private.CoreLib — the same allow-listed assembly -/// that supplies primitives (int, string, Math). They cannot -/// be blocked by namespace because System itself must stay allowed. They -/// are therefore denied type-granularly via -/// . Environment.Exit / -/// Environment.FailFast kill the in-process OPC UA server outright; -/// Activator.CreateInstance is a reflection-equivalent escape; GC -/// and AppDomain expose process-wide control. Legitimate System -/// types (Math, String, Convert, DateTime, …) are not -/// on the list and stay usable. +/// The rules. (1) Every type a script names — and every type an expression evaluates or converts +/// to — must be allowed, recursively through generic arguments and array element types. (2) Every member a +/// script uses must be declared on an allowed type (or be listed in ), must not +/// be in , and its type arguments and return type must be allowed. Rule (2)'s +/// return-type check is what keeps reflection handles out of reach: Exception.TargetSite is a member +/// of an allowed type but returns a MethodBase. (3) A few syntactic forms are refused outright +/// (): __makeref/__refvalue/__reftype/__arglist, +/// lock (a blocking primitive on a possibly-shared object) and extern local functions. +/// +/// +/// Defence in depth. also references only the handful of BCL assemblies +/// these types live in, so most unlisted APIs fail to bind at all. That alone is not sufficient — +/// System.Private.CoreLib carries File, Thread, Assembly, Environment — +/// so this analyzer remains the gate, and its own test (ForbiddenTypeAnalyzerTests) runs every +/// bypass against every assembly the host can load. +/// +/// +/// Adding to the list. Add a type only when it has no I/O, no process-wide state, no background work, +/// no blocking wait and no member that returns or accepts a reflection handle; prefer a new +/// helper to opening BCL surface. Every addition changes this assembly's +/// identity, so the out-of-process PE cache (keyed on it) is invalidated and nothing compiled under the old +/// list is reused. /// /// public static class ForbiddenTypeAnalyzer { - /// - /// Namespace prefixes scripts are NOT allowed to reference. Each string is - /// matched as a prefix against the resolved symbol's namespace name (dot- - /// delimited), so System.IO catches System.IO.File, - /// System.IO.Pipes, and any future subnamespace without needing explicit - /// enumeration. - /// - public static readonly IReadOnlyList ForbiddenNamespacePrefixes = + /// Namespaces whose every type is allowed. Exact match — a sub-namespace is NOT included. + public static readonly IReadOnlyList AllowedNamespaces = [ - "System.IO", - "System.Net", - "System.Diagnostics", // catches Process, ProcessStartInfo, EventLog, Trace/Debug file sinks - "System.Reflection", - "System.Threading.Tasks", // Task.Run / Parallel — scripts are synchronous predicates - // and have no legitimate need to start background work; - // a Task fan-out outlives the evaluation timeout entirely. - // Listed BEFORE the parent prefix so its rejection names it. - "System.Threading", // Thread / ThreadPool / Timer (background work that outlives - // the timeout) AND every blocking primitive — SemaphoreSlim, - // Monitor, SpinWait, ManualResetEvent(Slim), Mutex, - // EventWaitHandle — which park the script's pool thread past - // its budget (the same orphan ScriptRunGuard exists to bound) - // and, for the named kernel objects, touch system-global - // state. The few sync-free primitives a script may - // legitimately name are allow-listed in - // AllowedTypesInForbiddenNamespaces. - "System.Runtime.InteropServices", - "System.Runtime.Loader", // AssemblyLoadContext + AssemblyDependencyResolver — - // arbitrary DLL load into the host process. - // Namespace-prefix rather than type-granular so - // future BCL additions to this namespace are - // denied by default. - "Microsoft.Win32", // registry + "System.Collections", + "System.Collections.Generic", + "System.Collections.ObjectModel", ]; /// - /// Types that stay reachable although their namespace is in - /// . Matched by exact fully-qualified name against the - /// resolved type symbol (generic constructions unwrapped). The whole of System.Threading is - /// denied; these three are the sync-free primitives with no blocking surface — a - /// is read-only state, and - /// are single-instruction memory operations. + /// Types a script may name, as Namespace.Name without generic arity (so System.Func covers every + /// Func<…>). A nested type is allowed when its containing type is. Every System.Exception + /// subclass declared in the System namespace is allowed in addition to this list. /// - public static readonly IReadOnlyList AllowedTypesInForbiddenNamespaces = + public static readonly IReadOnlyList AllowedTypes = [ - "System.Threading.CancellationToken", - "System.Threading.Interlocked", - "System.Threading.Volatile", + // Primitives and core value types. + "System.Object", "System.ValueType", "System.Void", "System.String", "System.Boolean", "System.Char", + "System.SByte", "System.Byte", "System.Int16", "System.UInt16", "System.Int32", "System.UInt32", + "System.Int64", "System.UInt64", "System.Int128", "System.UInt128", "System.Half", "System.Single", + "System.Double", "System.Decimal", "System.Enum", "System.Nullable", "System.Array", "System.Guid", + "System.Index", "System.Range", "System.HashCode", "System.Tuple", "System.ValueTuple", + "System.Span", "System.ReadOnlySpan", "System.Memory", "System.ReadOnlyMemory", "System.MemoryExtensions", + "System.CharEnumerator", "System.FormattableString", "System.TypeCode", + // Time. + "System.DateTime", "System.DateTimeOffset", "System.DateTimeKind", "System.DayOfWeek", "System.DateOnly", + "System.TimeOnly", "System.TimeSpan", "System.TimeZoneInfo", + // Maths / conversion. + "System.Math", "System.MathF", "System.MidpointRounding", "System.Convert", "System.BitConverter", + "System.Base64FormattingOptions", "System.Random", + "System.Buffers.Binary.BinaryPrimitives", // register / byte-order decoding (pure functions over spans) + "System.Numerics.BitOperations", + // Strings. + "System.StringComparison", "System.StringComparer", "System.StringSplitOptions", + // Delegates (members inherited from System.Delegate — Method, Target, DynamicInvoke — stay refused). + "System.Func", "System.Action", "System.Predicate", "System.Comparison", "System.Converter", + // Small helpers and interfaces. + "System.Lazy", "System.IComparable", "System.IEquatable", "System.IFormattable", "System.IFormatProvider", + "System.IConvertible", "System.IDisposable", "System.ICloneable", + // System.Linq — LINQ-to-objects only (not ParallelEnumerable / ParallelQuery / Queryable / IQueryable). + "System.Linq.Enumerable", "System.Linq.IGrouping", "System.Linq.ILookup", "System.Linq.Lookup", + "System.Linq.IOrderedEnumerable", + // Text. + "System.Text.StringBuilder", "System.Text.Encoding", "System.Text.Rune", "System.Text.NormalizationForm", + "System.Text.RegularExpressions.Regex", "System.Text.RegularExpressions.RegexOptions", + "System.Text.RegularExpressions.Match", "System.Text.RegularExpressions.MatchCollection", + "System.Text.RegularExpressions.Group", "System.Text.RegularExpressions.GroupCollection", + "System.Text.RegularExpressions.Capture", "System.Text.RegularExpressions.CaptureCollection", + "System.Text.RegularExpressions.RegexMatchTimeoutException", + // Globalization (formatting / parsing; the ambient-culture members are in ForbiddenMembers). + "System.Globalization.CultureInfo", "System.Globalization.NumberStyles", "System.Globalization.DateTimeStyles", + "System.Globalization.NumberFormatInfo", "System.Globalization.DateTimeFormatInfo", + "System.Globalization.CompareOptions", "System.Globalization.CompareInfo", "System.Globalization.TextInfo", + "System.Globalization.UnicodeCategory", "System.Globalization.CharUnicodeInfo", + // Lock-free single-variable operations (no wait, no callback). + "System.Threading.Interlocked", "System.Threading.Volatile", + // Compiler-only: [MethodImpl] on a local function, and the handler an interpolated string binds to. + "System.Runtime.CompilerServices.MethodImplAttribute", "System.Runtime.CompilerServices.MethodImplOptions", + "System.Runtime.CompilerServices.DefaultInterpolatedStringHandler", + // The ctx API. + "ZB.MOM.WW.OtOpcUa.Core.Scripting.ScriptGlobals", + "ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataValueSnapshot", + "ZB.MOM.WW.OtOpcUa.Core.Abstractions.DriverDataType", + "Serilog.ILogger", "Serilog.Events.LogEventLevel", ]; /// - /// Members scripts are NOT allowed to call on otherwise-allowed types, as - /// (declaring type, member name). System.Type must stay reachable - /// (typeof, Name, IsValueType are ordinary metadata reads) but its reflection - /// entry points obtain a type or member by NAME — Type.GetType("System.IO.File") reaches a - /// forbidden type without ever naming it syntactically, and GetMethod* / GetProperty - /// / InvokeMember / … hand back a System.Reflection handle (which pass 2 catches when - /// declared, but not when consumed inline). Instance object.GetType() is declared on - /// System.Object and is not matched. + /// Types a script may hold and pass as values but whose members are limited to the listed names (anything + /// else declared on the type is refused). System.Type is the reflection gateway — typeof(x), + /// o.GetType() == typeof(double) and Convert.ChangeType(v, typeof(int)) are ordinary, but + /// Assembly, Module, GetMethod, MakeGenericType, TypeHandle, … are not. + /// CancellationToken (ctx.CancellationToken) may be polled but not Registered against + /// (a callback that runs off the evaluation) nor waited on through its WaitHandle. /// + public static readonly IReadOnlyDictionary> RestrictedTypeMembers = + new Dictionary>(StringComparer.Ordinal) + { + ["System.Type"] = + [ + "FullName", "Namespace", "IsValueType", "IsPrimitive", "IsEnum", "IsArray", "IsClass", "IsInterface", + "IsAbstract", "IsSealed", "IsGenericType", "IsAssignableFrom", "IsAssignableTo", "IsInstanceOfType", + "IsSubclassOf", "GetElementType", "GetGenericArguments", "GetEnumUnderlyingType", "GetEnumNames", + "GetTypeCode", "Equals", "GetHashCode", "ToString", "op_Equality", "op_Inequality", + ], + ["System.Threading.CancellationToken"] = + [ + "IsCancellationRequested", "CanBeCanceled", "ThrowIfCancellationRequested", "None", + "Equals", "GetHashCode", "ToString", "op_Equality", "op_Inequality", + ], + }; + + /// + /// Members allowed although their declaring type is not: typeof(int).Name binds to + /// System.Reflection.MemberInfo.Name (Type inherits it without overriding). + /// + public static readonly IReadOnlyList<(string Type, string Member)> AllowedMembers = + [ + ("System.Reflection.MemberInfo", "Name"), + ]; + + /// Members refused on otherwise-allowed types: process-wide state. public static readonly IReadOnlyList<(string Type, string Member)> ForbiddenMembers = [ - ("System.Type", "GetType"), - ("System.Type", "GetMethod"), - ("System.Type", "GetMethods"), - ("System.Type", "InvokeMember"), - ("System.Type", "GetProperty"), - ("System.Type", "GetProperties"), - ("System.Type", "GetField"), - ("System.Type", "GetFields"), - ("System.Type", "GetMember"), - ("System.Type", "GetMembers"), - ("System.Type", "GetConstructor"), - ("System.Type", "GetConstructors"), - ("System.Type", "GetEvent"), - ("System.Type", "GetEvents"), - ("System.Type", "GetDefaultMembers"), - - // Process-wide mutators on otherwise-useful types (lmxopcua#792). CultureInfo itself must stay - // reachable (CultureInfo.InvariantCulture is the right way to format), but its ambient-culture - // properties are process / pool-thread state: Default* apply to every thread created afterwards, and - // CurrentCulture / CurrentUICulture stick to the pooled thread the script ran on. The whole property is - // denied (read and write) — a script that wants a culture names InvariantCulture or CultureInfo.GetCultureInfo. + // Ambient culture is process / pool-thread state (lmxopcua#792): name InvariantCulture or GetCultureInfo. ("System.Globalization.CultureInfo", "DefaultThreadCurrentCulture"), ("System.Globalization.CultureInfo", "DefaultThreadCurrentUICulture"), ("System.Globalization.CultureInfo", "CurrentCulture"), ("System.Globalization.CultureInfo", "CurrentUICulture"), // Drops the process-wide time-zone cache. ("System.TimeZoneInfo", "ClearCachedData"), + // Process-wide encoding provider registration. + ("System.Text.Encoding", "RegisterProvider"), + // Process-wide regex cache size. + ("System.Text.RegularExpressions.Regex", "CacheSize"), + ("System.Text.RegularExpressions.Regex", "CompileToAssembly"), ]; - /// - /// Fully-qualified type names scripts are NOT allowed to reference, regardless of - /// namespace. Used when a dangerous type shares its namespace with legitimate types - /// (e.g. System.Runtime.CompilerServices hosts both MethodImplOptions and - /// RuntimeHelpers) so a namespace-prefix rule would over-block. Matched by exact - /// fully-qualified name against the resolved type symbol — every member of - /// the type (including read-only ones) is therefore rejected. - /// - /// - /// - /// System.Environment — Exit / FailFast terminate - /// the host process; the whole type is denied (the read members have no - /// legitimate SCADA-predicate use either). - /// System.AppDomain — process-wide assembly-load / - /// unhandled-exception control. - /// System.GC — Collect / AddMemoryPressure perturb - /// the process memory subsystem. - /// System.Activator — CreateInstance is a - /// reflection-equivalent escape that constructs a forbidden type by name - /// without ever naming it syntactically. - /// System.Runtime.CompilerServices.Unsafe — exposes raw type- - /// reinterpretation (As<TFrom,TTo>, As<T>(object)) - /// that bypasses the CLR type system without requiring an unsafe context at - /// the call site; enables type-confusion and managed heap corruption. - /// System.Runtime.CompilerServices.RuntimeHelpers — - /// GetUninitializedObject constructs an instance of any type (a forbidden - /// one included) with no constructor and no syntactic type name beyond a - /// Type value; PrepareMethod / RunClassConstructor reach - /// runtime internals. - /// - /// - /// System.Threading.Thread / ThreadPool / Timer used to be listed - /// here; since the whole System.Threading namespace is denied (with a type-granular - /// allow-list, see ) the prefix rule reaches - /// them first. - /// - /// - public static readonly IReadOnlyList ForbiddenFullTypeNames = - [ - "System.Environment", - "System.AppDomain", - "System.GC", - "System.Activator", - // System.Runtime.CompilerServices.Unsafe exposes raw type-reinterpretation - // (Unsafe.As, Unsafe.As(object)) that bypasses the CLR type system - // without requiring an 'unsafe' compilation context at the call site. In a script, - // calling Unsafe.As(someObject) can corrupt managed heap references and - // cause type-confusion in downstream virtual-tag consumers. Type-granular (not - // namespace-prefix) because System.Runtime.CompilerServices also contains harmless - // compile-time-only types (CallerMemberNameAttribute, MethodImplAttribute, - // MethodImplOptions) that scripts may legitimately reference. - "System.Runtime.CompilerServices.Unsafe", - // RuntimeHelpers.GetUninitializedObject(Type) builds an instance of ANY type — a - // forbidden one obtained through Type.GetType (itself denied via ForbiddenMembers) - // included — without a constructor or a syntactic type name. Same namespace caveat - // as Unsafe above, so type-granular. - "System.Runtime.CompilerServices.RuntimeHelpers", - // lmxopcua#792 — process-wide runtime configuration. System.AppContext.SetSwitch / SetData flip - // BCL compatibility switches (serialization, networking, globalization) for the whole process and - // GetData / BaseDirectory leak the host's install path and TRUSTED_PLATFORM_ASSEMBLIES. The whole - // type is denied (same class as Environment / AppDomain, which are already denied); TryGetSwitch is - // read-only but has no script use either. - "System.AppContext", - // Console.SetOut / SetError / SetIn / Out / Write* replace or write the process's standard streams — - // in the ScriptWorker stdout/stderr belong to the launcher, in the host they belong to the service - // log capture. Scripts log through ctx.Logger. - "System.Console", - // GCSettings.LatencyMode / LargeObjectHeapCompactionMode are process-wide GC tuning knobs. - "System.Runtime.GCSettings", - // ProfileOptimization.SetProfileRoot / StartProfile redirect the JIT profile root (a file-writing, - // process-wide setting). - "System.Runtime.ProfileOptimization", - // EncodingProvider registration is process-wide (Encoding.RegisterProvider takes an EncodingProvider). - "System.Text.EncodingProvider", - "System.Text.CodePagesEncodingProvider", - // TypeDescriptor.AddProvider / AddAttributes change type metadata for the whole process, and - // CreateInstance builds a type by name. - "System.ComponentModel.TypeDescriptor", - // CryptoConfig.AddAlgorithm / AddOID mutate the process-wide algorithm map, and CreateFromName builds - // a type by name (an Activator-equivalent). - "System.Security.Cryptography.CryptoConfig", - ]; + private const string ScriptContextFullName = "ZB.MOM.WW.OtOpcUa.Core.Scripting.ScriptContext"; + private const string ExceptionFullName = "System.Exception"; + + private static readonly HashSet AllowedNamespaceSet = new(AllowedNamespaces, StringComparer.Ordinal); + private static readonly HashSet AllowedTypeSet = new(AllowedTypes, StringComparer.Ordinal); + private static readonly HashSet<(string, string)> AllowedMemberSet = new(AllowedMembers); + private static readonly HashSet<(string, string)> ForbiddenMemberSet = new(ForbiddenMembers); /// - /// Scan the for references to forbidden types. - /// Returns empty list when the script is clean; non-empty list means the script - /// must be rejected at publish with the rejections surfaced to the operator. + /// Scan the for anything outside the allow-list. Returns an empty list when the + /// script is clean; a non-empty list means the script must be rejected at publish (and is marked in the + /// editor), one entry per offending reference. /// - /// The compilation to analyze. - /// A list of forbidden type rejections, or empty if the script is clean. + /// The compilation to analyze (the synthesized CompiledScript.Run wrapper). + /// The rejections, or empty if the script is clean. /// - /// - /// The walker has two passes per node. Pass (1) is the member / call surface: - /// ObjectCreationExpressionSyntax, InvocationExpressionSyntax with - /// a member-access target, MemberAccessExpressionSyntax, and bare - /// IdentifierNameSyntax are resolved via - /// .GetSymbolInfo. This catches static calls - /// (System.IO.File.ReadAllText) and constructors, and is deliberately - /// narrow: resolving GetSymbolInfo on every node would flag - /// harmless inherited members (e.g. typeof(int).Name resolves - /// Name to System.Reflection.MemberInfo, the base type that - /// declares it, even though the receiver type System.Type is allowed). - /// - /// - /// Pass (2) resolves the type of every - /// TypeSyntax node via GetTypeInfo. The old walker only inspected - /// the four node kinds above, so a forbidden type named through - /// typeof(System.IO.File), a generic argument - /// (List<System.IO.FileInfo>), a cast - /// ((System.IO.Stream)null), an is / as type pattern, - /// default(System.Reflection.Assembly), an array-creation element type, - /// or an explicitly-typed local declaration produced no examined node and so - /// slipped through. Every TypeSyntax resolves to a concrete - /// ; generic type arguments and array element types - /// are unwrapped recursively so a forbidden type nested at any depth is caught. - /// + /// The wrapper's own header — using directives, the namespace, and the Run method's return and + /// parameter types (chosen by the host, e.g. ScriptGlobals<VirtualTagContext>) — is not + /// analyzed; everything else in the tree is, including the wrapper's var ctx = globals.ctx; and any + /// member a malformed source manages to inject (the publish gate separately refuses injection, LMX001/002). /// public static IReadOnlyList Analyze(Compilation compilation) { @@ -268,179 +213,268 @@ public static class ForbiddenTypeAnalyzer foreach (var tree in compilation.SyntaxTrees) { var semantic = compilation.GetSemanticModel(tree); + var walker = new Walker(compilation, semantic, rejections); var root = tree.GetRoot(); - foreach (var node in root.DescendantNodes()) + var trusted = TrustedWrapperSpans(root); + foreach (var node in root.DescendantNodes(n => !trusted.Any(s => s.Contains(n.Span)))) { - // Pass (1) — member / call surface. Narrowly targeted at the node kinds - // that name a callable member or constructor, so inherited-member - // resolution does not produce false positives. - switch (node) - { - case ObjectCreationExpressionSyntax obj: - CheckSymbol(semantic.GetSymbolInfo(obj.Type).Symbol, obj.Type.Span, rejections); - break; - case InvocationExpressionSyntax inv when inv.Expression is MemberAccessExpressionSyntax memberAcc: - CheckSymbol(semantic.GetSymbolInfo(memberAcc.Expression).Symbol, memberAcc.Expression.Span, rejections); - CheckSymbol(semantic.GetSymbolInfo(inv).Symbol, inv.Span, rejections); - break; - case MemberAccessExpressionSyntax mem: - // Catches static calls like System.IO.File.ReadAllText(...) — the - // MemberAccess "System.IO.File" resolves to the File type symbol - // whose containing namespace is System.IO, triggering a rejection. - CheckSymbol(semantic.GetSymbolInfo(mem.Expression).Symbol, mem.Expression.Span, rejections); - // The accessed member itself: a property such as CultureInfo.DefaultThreadCurrentCulture is - // never an invocation, so the member deny-list must run here (member-only — resolving the - // type of an inherited member would flag harmless reads, see the class remarks). - var accessed = semantic.GetSymbolInfo(mem).Symbol; - TryRejectMember(accessed, mem.Span, accessed?.ContainingNamespace?.ToDisplayString() ?? string.Empty, rejections); - break; - case IdentifierNameSyntax id when node.Parent is not MemberAccessExpressionSyntax: - CheckSymbol(semantic.GetSymbolInfo(id).Symbol, id.Span, rejections); - break; - } - - // Pass (2) — type-reference surface. Every TypeSyntax - // resolves to the type it names, regardless of the syntactic form that - // introduced it (typeof operand, cast type, generic argument, default(T) - // operand, array element type, is/as pattern type, declared local type). - // Type arguments and array element types are walked recursively. - if (node is TypeSyntax) - CheckTypeSymbol(semantic.GetTypeInfo(node).Type, node.Span, rejections); + if (trusted.Any(s => s.Contains(node.Span))) continue; + walker.Visit(node); } } return rejections; } - /// - /// Reject if it (or, recursively, any of its generic type - /// arguments / array element types) is forbidden. Walks the full type tree so a - /// forbidden type nested inside an allowed generic — e.g. - /// List<System.IO.FileInfo> — is still caught. - /// - private static void CheckTypeSymbol(ITypeSymbol? type, TextSpan span, List rejections) + /// The wrapper header spans the host writes (see 's remarks). + private static List TrustedWrapperSpans(SyntaxNode root) { - if (type is null) return; - - CheckSymbol(type, span, rejections); - - switch (type) + var spans = new List(); + var runSeen = false; + foreach (var node in root.DescendantNodes(n => n is CompilationUnitSyntax or BaseNamespaceDeclarationSyntax or TypeDeclarationSyntax)) { - case IArrayTypeSymbol array: - CheckTypeSymbol(array.ElementType, span, rejections); - break; - case INamedTypeSymbol named: - foreach (var arg in named.TypeArguments) - CheckTypeSymbol(arg, span, rejections); - break; + switch (node) + { + case UsingDirectiveSyntax u: + spans.Add(u.Span); + break; + case BaseNamespaceDeclarationSyntax ns: + spans.Add(ns.Name.Span); + break; + // Only the FIRST Run — the wrapper's own, which precedes the user source. A second one can only be + // injected by the source (refused at publish as LMX001/002, but the editor analyses it as written). + case MethodDeclarationSyntax { Identifier.ValueText: "Run", Parent: ClassDeclarationSyntax { Identifier.ValueText: "CompiledScript" } } run + when !runSeen: + runSeen = true; + spans.Add(run.ReturnType.Span); + spans.Add(run.ParameterList.Span); + break; + } } + return spans; } /// - /// Member deny-list check on its own (no type / namespace rule): rejects a method or property whose declaring - /// type and name are listed in . Exact declaring-type match, so an inherited - /// harmless member is never flagged. + /// Syntax refused regardless of binding: the undocumented TypedReference keywords, lock (a + /// blocking monitor on an object that may be shared with the host, e.g. lock (typeof(string))), and + /// extern local functions (a native entry point). /// - private static bool TryRejectMember(ISymbol? symbol, TextSpan span, string ns, List rejections) + /// The node. + /// A description of the construct, or null when the node is allowed. + internal static string? IsForbiddenSyntax(SyntaxNode node) => node switch { - if (symbol is not (IMethodSymbol or IPropertySymbol)) return false; + MakeRefExpressionSyntax => "__makeref", + RefValueExpressionSyntax => "__refvalue", + RefTypeExpressionSyntax => "__reftype", + ExpressionSyntax e when e.IsKind(SyntaxKind.ArgListExpression) => "__arglist", + LockStatementSyntax => "lock", + LocalFunctionStatementSyntax f when f.Modifiers.Any(SyntaxKind.ExternKeyword) => "extern local function", + _ => null, + }; - var declaring = symbol.ContainingType.OriginalDefinition.ToDisplayString( - SymbolDisplayFormat.FullyQualifiedFormat.WithGlobalNamespaceStyle( - SymbolDisplayGlobalNamespaceStyle.Omitted)); - foreach (var (type, member) in ForbiddenMembers) + private sealed class Walker(Compilation compilation, SemanticModel semantic, List rejections) + { + public void Visit(SyntaxNode node) { - if (declaring != type || symbol.Name != member) continue; - if (rejections.Any(r => r.Span == span && r.TypeName == $"{type}.{member}")) return true; - rejections.Add(new ForbiddenTypeRejection( - Span: span, - TypeName: $"{type}.{member}", - Namespace: ns, - Message: $"Member '{type}.{member}' is on the sandbox forbidden-member deny-list: " + - "it obtains a type or member by name or changes process-wide state, which bypasses the sandbox " + - "(see ForbiddenTypeAnalyzer.ForbiddenMembers for the authoritative list).")); - return true; + if (IsForbiddenSyntax(node) is { } construct) + { + Add(node.Span, construct, string.Empty, + $"'{construct}' is not allowed in a script (sandbox: see ForbiddenTypeAnalyzer.IsForbiddenSyntax)."); + return; + } + + // Members the compiler calls with no name in the source: query-clause operators, foreach's + // GetEnumerator / MoveNext / Current, and a deconstruction's Deconstruct. + switch (node) + { + case QueryClauseSyntax clause: + var clauseInfo = semantic.GetQueryClauseInfo(clause); + CheckOptional(clauseInfo.OperationInfo.Symbol, clause.Span); + CheckOptional(clauseInfo.CastInfo.Symbol, clause.Span); + return; + case SelectOrGroupClauseSyntax selectOrGroup: + CheckOptional(semantic.GetSymbolInfo(selectOrGroup).Symbol, selectOrGroup.Span); + return; + case CommonForEachStatementSyntax forEach: + var forEachInfo = semantic.GetForEachStatementInfo(forEach); + CheckOptional(forEachInfo.GetEnumeratorMethod, forEach.Expression.Span); + CheckOptional(forEachInfo.MoveNextMethod, forEach.Expression.Span); + CheckOptional(forEachInfo.CurrentProperty, forEach.Expression.Span); + return; + } + if (node is AssignmentExpressionSyntax { Left: TupleExpressionSyntax or DeclarationExpressionSyntax } deconstruction) + CheckDeconstruction(semantic.GetDeconstructionInfo(deconstruction), deconstruction.Span); + + // Every expression — names, member accesses, invocations, object creations, element accesses, + // operators, and every TypeSyntax (TypeSyntax is an ExpressionSyntax) — is resolved twice: the symbol it + // binds to, and the type it evaluates / converts to. + if (node is not ExpressionSyntax expr) return; + + var symbol = semantic.GetSymbolInfo(expr).Symbol; + if (symbol is not null) CheckSymbol(symbol, expr.Span); + + var typeInfo = semantic.GetTypeInfo(expr); + CheckType(typeInfo.Type, expr.Span); + if (!SymbolEqualityComparer.Default.Equals(typeInfo.Type, typeInfo.ConvertedType)) + CheckType(typeInfo.ConvertedType, expr.Span); } + + private void CheckOptional(ISymbol? symbol, TextSpan span) + { + if (symbol is not null) CheckSymbol(symbol, span); + } + + private void CheckDeconstruction(DeconstructionInfo info, TextSpan span) + { + CheckOptional(info.Method, span); + foreach (var nested in info.Nested) CheckDeconstruction(nested, span); + } + + private void CheckSymbol(ISymbol symbol, TextSpan span) + { + switch (symbol) + { + case ITypeSymbol type: + CheckType(type, span); + break; + case IMethodSymbol method: + if (method.MethodKind is MethodKind.LocalFunction or MethodKind.AnonymousFunction) + { + // Script-declared; its signature types are checked where they are written. + foreach (var arg in method.TypeArguments) CheckType(arg, span); + break; + } + CheckMember(method.ReducedFrom ?? method, span); + foreach (var arg in method.TypeArguments) CheckType(arg, span); + if (!method.ReturnsVoid) CheckType(method.ReturnType, span); + break; + case IPropertySymbol property: + CheckMember(property, span); + CheckType(property.Type, span); + break; + case IFieldSymbol field: + CheckMember(field, span); + CheckType(field.Type, span); + break; + case IEventSymbol evt: + CheckMember(evt, span); + CheckType(evt.Type, span); + break; + // Locals, parameters, range variables, labels, namespaces, aliases, discards: nothing to check — + // their types come from a checked declaration or expression. + } + } + + private void CheckMember(ISymbol member, TextSpan span) + { + var declaring = member.ContainingType; + if (declaring is null || IsSourceSymbol(declaring)) return; + + var declaringName = TypeKey(declaring.OriginalDefinition); + var name = member.Name; + var pair = (declaringName, name); + var display = $"{declaringName}.{name}"; + var ns = declaring.ContainingNamespace?.ToDisplayString() ?? string.Empty; + + if (ForbiddenMemberSet.Contains(pair)) + { + Add(span, display, ns, + $"Member '{display}' is on the sandbox forbidden-member list: it changes process-wide state " + + "(see ForbiddenTypeAnalyzer.ForbiddenMembers)."); + return; + } + if (AllowedMemberSet.Contains(pair)) return; + + if (RestrictedTypeMembers.TryGetValue(declaringName, out var allowedNames)) + { + if (!allowedNames.Contains(name, StringComparer.Ordinal)) + Add(span, display, ns, + $"Member '{display}' is not on the script sandbox allow-list: only " + + $"{string.Join(", ", allowedNames)} may be used on '{declaringName}' " + + "(see ForbiddenTypeAnalyzer.RestrictedTypeMembers)."); + return; + } + + if (!IsTypeAllowedShallow(declaring)) + Add(span, display, ns, + $"Member '{display}' is declared on '{declaring.ToDisplayString()}', which is not on the script " + + "sandbox allow-list (see ForbiddenTypeAnalyzer.AllowedTypes)."); + } + + private void CheckType(ITypeSymbol? type, TextSpan span) + { + switch (type) + { + case null: + case IErrorTypeSymbol: + case ITypeParameterSymbol: + return; + case IArrayTypeSymbol array: + CheckType(array.ElementType, span); + return; + case IPointerTypeSymbol or IFunctionPointerTypeSymbol: + Add(span, type.ToDisplayString(), string.Empty, $"Pointer type '{type.ToDisplayString()}' is not allowed in a script."); + return; + case INamedTypeSymbol named: + if (!IsTypeAllowedShallow(named)) + { + var ns = named.ContainingNamespace?.ToDisplayString() ?? string.Empty; + Add(span, named.ToDisplayString(), ns, + $"Type '{named.ToDisplayString()}' is not on the script sandbox allow-list " + + "(see ForbiddenTypeAnalyzer.AllowedTypes / AllowedNamespaces)."); + return; + } + foreach (var arg in named.TypeArguments) CheckType(arg, span); + return; + default: + // dynamic and anything else unrecognised. + Add(span, type.ToDisplayString(), string.Empty, + $"Type '{type.ToDisplayString()}' is not on the script sandbox allow-list."); + return; + } + } + + private bool IsTypeAllowedShallow(INamedTypeSymbol type) + { + if (type.IsAnonymousType || IsSourceSymbol(type)) return true; + if (type.TypeKind == TypeKind.Dynamic) return false; + var def = type.OriginalDefinition; + if (def.ContainingType is { } outer) return IsTypeAllowedShallow(outer); + var key = TypeKey(def); + if (AllowedTypeSet.Contains(key) || RestrictedTypeMembers.ContainsKey(key)) return true; + var ns = def.ContainingNamespace?.ToDisplayString() ?? string.Empty; + if (AllowedNamespaceSet.Contains(ns)) return true; + if (ns == "System" && DerivesFrom(def, ExceptionFullName)) return true; + return DerivesFrom(def, ScriptContextFullName); + } + + private bool IsSourceSymbol(ISymbol symbol) + => SymbolEqualityComparer.Default.Equals(symbol.ContainingAssembly, compilation.Assembly); + + private void Add(TextSpan span, string typeName, string ns, string message) + { + if (rejections.Any(r => r.Span == span && r.TypeName == typeName)) return; + rejections.Add(new ForbiddenTypeRejection(span, typeName, ns, message)); + } + } + + private static bool DerivesFrom(INamedTypeSymbol type, string fullName) + { + for (var t = type; t is not null; t = t.BaseType) + if (TypeKey(t.OriginalDefinition) == fullName) return true; return false; } - private static void CheckSymbol(ISymbol? symbol, TextSpan span, List rejections) + /// Namespace.Name without generic arity; nested types as Outer.Inner. + private static string TypeKey(INamedTypeSymbol type) { - if (symbol is null) return; - - var typeSymbol = symbol switch - { - ITypeSymbol t => t, - IMethodSymbol m => m.ContainingType, - IPropertySymbol p => p.ContainingType, - IFieldSymbol f => f.ContainingType, - _ => null, - }; - if (typeSymbol is null) return; - - var typeName = typeSymbol.ToDisplayString(); - - // The broadened walk resolves both GetSymbolInfo and GetTypeInfo on every node, - // so the same forbidden reference can be hit several times. Dedupe on span + type - // so the operator sees one rejection per offending reference, not a noisy pile of - // identical messages. - if (rejections.Any(r => r.Span == span && r.TypeName == typeName)) - return; - - // Full name of the (unwrapped) type — shared by the allow-list, the type deny-list and the - // member deny-list below. OriginalDefinition unwraps any generic construction before naming. - var fullTypeName = typeSymbol.OriginalDefinition.ToDisplayString( - SymbolDisplayFormat.FullyQualifiedFormat.WithGlobalNamespaceStyle( - SymbolDisplayGlobalNamespaceStyle.Omitted)); - - var ns = typeSymbol.ContainingNamespace?.ToDisplayString() ?? string.Empty; - - // Member deny-list first: the containing type (System.Type) is allowed, so neither list - // below would ever look at the member name. - if (TryRejectMember(symbol, span, ns, rejections)) - return; - - // A type on the allow-list stays reachable even though its namespace is denied; it is still - // subject to the type-granular deny-list below (nothing is on both today). - var allowListed = AllowedTypesInForbiddenNamespaces.Contains(fullTypeName, StringComparer.Ordinal); - - if (!allowListed) - { - foreach (var forbidden in ForbiddenNamespacePrefixes) - { - if (ns == forbidden || ns.StartsWith(forbidden + ".", StringComparison.Ordinal)) - { - rejections.Add(new ForbiddenTypeRejection( - Span: span, - TypeName: typeName, - Namespace: ns, - Message: $"Type '{typeName}' is in the forbidden namespace '{ns}'. " + - $"Scripts cannot reach {forbidden}* per Phase 7 sandbox rules.")); - return; - } - } - } - - // Type-granular deny-list — dangerous types that live in an allow-listed namespace - // (System, System.Runtime.CompilerServices) and so cannot be caught by - // ForbiddenNamespacePrefixes. - foreach (var forbiddenType in ForbiddenFullTypeNames) - { - if (fullTypeName == forbiddenType) - { - rejections.Add(new ForbiddenTypeRejection( - Span: span, - TypeName: typeSymbol.ToDisplayString(), - Namespace: ns, - Message: $"Type '{forbiddenType}' is on the Phase 7 sandbox forbidden-type " + - $"deny-list. Scripts cannot reach this type per sandbox rules " + - $"(see ForbiddenTypeAnalyzer.ForbiddenFullTypeNames for the authoritative list).")); - return; - } - } + var prefix = type.ContainingType is { } outer + ? TypeKey(outer.OriginalDefinition) + : type.ContainingNamespace is { IsGlobalNamespace: false } ns ? ns.ToDisplayString() : null; + return prefix is null ? type.Name : prefix + "." + type.Name; } } -/// A single forbidden-type reference in a user script. +/// A single reference in a user script that is outside the sandbox allow-list. public sealed record ForbiddenTypeRejection( TextSpan Span, string TypeName, @@ -448,7 +482,7 @@ public sealed record ForbiddenTypeRejection( string Message); /// Thrown from when the -/// post-compile forbidden-type analyzer finds references to denied namespaces. +/// post-compile finds references outside the sandbox allow-list. public sealed class ScriptSandboxViolationException : Exception { /// Gets the list of forbidden type rejections that triggered this exception. @@ -465,7 +499,7 @@ public sealed class ScriptSandboxViolationException : Exception private static string BuildMessage(IReadOnlyList rejections) { var lines = rejections.Select(r => $" - {r.Message}"); - return "Script references types outside the Phase 7 sandbox allow-list:\n" + return "Script references types or members outside the script sandbox allow-list:\n" + string.Join("\n", lines); } } diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptEvaluator.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptEvaluator.cs index 8d717b126..038b0334a 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptEvaluator.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptEvaluator.cs @@ -30,9 +30,9 @@ namespace ZB.MOM.WW.OtOpcUa.Core.Scripting; /// allow-list — catches syntax errors, unresolved /// types (the sandbox's first line of defense), and most type-resolution /// failures, throwing ; (2) -/// runs against the semantic model — catches -/// sandbox escapes that slipped past reference restrictions due to .NET's type -/// forwarding, throwing ; (3) emit +/// runs against the semantic model — the sandbox gate: every +/// symbol, expression type and member must be on its allow-list (lmxopcua#971), +/// else it throws ; (3) emit /// to an in-memory PE stream + load into the collectible ALC — throws at this /// layer only for internal Roslyn bugs, not user error. Between (2) and (3) the tree is rewritten to /// call on entry to every script-declared body, so unbounded @@ -128,8 +128,8 @@ public sealed class ScriptEvaluator : IDisposable if (compileErrors.Length > 0) throw new CompilationErrorException(compileErrors); - // Step 3 — forbidden-type semantic analysis. Defense-in-depth against - // reference-list leaks due to type forwarding. + // Step 3 — the sandbox gate: the allow-list analyzer (lmxopcua#971). The narrowed + // reference set in step 2 is only defence in depth (CoreLib alone carries File / Thread / Assembly). var rejections = ForbiddenTypeAnalyzer.Analyze(compilation); if (rejections.Count > 0) throw new ScriptSandboxViolationException(rejections); @@ -210,7 +210,7 @@ public sealed class ScriptEvaluator : IDisposable /// /// A digest of everything that decides what emits for a given source, other than /// the source itself (lmxopcua#780 design §7): the Roslyn version, this assembly's build identity (the - /// analyzer's deny-lists, the wrapper template, the stack-guard rewrite), the sandbox reference set, the + /// analyzer's allow-list, the wrapper template, the stack-guard rewrite), the sandbox reference set, the /// runtime version and / . A compiled-PE cache /// keys on it, so an analyzer or compiler change invalidates every cached image and a cached PE can never skip /// a newer sandbox rule. diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptSandbox.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptSandbox.cs index f0bbdc686..3b2900d80 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptSandbox.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptSandbox.cs @@ -4,22 +4,17 @@ using ZB.MOM.WW.OtOpcUa.Core.Abstractions; namespace ZB.MOM.WW.OtOpcUa.Core.Scripting; /// -/// Factory for the compile-time sandbox every user script is built against. -/// Enforces a read-only sandbox by whitelisting only the -/// assemblies + namespaces the script API needs; no System.IO, no -/// System.Net, no System.Diagnostics.Process, no -/// System.Reflection. Attempts to reference those types in a script fail at -/// compile with a compiler error that points at the exact span — the operator sees -/// the rejection before publish, not at evaluation. +/// Factory for the compile-time reference set every user script is built against: the OtOpcUa +/// assemblies the ctx API lives in plus the few BCL assemblies listed in +/// . An API outside that set fails to bind (a compiler error pointing at the +/// span); an API inside it that is not on the allow-list is rejected by +/// the analyzer. Either way the operator sees the rejection before publish, not at evaluation. /// /// /// -/// Roslyn would otherwise pull in every type in the BCL transitively via -/// mscorlib / System.Runtime — this class overrides that with an -/// explicit minimal allow-list. The list is the same regardless of whether -/// uses the legacy -/// CSharpScript path or the collectible-AssemblyLoadContext path: -/// both go through . +/// The analyzer is the gate; this reference set is defence in depth (lmxopcua#971). The same set is used by +/// the publish gate () and by the AdminUI script editor, so +/// the editor's completions and diagnostics cover exactly what publish compiles. /// /// /// Namespaces pre-imported so scripts don't have to write using clauses: @@ -70,16 +65,12 @@ public static class ScriptSandbox contextType.Assembly, }; - // BCL references. We list the trusted-platform-assemblies set restricted to - // System.* and netstandard so the synthesized wrapper can reference every BCL - // type by FQN — including the ones we forbid (HttpClient, File, Process, - // Registry, etc.). Letting those types resolve at compile is intentional: the - // hard security gate is ForbiddenTypeAnalyzer in step 3 of the compile pipeline - // (the analyzer must be the sole gate because type forwarding makes any - // references-list-only restriction porous). - // The references list now serves only as scoping hygiene — out-of-band BCL - // surface (operator-authored hosting helpers, third-party packages, app code) - // is not on the list and stays unreachable. + // BCL references (lmxopcua#971): only BclAssemblyNames — the handful of assemblies the + // ForbiddenTypeAnalyzer allow-list draws from — so most unlisted BCL surface (System.Xml*, + // System.Formats.*, System.Net.*, System.Linq.Expressions, System.ComponentModel*, System.Security.*, + // System.Console, Process) does not bind at all. Defence in depth, NOT the gate: System.Private.CoreLib + // alone carries File, Thread, Assembly and Environment, so ForbiddenTypeAnalyzer stays the authority on + // what a script may name. var references = new List(); // both halves are cached. CreateFromFile reads + maps the DLL, and the BCL half is ~170 // assemblies, so doing it per compile was the dominant fixed cost of every ScriptEvaluator build. @@ -123,35 +114,39 @@ public static class ScriptSandbox static () => EnumerateBclAssemblyPaths().Select(static p => (MetadataReference)MetadataReference.CreateFromFile(p)).ToArray(), LazyThreadSafetyMode.ExecutionAndPublication); + /// + /// The BCL assemblies a script is compiled against: the ones holding the types on + /// , plus the facades the pinned assemblies' own metadata binds + /// through. Every other BCL assembly is left out, so its types do not bind at all (lmxopcua#971). + /// + public static readonly IReadOnlyList BclAssemblyNames = + [ + "System.Private.CoreLib.dll", // primitives, Math, String, DateTime, List/Dictionary, CultureInfo, … + "System.Runtime.dll", // the reference facade every pinned assembly binds through + "netstandard.dll", // facade for netstandard-built dependencies + "System.Collections.dll", // SortedDictionary, LinkedList, Stack, Queue, PriorityQueue, … + "System.Collections.NonGeneric.dll", // the rest of System.Collections + "System.ObjectModel.dll", // System.Collections.ObjectModel + "System.Linq.dll", // System.Linq.Enumerable + "System.Text.RegularExpressions.dll", + ]; + private static IEnumerable EnumerateBclAssemblyPaths() { - // The .NET host advertises the resolved runtime-shared-framework + BCL DLL set - // via the TRUSTED_PLATFORM_ASSEMBLIES AppContext data slot. This is what the - // ALC fallback uses when resolving assemblies, so anything in here is already - // loadable by the host process. We restrict to System.* and netstandard to keep - // the script's reachable surface to the BCL — anything else (Microsoft.*, - // application code, third-party packages happening to be in the runtime store) - // would expand the analyzer's deny-list job unnecessarily. + // The .NET host advertises the resolved runtime-shared-framework + BCL DLL set via the + // TRUSTED_PLATFORM_ASSEMBLIES AppContext data slot; the listed files are picked out of it. var raw = (string?)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES"); if (string.IsNullOrEmpty(raw)) yield break; var separator = OperatingSystem.IsWindows() ? ';' : ':'; + var seen = new HashSet(StringComparer.Ordinal); foreach (var path in raw.Split(separator, StringSplitOptions.RemoveEmptyEntries)) { + // A host can list the same file twice (the test host lists System.Private.CoreLib twice); first wins. var name = System.IO.Path.GetFileName(path); - if (name.StartsWith("System.", StringComparison.Ordinal) || - string.Equals(name, "netstandard.dll", StringComparison.Ordinal) || - string.Equals(name, "mscorlib.dll", StringComparison.Ordinal) || - // Microsoft.Win32.Registry isn't a System.* DLL but the analyzer's - // Microsoft.Win32 deny-list relies on the type being resolvable so it - // can identify + reject it. Add the one - // DLL we need rather than broadening to Microsoft.* (which would also - // pull in compilers, build tooling, etc.). - string.Equals(name, "Microsoft.Win32.Registry.dll", StringComparison.Ordinal)) - { + if (BclAssemblyNames.Contains(name, StringComparer.Ordinal) && seen.Add(name)) yield return path; - } } } } diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ForbiddenTypeAnalyzerTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ForbiddenTypeAnalyzerTests.cs new file mode 100644 index 000000000..9b6990d10 --- /dev/null +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ForbiddenTypeAnalyzerTests.cs @@ -0,0 +1,307 @@ +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.Scripting; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; + +namespace ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests; + +/// +/// lmxopcua#971 (review 2026-12-02 K-1): the sandbox used to be a deny-list over the whole BCL and every one of +/// the snippets below compiled and ran — reading and writing files, starting a process, reaching the certificate +/// store, starting background work and replacing the process-global logger. The analyzer is now an +/// allow-list: a script may name only the ctx API and an explicit set of value / collection / text +/// types, so each snippet is refused. +/// +/// +/// Each snippet is asserted twice. runs the real publish gate +/// (), where a snippet may now also fail to bind because +/// the narrowed reference set no longer carries its assembly. +/// compiles the same snippet against EVERY assembly the test host can load and asserts the analyzer on its own +/// rejects it — so the allow-list is the gate, and the narrowed reference set is defence in depth rather than the +/// thing doing the work. +/// +[Trait("Category", "Unit")] +public sealed class ForbiddenTypeAnalyzerTests +{ + /// The eight K-1 bypasses (the background-work row is three snippets) plus a few siblings. + public static TheoryData BypassSnippets => new() + { + // 1. Delegate.CreateDelegate binds Type.GetType by name, then File.ReadAllText on the returned type. + { "CreateDelegate-file-read", """ + var getType = (Func)Delegate.CreateDelegate(typeof(Func), typeof(Type), "GetType"); + var file = getType("System.IO.File"); + var read = (Func)Delegate.CreateDelegate(typeof(Func), file, "ReadAllText"); + return read("/etc/hosts"); + """ }, + // 2. System.Linq.Expressions: Type.GetType by name, then Process.Start, both compiled and invoked. + { "Expressions-process-start", """ + var name = System.Linq.Expressions.Expression.Constant("System.Diagnostics.Process, System.Diagnostics.Process"); + var getType = System.Linq.Expressions.Expression.Lambda>( + System.Linq.Expressions.Expression.Call(typeof(Type), "GetType", null, name)).Compile(); + var processType = getType(); + var start = System.Linq.Expressions.Expression.Lambda>( + System.Linq.Expressions.Expression.Call(processType, "Start", null, + System.Linq.Expressions.Expression.Constant("/usr/bin/true"))).Compile(); + return start(); + """ }, + // 3. XDocument.Load reads a path or fetches a URL. + { "XDocument-load", """return System.Xml.Linq.XDocument.Load("/etc/hosts").ToString();""" }, + // 4. XElement.Save writes a file. + { "XElement-save", """new System.Xml.Linq.XElement("a", "b").Save("/tmp/otopcua-k1.xml"); return 0;""" }, + // 5. TarFile archives a directory to a file. + { "TarFile-create", """System.Formats.Tar.TarFile.CreateFromDirectory("/tmp", "/tmp/otopcua-k1.tar", false); return 0;""" }, + // 6. The certificate store API. + { "X509Store", """return new System.Security.Cryptography.X509Certificates.X509Store().Name;""" }, + // 7. Background work that outlives the evaluation budget. + { "Timers-Timer", """var t = new System.Timers.Timer(50) { AutoReset = true }; t.Start(); return 0;""" }, + { "BackgroundWorker", """var w = new System.ComponentModel.BackgroundWorker(); w.RunWorkerAsync(); return 0;""" }, + { "AsParallel", """return Enumerable.Range(0, 100).AsParallel().Sum();""" }, + // 8. Replacing the process-global logger. + { "Serilog-Log-Logger", """Serilog.Log.Logger = Serilog.Core.Logger.None; return 0;""" }, + + // Siblings the deny-list also let through: reflection handles reached through an allowed type's member + // (System.Type.Assembly is a member of an allowed type, so no deny-listed name was ever written) ... + { "Type-Assembly-Location", """return typeof(int).Assembly.Location;""" }, + { "Type-Module", """return typeof(int).Module.Name;""" }, + // ... a reflection handle obtained from an exception, and a delegate's bound method ... + { "Exception-TargetSite", """var m = new Exception().TargetSite; return 0;""" }, + { "Delegate-Method", """Func f = () => 1; return f.Method.Name;""" }, + { "Delegate-DynamicInvoke", """Func f = () => 1; return f.DynamicInvoke();""" }, + // ... cancellation callbacks (run later, off the evaluation) ... + { "CancellationToken-Register", """ctx.CancellationToken.Register(() => { }); return 0;""" }, + // ... the host's own non-script API surface in Core.Abstractions ... + { "Host-credential-helper", """return ZB.MOM.WW.OtOpcUa.Core.Abstractions.CredentialFilePaths.ResolveWithin("a", "/etc", "f", "d");""" }, + // ... Queryable compiles expression trees. + { "AsQueryable", """return new[] { 1, 2 }.AsQueryable().Count();""" }, + // ... and the undocumented TypedReference keywords. + { "makeref", """int i = 1; var r = __makeref(i); return 0;""" }, + }; + + + /// Each bypass snippet is refused by the publish gate. + /// Row label. + /// The script body. + [Theory] + [MemberData(nameof(BypassSnippets))] + public void Bypass_snippet_is_refused_at_publish(string name, string source) + { + _ = name; + SandboxRefusal.Refuses(source); + } + + /// + /// With every loadable assembly referenced (so the snippet binds), the allow-list analyzer on its own + /// rejects it. + /// + /// Row label. + /// The script body. + [Theory] + [MemberData(nameof(BypassSnippets))] + public void Allow_list_alone_rejects_bypass_snippet(string name, string source) + { + _ = name; + SandboxRefusal.AnalyzerAloneRejects(source); + } + + /// + /// APIs the old deny-list named that now sit outside the narrowed reference set (so publish refuses them as a + /// compile error): the allow-list must still reject each one on its own. + /// + /// The script body. + [Theory] + [InlineData("""var c = new System.Net.Http.HttpClient(); return 0;""")] + [InlineData("""System.Diagnostics.Process.Start("cmd.exe"); return 0;""")] + [InlineData("""var t = typeof(System.Diagnostics.Process); return 0;""")] + [InlineData("""System.Net.Http.HttpClient c = null; return 0;""")] + [InlineData("""return System.IO.File.ReadAllText("/etc/hosts");""")] + [InlineData("""var s = new System.Net.Sockets.Socket(System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp); return 0;""")] + public void Allow_list_alone_rejects_previously_deny_listed_api(string source) + => SandboxRefusal.AnalyzerAloneRejects(source); + + /// + /// Positive control for the full-host theory: an ordinary script compiled the same way produces no + /// rejection, so the theory above cannot pass merely because the full-host compilation is rejected wholesale. + /// + [Fact] + public void Allow_list_accepts_ordinary_script_against_full_host() + { + var compilation = SandboxRefusal.CompileAgainstFullHost(""" + var v = ctx.GetTag("A"); + if (v.StatusCode != 0 || v.Value is null) return null; + var xs = new System.Collections.Generic.List { Convert.ToDouble(v.Value), 2.5 }; + ctx.Logger.Information("avg {Avg}", xs.Average()); + return Math.Round(xs.Where(x => x > 0).Sum(), 2).ToString(System.Globalization.CultureInfo.InvariantCulture); + """); + compilation.GetDiagnostics(TestContext.Current.CancellationToken).Where(d => d.Severity == DiagnosticSeverity.Error).ShouldBeEmpty(); + ForbiddenTypeAnalyzer.Analyze(compilation).ShouldBeEmpty(); + } + + /// A rejection names the type, and the message points at the allow-list. + [Fact] + public void Rejection_names_the_type_and_the_allow_list() + { + var ex = Should.Throw(() => + ScriptEvaluator.Compile("""return Delegate.CreateDelegate(typeof(Func), typeof(int), "x");""")); + ex.Rejections.ShouldContain(r => r.TypeName.StartsWith("System.Delegate", StringComparison.Ordinal)); + ex.Message.ShouldContain("allow-list"); + } + + /// + /// System.Type is usable as a value with a member allow-list: metadata reads work, the reflection + /// handles do not; the rejection names the member. + /// + [Fact] + public async Task Type_is_a_value_with_a_member_allow_list() + { + using var ok = ScriptEvaluator.Compile( + """object o = 1.5; var t = o.GetType(); return t == typeof(double) && t.IsValueType && t.Name == "Double" && t.FullName == "System.Double";"""); + (await ok.RunAsync(new FakeScriptContext(), TestContext.Current.CancellationToken)).ShouldBe(true); + + var ex = Should.Throw(() => + ScriptEvaluator.Compile("""return typeof(int).TypeHandle;""")); + ex.Rejections.ShouldContain(r => r.TypeName == "System.Type.TypeHandle"); + } + + /// + /// Every public type of every assembly in the sandbox reference set is either on the allow-list or rejected + /// when a script names it — and nothing from a namespace the K-1 review flagged is on the allow-list. + /// + [Fact] + public void Every_referenced_public_type_is_allowed_or_rejected_when_named() + { + var sandbox = ScriptSandbox.Build(typeof(FakeScriptContext)); + var probe = CSharpCompilation.Create("Probe", references: sandbox.References); + var types = new List(); + foreach (var reference in sandbox.References) + { + if (probe.GetAssemblyOrModuleSymbol(reference) is IAssemblySymbol asm) + Collect(asm.GlobalNamespace, types); + } + types.Count.ShouldBeGreaterThan(500); + + // One script naming every type by typeof, one statement per line; a rejection's line identifies the type. + var named = types + .Where(t => t.DeclaredAccessibility == Accessibility.Public && t.ContainingType is null) + .Where(t => !t.GetAttributes().Any(a => a.AttributeClass?.Name == "ObsoleteAttribute")) + .Select(t => t.IsGenericType + ? $"global::{t.ContainingNamespace.ToDisplayString()}.{t.Name}<{new string(',', t.Arity - 1)}>" + : $"global::{t.ToDisplayString()}") + .Distinct(StringComparer.Ordinal) + .ToArray(); + var body = string.Join("\n", named.Select(n => $"_ = typeof({n});")) + "\nreturn 0;"; + var compilation = SandboxRefusal.CompileAgainst(body, sandbox.References); + var tree = compilation.SyntaxTrees[0]; + var lineOfFirstStatement = tree.GetText(TestContext.Current.CancellationToken).Lines.IndexOf(tree.GetRoot(TestContext.Current.CancellationToken).DescendantNodes() + .OfType().First().SpanStart); + var rejectedLines = ForbiddenTypeAnalyzer.Analyze(compilation) + .Select(r => tree.GetText(TestContext.Current.CancellationToken).Lines.IndexOf(r.Span.Start) - lineOfFirstStatement) + .ToHashSet(); + var errorLines = compilation.GetDiagnostics(TestContext.Current.CancellationToken) + .Where(d => d.Severity == DiagnosticSeverity.Error) + .Select(d => tree.GetText(TestContext.Current.CancellationToken).Lines.IndexOf(d.Location.SourceSpan.Start) - lineOfFirstStatement) + .ToHashSet(); + + var allowed = new List(); + for (var i = 0; i < named.Length; i++) + { + if (rejectedLines.Contains(i) || errorLines.Contains(i)) continue; + allowed.Add(named[i]); + } + + // The allowed set is small and explainable; nothing from the flagged surface is in it. + string[] flagged = + [ + "global::System.IO.", "global::System.Net.", "global::System.Reflection.", "global::System.Diagnostics.", + "global::System.Linq.Expressions.", "global::System.Xml.", "global::System.Formats.", "global::System.Timers.", + "global::System.ComponentModel.", "global::System.Security.", "global::System.Runtime.InteropServices.", + "global::System.Runtime.Loader.", "global::System.Threading.Tasks.", "global::Serilog.Log", + "global::Serilog.LoggerConfiguration", "global::Serilog.Core.", "global::System.Delegate", + "global::System.Environment", "global::System.AppDomain", "global::System.AppContext", "global::System.GC", + "global::System.Activator", "global::System.Console", "global::System.Linq.ParallelEnumerable", + "global::System.Linq.Queryable", "global::System.Threading.Thread", "global::System.Threading.Timer", + "global::System.Threading.ThreadPool", "global::System.Runtime.CompilerServices.Unsafe", + "global::System.Runtime.CompilerServices.RuntimeHelpers", + ]; + allowed.Where(n => flagged.Any(f => f.EndsWith('.') ? n.StartsWith(f, StringComparison.Ordinal) : n == f || n.StartsWith(f + "<", StringComparison.Ordinal))).ShouldBeEmpty(); + allowed.Count.ShouldBeLessThan(named.Length / 2); + allowed.ShouldContain("global::System.Math"); + allowed.ShouldContain("global::System.Collections.Generic.List<>"); + } + + private static void Collect(INamespaceSymbol ns, List into) + { + into.AddRange(ns.GetTypeMembers()); + foreach (var child in ns.GetNamespaceMembers()) Collect(child, into); + } +} + +/// Shared assertions for "the sandbox refuses this script" (lmxopcua#971). +internal static class SandboxRefusal +{ + private static readonly Lazy FullHostReferences = new(() => + { + var tpa = ((string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")!) + .Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries); + var paths = new HashSet(tpa, StringComparer.Ordinal) + { + typeof(FakeScriptContext).Assembly.Location, + typeof(ScriptContext).Assembly.Location, + typeof(DataValueSnapshot).Assembly.Location, + typeof(Serilog.ILogger).Assembly.Location, + }; + return paths.Where(File.Exists).Select(p => (MetadataReference)MetadataReference.CreateFromFile(p)).ToArray(); + }); + + /// + /// The publish gate refuses : the analyzer rejected it, or (narrowed reference set) the + /// API no longer binds at all. Anything else — in particular no exception — is a sandbox bypass. + /// + /// The script body. + /// The refusal. + public static Exception Refuses(string source) + { + var ex = Should.Throw(() => ScriptEvaluator.Compile(source)); + (ex is ScriptSandboxViolationException or CompilationErrorException).ShouldBeTrue( + $"expected a sandbox / compile refusal, got {ex.GetType().Name}: {ex.Message}"); + return ex; + } + + /// + /// Compiled against every assembly the test host can load (so the snippet binds), the analyzer on its own + /// rejects . + /// + /// The script body. + public static void AnalyzerAloneRejects(string source) + { + var compilation = CompileAgainstFullHost(source); + compilation.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error).ShouldBeEmpty( + "the snippet must bind against the full host surface, or this proves nothing about the analyzer"); + ForbiddenTypeAnalyzer.Analyze(compilation).ShouldNotBeEmpty(); + } + + /// The script wrapped like the publish gate wraps it, compiled against the full host surface. + /// The script body. + /// The compilation. + public static CSharpCompilation CompileAgainstFullHost(string body) => CompileAgainst(body, FullHostReferences.Value); + + /// The script wrapped like the publish gate wraps it, compiled against . + /// The script body. + /// The references. + /// The compilation. + public static CSharpCompilation CompileAgainst(string body, IEnumerable references) + { + var source = + "using System;\nusing System.Linq;\nusing ZB.MOM.WW.OtOpcUa.Core.Abstractions;\nusing ZB.MOM.WW.OtOpcUa.Core.Scripting;\n" + + "namespace ZB.MOM.WW.OtOpcUa.Core.Scripting.Compiled;\n" + + "public static class CompiledScript\n{\n" + + " public static object? Run(global::ZB.MOM.WW.OtOpcUa.Core.Scripting.ScriptGlobals globals)\n {\n" + + " var ctx = globals.ctx;\n" + body + "\n }\n}\n"; + return CSharpCompilation.Create( + "Sandbox" + Guid.NewGuid().ToString("N"), + [CSharpSyntaxTree.ParseText(source)], + references, + new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, nullableContextOptions: NullableContextOptions.Enable)); + } +} diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScriptAllowListRegressionTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScriptAllowListRegressionTests.cs new file mode 100644 index 000000000..b17978029 --- /dev/null +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScriptAllowListRegressionTests.cs @@ -0,0 +1,193 @@ +using System.Text.RegularExpressions; +using Shouldly; +using Xunit; + +namespace ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests; + +/// +/// lmxopcua#971: inverting the sandbox to an allow-list must not break legitimate scripts. Two corpora are +/// compiled through the real publish gate: the script samples the repo ships (operator docs and the seed SQL the +/// smoke / gate rigs load), and a set of authoring idioms covering the BCL surface a SCADA predicate or +/// calculation reasonably uses. When the 2026-12-02 change landed, a differential run over every script-shaped +/// string literal in src/ and tests/ (511 that compiled before) found none that stopped compiling +/// apart from the one expression-tree test, which is intentional. +/// +[Trait("Category", "Unit")] +public sealed class ScriptAllowListRegressionTests +{ + /// Authoring idioms that must keep compiling (and running) under the allow-list. + public static TheoryData Idioms => new() + { + // Quality / timestamp branching on the ctx API. + """ + var v = ctx.GetTag("A"); + if (v.StatusCode != 0u || v.Value is null) return null; + var age = ctx.Now - (v.SourceTimestampUtc ?? ctx.Now); + return age > TimeSpan.FromMinutes(5) ? null : v.Value; + """, + // Numeric conversion, rounding, deadband, Math. + """ + var a = Convert.ToDouble(ctx.GetTag("A").Value ?? 0.0); + var b = Convert.ToDouble(ctx.GetTag("B").Value ?? 0.0); + if (!ScriptContext.Deadband(a, b, 0.5)) return null; + return Math.Round(Math.Sqrt(a * a + b * b), 2, MidpointRounding.AwayFromZero) + Math.Clamp(a, 0, 10) + Math.PI; + """, + // Culture-invariant formatting / parsing. + """ + var inv = System.Globalization.CultureInfo.InvariantCulture; + var ok = double.TryParse("1.5", System.Globalization.NumberStyles.Float, inv, out var d); + return ok ? d.ToString("F3", inv) + " " + DateTime.UtcNow.ToString("o", inv) + $" {d:0.00}" : ""; + """, + // Strings, StringBuilder, Regex, char. + """ + var sb = new System.Text.StringBuilder(); + foreach (var part in "a,b,,c".Split(',', StringSplitOptions.RemoveEmptyEntries)) sb.Append(part.ToUpperInvariant()).Append(';'); + var m = System.Text.RegularExpressions.Regex.Match("T-123", @"T-(\d+)"); + var n = m.Success ? int.Parse(m.Groups[1].Value) : 0; + return sb.ToString().Trim(';') + n + (char.IsDigit('7') ? "d" : "") + string.Join("|", new[] { "x", "y" }); + """, + // Collections + LINQ. + """ + var readings = new System.Collections.Generic.Dictionary { ["a"] = 1, ["b"] = 5, ["c"] = 3 }; + var set = new System.Collections.Generic.HashSet { 1, 2 }; + var q = new System.Collections.Generic.Queue(); q.Enqueue(1); + var top = readings.OrderByDescending(kv => kv.Value).Take(2).Select(kv => kv.Key).ToList(); + var groups = readings.GroupBy(kv => kv.Value > 2).ToDictionary(g => g.Key, g => g.Count()); + return top.Count + groups[true] + set.Count + q.Count + readings.Values.Average() + readings.Values.Max(); + """, + // Bits / bytes: register decoding. + """ + var raw = Convert.ToInt32(ctx.GetTag("HR").Value ?? 0); + var bytes = BitConverter.GetBytes((ushort)raw); + var be = System.Buffers.Binary.BinaryPrimitives.ReverseEndianness((ushort)raw); + return ((raw >> 3) & 1) == 1 || bytes.Length == 2 && be >= 0 && System.Numerics.BitOperations.PopCount((uint)raw) >= 0; + """, + // Pattern matching, switch, tuples, local functions, nullable, try/catch. + """ + object o = ctx.GetTag("S").Value; + static int Scale(int x) => x * 10; + var (lo, hi) = (1, 9); + int? maybe = o is int i ? Scale(i) : null; + try + { + return o switch { double dv when dv > hi => "high", double dv when dv < lo => "low", string s => s, _ => maybe?.ToString() ?? "none" }; + } + catch (InvalidCastException) { return "bad"; } + catch (Exception ex) { ctx.Logger.Warning(ex, "script failed for {Kind}", nameof(o)); return "err"; } + """, + // Time. + """ + var now = ctx.Now; + var shiftStart = now.Date.AddHours(now.Hour >= 6 && now.Hour < 18 ? 6 : 18); + var local = TimeZoneInfo.ConvertTimeFromUtc(now, TimeZoneInfo.Utc); + return (now - shiftStart).TotalMinutes + local.Minute + (now.DayOfWeek == DayOfWeek.Sunday ? 1 : 0) + DateTimeOffset.UtcNow.Offset.TotalHours; + """, + // Logging at levels, enums, type checks, cancellation polling, Interlocked. + """ + ctx.Logger.Information("tick {N}", 1); + if (ctx.Logger.IsEnabled(Serilog.Events.LogEventLevel.Debug)) ctx.Logger.Debug("dbg"); + var kind = Enum.Parse("Monday"); + var counter = 0; + for (var k = 0; k < 3 && !ctx.CancellationToken.IsCancellationRequested; k++) System.Threading.Interlocked.Increment(ref counter); + ctx.CancellationToken.ThrowIfCancellationRequested(); + object val = 1.0; + return val.GetType() == typeof(double) && kind == DayOfWeek.Monday ? counter : -1; + """, + // Arrays, Array helpers, Span, Guid, Random, HashCode. + """ + var arr = new[] { 3, 1, 2 }; + Array.Sort(arr); + Span span = arr; + var idx = Array.IndexOf(arr, 2); + return span[0] + idx + (Guid.Empty == Guid.Empty ? 1 : 0) + HashCode.Combine(1, 2) * 0 + Random.Shared.Next(1) + arr[^1]; + """, + // Query syntax, foreach, deconstruction (compiler-called members the analyzer also checks). + """ + var xs = new[] { 5, 1, 4 }; + var q = from x in xs where x > 1 orderby x group x by x % 2 into g select (Key: g.Key, Sum: g.Sum()); + var total = 0; + foreach (var (key, sum) in q) total += key + sum; + foreach (var kv in new System.Collections.Generic.Dictionary { ["a"] = 1 }) { var (k, v) = kv; total += v + k.Length; } + return total; + """, + // Writes. + """ + ctx.SetVirtualTag("Out", 42); + return true; + """, + }; + + /// Each idiom compiles through the publish gate and runs. + /// The script body. + [Theory] + [MemberData(nameof(Idioms))] + public async Task Idiom_compiles_and_runs(string source) + { + using var evaluator = ScriptEvaluator.Compile(source); + var ctx = new FakeScriptContext() + .Seed("A", 3.0).Seed("B", 4.0).Seed("HR", 8).Seed("S", 12.5); + _ = await evaluator.RunAsync(ctx, TestContext.Current.CancellationToken); + } + + /// Every script sample in the operator docs and the seed SQL compiles through the publish gate. + [Fact] + public void Shipped_script_samples_compile() + { + var samples = ShippedSamples().ToList(); + // Positive control: the extraction found the samples it is meant to find (ScriptEditor.md, FOCAS.md, the + // t13 seed SQL, the phase-7 smoke seed), so an empty corpus cannot pass vacuously. + samples.Count.ShouldBeGreaterThanOrEqualTo(6); + samples.ShouldContain(s => s.Origin.EndsWith("FOCAS.md", StringComparison.Ordinal)); + samples.ShouldContain(s => s.Origin.EndsWith("seed-phase-7-smoke.sql", StringComparison.Ordinal)); + + var failures = new List(); + foreach (var (origin, source) in samples) + { + try { ScriptEvaluator.CompileToImage(source); } + catch (Exception ex) when (ex is ScriptSandboxViolationException or CompilationErrorException) + { + failures.Add($"{origin}: {ex.Message}\n{source}"); + } + } + failures.ShouldBeEmpty(); + } + + private static IEnumerable<(string Origin, string Source)> ShippedSamples() + { + var root = RepoRoot(); + // Operator-facing docs (not docs/plans — design notes quote non-script C# freely). + foreach (var file in Directory.EnumerateFiles(Path.Combine(root, "docs"), "*.md", SearchOption.TopDirectoryOnly) + .Concat(Directory.EnumerateFiles(Path.Combine(root, "docs", "drivers"), "*.md"))) + { + foreach (Match m in Regex.Matches(File.ReadAllText(file), @"```(?:csharp|cs|c#)\s*\n(.*?)```", RegexOptions.Singleline)) + { + if (m.Groups[1].Value.Contains("ctx.", StringComparison.Ordinal)) + yield return (Path.GetRelativePath(root, file), m.Groups[1].Value); + } + } + + // Scripts seeded into ConfigDb by the smoke / gate rigs: N'…' literals carrying a ctx. call and a return. + var sqlFiles = Directory.EnumerateFiles(Path.Combine(root, "scripts"), "*.sql", SearchOption.AllDirectories) + .Concat(Directory.EnumerateFiles(Path.Combine(root, "docs"), "*.sql", SearchOption.AllDirectories)); + foreach (var file in sqlFiles) + { + // Splice T-SQL concatenation (N'…("' + @RawPath + N'")…') back into one literal. + var text = Regex.Replace(File.ReadAllText(file), @"'\s*\+\s*@\w+\s*\+\s*N'", "Plant/Driver/Dev/Tag"); + foreach (Match m in Regex.Matches(text, @"N'((?:[^']|'')*)'")) + { + var value = m.Groups[1].Value.Replace("''", "'", StringComparison.Ordinal); + if (value.Contains("ctx.", StringComparison.Ordinal) && Regex.IsMatch(value, @"\breturn\b")) + yield return (Path.GetRelativePath(root, file), value); + } + } + } + + private static string RepoRoot() + { + for (var dir = new DirectoryInfo(AppContext.BaseDirectory); dir is not null; dir = dir.Parent) + { + if (File.Exists(Path.Combine(dir.FullName, "docs", "ScriptEditor.md"))) return dir.FullName; + } + throw new InvalidOperationException("repository root (docs/ScriptEditor.md) not found above " + AppContext.BaseDirectory); + } +} diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScriptSandboxBuildTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScriptSandboxBuildTests.cs index 5231af8b7..1d9f58f06 100644 --- a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScriptSandboxBuildTests.cs +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScriptSandboxBuildTests.cs @@ -66,9 +66,33 @@ public sealed class ScriptSandboxBuildTests var first = ScriptSandbox.Build(typeof(ScriptContext)); var second = ScriptSandbox.Build(typeof(ScriptContext)); - first.References.Count.ShouldBeGreaterThan(50); + first.References.Count.ShouldBeGreaterThan(ScriptSandbox.BclAssemblyNames.Count); first.References.Count.ShouldBe(second.References.Count); for (var i = 0; i < first.References.Count; i++) ReferenceEquals(first.References[i], second.References[i]).ShouldBeTrue($"reference {i} was rebuilt"); } + + /// + /// lmxopcua#971: the BCL half of the reference set is exactly — every + /// listed assembly is found, and nothing carrying I/O, networking, XML, archives, expression trees, component + /// model, crypto, the console or processes is referenced. + /// + [Fact] + public void Bcl_reference_set_is_the_narrow_listed_set() + { + var bcl = ScriptSandbox.ReferenceIdentities(typeof(ScriptContext)) + .Where(i => i.EndsWith(".dll", StringComparison.Ordinal)) + .Select(Path.GetFileName) + .ToArray(); + + bcl.Order(StringComparer.Ordinal).ShouldBe(ScriptSandbox.BclAssemblyNames.Order(StringComparer.Ordinal)); + string[] mustBeAbsent = + [ + "System.Xml.Linq.dll", "System.Private.Xml.dll", "System.Formats.Tar.dll", "System.Linq.Expressions.dll", + "System.ComponentModel.dll", "System.Security.Cryptography.dll", "System.Console.dll", + "System.Diagnostics.Process.dll", "System.Net.Http.dll", "System.IO.FileSystem.dll", "System.Linq.Parallel.dll", + "System.Linq.Queryable.dll", "Microsoft.Win32.Registry.dll", "mscorlib.dll", + ]; + bcl.ShouldNotContain(n => mustBeAbsent.Contains(n)); + } } diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScriptSandboxHardeningTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScriptSandboxHardeningTests.cs index 05da1e52a..76d79c826 100644 --- a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScriptSandboxHardeningTests.cs +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScriptSandboxHardeningTests.cs @@ -176,16 +176,18 @@ public sealed class ScriptSandboxHardeningTests [InlineData("System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture;")] public void Rejects_process_wide_mutators(string statement) { - var ex = Rejects(statement + " return 0;"); - ex.Rejections.ShouldNotBeEmpty(); - ex.Message.ShouldContain("sandbox"); + // Since lmxopcua#971 a type whose assembly is outside the narrowed reference set (Console, TypeDescriptor, + // CryptoConfig, CodePagesEncodingProvider) no longer binds, so the refusal can be the compiler's; the + // allow-list's own verdict on every one of them is pinned against the full host surface below. + SandboxRefusal.Refuses(statement + " return 0;"); + SandboxRefusal.AnalyzerAloneRejects(statement + " return 0;"); } [Fact] public void AppContext_rejection_names_the_type() { var ex = Rejects("System.AppContext.SetSwitch(\"a\", true); return 0;"); - ex.Rejections.ShouldContain(r => r.Message.Contains("System.AppContext") && r.Message.Contains("forbidden-type")); + ex.Rejections.ShouldContain(r => r.Message.Contains("System.AppContext") && r.Message.Contains("allow-list")); } [Fact] diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScriptSandboxTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScriptSandboxTests.cs index 2d6be6d9f..d3e83f29b 100644 --- a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScriptSandboxTests.cs +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScriptSandboxTests.cs @@ -67,24 +67,26 @@ public sealed class ScriptSandboxTests [Fact] public void Rejects_HttpClient_at_compile() { - Should.Throw(() => - ScriptEvaluator.Compile( - """ - var c = new System.Net.Http.HttpClient(); - return 0; - """)); + // lmxopcua#971: System.Net.Http is outside the narrowed reference set, so publish refuses it as a compile + // error; the allow-list's own verdict is pinned against the full host surface. + const string source = """ + var c = new System.Net.Http.HttpClient(); + return 0; + """; + SandboxRefusal.Refuses(source); + SandboxRefusal.AnalyzerAloneRejects(source); } /// Verifies that Process.Start is rejected at compile time. [Fact] public void Rejects_Process_Start_at_compile() { - Should.Throw(() => - ScriptEvaluator.Compile( - """ - System.Diagnostics.Process.Start("cmd.exe"); - return 0; - """)); + const string source = """ + System.Diagnostics.Process.Start("cmd.exe"); + return 0; + """; + SandboxRefusal.Refuses(source); + SandboxRefusal.AnalyzerAloneRejects(source); } /// Verifies that Assembly.Load is rejected at compile time. @@ -292,27 +294,26 @@ public sealed class ScriptSandboxTests { // An explicitly-typed local declaration 'System.Net.Http.HttpClient c;' names // a forbidden type with no construction or call. (Core.Scripting-002.) - Should.Throw(() => - ScriptEvaluator.Compile( - """ - System.Net.Http.HttpClient c = null; - return 0; - """)); + const string source = """ + System.Net.Http.HttpClient c = null; + return 0; + """; + SandboxRefusal.Refuses(source); + SandboxRefusal.AnalyzerAloneRejects(source); } /// Verifies that typeof a forbidden type inside Activator is rejected at compile time. [Fact] public void Rejects_typeof_forbidden_type_inside_Activator_at_compile() { - // Activator is already denied by ForbiddenFullTypeNames, but the typeof operand - // is independently a forbidden-type reference — confirm the typeof path catches + // The typeof operand is independently a forbidden-type reference — confirm the typeof path catches // it even when the Activator type itself were allowed. (Core.Scripting-002.) - Should.Throw(() => - ScriptEvaluator.Compile( - """ - var t = typeof(System.Diagnostics.Process); - return 0; - """)); + const string source = """ + var t = typeof(System.Diagnostics.Process); + return 0; + """; + SandboxRefusal.Refuses(source); + SandboxRefusal.AnalyzerAloneRejects(source); } /// Verifies that an allowed generic type argument still compiles. @@ -473,17 +474,17 @@ public sealed class ScriptSandboxTests { // Microsoft.Win32 provides registry access — not appropriate from a sandboxed // SCADA predicate. (Core.Scripting-010.) - Should.Throw(() => - ScriptEvaluator.Compile( - """ - var k = Microsoft.Win32.Registry.CurrentUser; - return 0; - """)); + const string source = """ + var k = Microsoft.Win32.Registry.CurrentUser; + return 0; + """; + SandboxRefusal.Refuses(source); + SandboxRefusal.AnalyzerAloneRejects(source); } // --- Core.Scripting-012: BCL refs broadened by -008/-016 re-exposed three vectors - // the original deny-list missed. Each is denied type-granularly in - // ForbiddenTypeAnalyzer.ForbiddenFullTypeNames; these tests pin the rejection. + // the original deny-list missed. None is on the ForbiddenTypeAnalyzer allow-list (lmxopcua#971); + // these tests pin the rejection. /// Verifies that ThreadPool.QueueUserWorkItem is rejected at compile time. [Fact] diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScriptStackGuardInjectionTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScriptStackGuardInjectionTests.cs index 2251fbfe6..7267ca684 100644 --- a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScriptStackGuardInjectionTests.cs +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScriptStackGuardInjectionTests.cs @@ -43,10 +43,28 @@ public sealed class ScriptStackGuardInjectionTests /// A lambda converted to an expression tree is left as it is (a block body is illegal there and an /// expression tree runs no script frame); rewriting it would turn a compiling script into an emit failure. + /// + /// Since lmxopcua#971 a script cannot write an expression tree at all (System.Linq.Expressions is off the + /// sandbox allow-list and out of the reference set — it was a by-name reflection escape), so the injector's + /// expression-tree carve-out is exercised directly on a compilation that references it. + /// [Fact] public void An_expression_tree_lambda_is_not_rewritten() { - Run("System.Linq.Expressions.Expression> e = x => x + 1; return (int)e.Body.NodeType;") - .ShouldBe((int)System.Linq.Expressions.ExpressionType.Add); + Should.Throw(() => ScriptEvaluator.Compile( + "System.Linq.Expressions.Expression> e = x => x + 1; return 0;")); + + var tree = Microsoft.CodeAnalysis.CSharp.CSharpSyntaxTree.ParseText( + "class C { static object Run() { System.Linq.Expressions.Expression> e = x => x + 1; return e; } }", + cancellationToken: TestContext.Current.CancellationToken); + var tpa = ((string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")!).Split(Path.PathSeparator); + var compilation = Microsoft.CodeAnalysis.CSharp.CSharpCompilation.Create( + "ExprTree", [tree], tpa.Select(p => Microsoft.CodeAnalysis.MetadataReference.CreateFromFile(p)), + new Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions(Microsoft.CodeAnalysis.OutputKind.DynamicallyLinkedLibrary)); + + var rewritten = ScriptStackGuardInjector.Inject(compilation, tree).GetRoot(TestContext.Current.CancellationToken).ToFullString(); + + rewritten.ShouldContain("e = x => x + 1;"); // the expression lambda is untouched + rewritten.Split("ScriptStackGuard.Check()").Length.ShouldBe(2); // only Run's body got the check } } diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ScriptAnalysis/DiagnoseTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ScriptAnalysis/DiagnoseTests.cs index 27c8679e3..5255dcd70 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ScriptAnalysis/DiagnoseTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ScriptAnalysis/DiagnoseTests.cs @@ -52,6 +52,55 @@ public sealed class DiagnoseTests public void Allow_listed_forms_are_not_flagged_in_the_editor(string code) => Diag(code).ShouldBeEmpty(); + // lmxopcua#971 (review 2026-12-02 K-1): the allow-list sandbox. Each bypass the old deny-list let through is now an + // error marker in the editor — OTSCRIPT_FORBIDDEN where the API still binds against the narrowed reference set, + // a compiler error where it no longer binds at all — and the editor's verdict matches the publish gate's. + [Theory] + [InlineData("""var g = (Func)Delegate.CreateDelegate(typeof(Func), typeof(Type), "GetType"); return 0;""", true)] + [InlineData("""Serilog.Log.Logger = Serilog.Core.Logger.None; return 0;""", true)] + [InlineData("""return typeof(int).Assembly.Location;""", true)] + [InlineData("""ctx.CancellationToken.Register(() => { }); return 0;""", true)] + [InlineData("""Func f = () => 1; return f.DynamicInvoke();""", true)] + [InlineData("""int i = 1; var r = __makeref(i); return 0;""", true)] + [InlineData("""return System.Xml.Linq.XDocument.Load("/etc/hosts").ToString();""", false)] + [InlineData("""System.Formats.Tar.TarFile.CreateFromDirectory("/tmp", "/tmp/x.tar", false); return 0;""", false)] + [InlineData("""var t = new System.Timers.Timer(50); t.Start(); return 0;""", false)] + [InlineData("""return Enumerable.Range(0, 100).AsParallel().Sum();""", false)] + [InlineData("""return new System.Security.Cryptography.X509Certificates.X509Store().Name;""", false)] + public void K1_bypass_is_an_error_marker_in_the_editor(string code, bool bindsAndIsForbidden) + { + var markers = Diag(code); + if (bindsAndIsForbidden) markers.ShouldContain(x => x.Code == "OTSCRIPT_FORBIDDEN" && x.Severity == 8); + else markers.ShouldContain(x => x.Severity == 8); + } + + // Editor ⇔ publish parity over both refused and accepted scripts: an error marker exactly when the publish gate + // (ScriptEvaluator over the same VirtualTagContext) refuses. + [Theory] + [InlineData("""var g = (Func)Delegate.CreateDelegate(typeof(Func), typeof(Type), "GetType"); return 0;""")] + [InlineData("""return typeof(int).Assembly.Location;""")] + [InlineData("""return System.Xml.Linq.XDocument.Load("/etc/hosts").ToString();""")] + [InlineData("""lock (typeof(string)) { } return 0;""")] + [InlineData("""return typeof(int).Name + System.Math.Round(1.25, 1).ToString(System.Globalization.CultureInfo.InvariantCulture);""")] + [InlineData("""var d = new System.Collections.Generic.Dictionary { ["a"] = 1 }; return d.Values.Sum();""")] + [InlineData("""return System.Text.RegularExpressions.Regex.IsMatch("T-1", @"T-\d") ? ctx.Now.Hour : 0;""")] + [InlineData("""ctx.Logger.Information("v {V}", ctx.GetTag("A").Value); return ctx.GetTag("A").StatusCode == 0u;""")] + public void Editor_and_publish_gate_agree(string code) + { + bool publishRefuses; + try + { + ZB.MOM.WW.OtOpcUa.Core.Scripting.ScriptEvaluator.CompileToImage(code); + publishRefuses = false; + } + catch (Exception ex) when (ex is ZB.MOM.WW.OtOpcUa.Core.Scripting.ScriptSandboxViolationException + or ZB.MOM.WW.OtOpcUa.Core.Scripting.CompilationErrorException) + { + publishRefuses = true; + } + Diag(code).Any(x => x.Severity == 8).ShouldBe(publishRefuses); + } + [Fact] public void Dynamic_tag_path_is_flagged() => Diag("""var p = "A"; return ctx.GetTag(p).Value;""") .ShouldContain(x => x.Message.Contains("literal"));