Merge #971: script sandbox is an allow-list; narrowed BCL reference set (K-1 closed)
This commit is contained in:
+17
-15
@@ -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
|
||||
|
||||
+21
-6
@@ -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<ScriptGlobals<TContext>, 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<int>`).
|
||||
|
||||
`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
|
||||
|
||||
@@ -1915,6 +1915,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.
|
||||
|
||||
@@ -6,259 +6,204 @@ using Microsoft.CodeAnalysis.Text;
|
||||
namespace ZB.MOM.WW.OtOpcUa.Core.Scripting;
|
||||
|
||||
/// <summary>
|
||||
/// Post-compile sandbox guard. <c>ScriptOptions</c> 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 <c>System.Net.Http.HttpClient</c> from being found if
|
||||
/// any transitive reference forwards to <c>System.Net.Http</c>. This analyzer walks
|
||||
/// the script's syntax tree after compile, uses the <see cref="SemanticModel"/> to
|
||||
/// resolve every type / member reference, and rejects any whose containing namespace
|
||||
/// matches a deny-list pattern.
|
||||
/// The script sandbox gate: an <em>allow-list</em> over every symbol a user script names. After the script
|
||||
/// compiles, the analyzer resolves every expression, type reference and invoked member through the
|
||||
/// <see cref="SemanticModel"/> and rejects anything that is not explicitly allowed. The publish gate
|
||||
/// (<see cref="ScriptEvaluator{TContext, TResult}.CompileToImage"/>) and the AdminUI Monaco editor's diagnostics
|
||||
/// both call <see cref="Analyze"/>, so the editor accepts exactly what publish accepts.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// Deny-list is the authoritative Phase 7 plan set, hardened since:
|
||||
/// <c>System.IO</c>, <c>System.Net</c>, <c>System.Diagnostics</c>,
|
||||
/// <c>System.Reflection</c>, <c>System.Threading.Tasks</c> and the whole of
|
||||
/// <c>System.Threading</c> (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; <c>CancellationToken</c> / <c>Interlocked</c> /
|
||||
/// <c>Volatile</c> are allow-listed back in), <c>System.Runtime.InteropServices</c>,
|
||||
/// <c>System.Runtime.Loader</c>, <c>Microsoft.Win32</c>; plus the member-granular
|
||||
/// <see cref="ForbiddenMembers"/> (<c>System.Type</c>'s reflection entry points).
|
||||
/// <b>Why an allow-list (lmxopcua#971, review 2026-12-02 K-1).</b> The analyzer used to be a deny-list of
|
||||
/// namespaces, types and <c>System.Type</c> members over the whole BCL. A deny-list over the BCL cannot be
|
||||
/// closed: <c>Delegate.CreateDelegate</c> and <c>System.Linq.Expressions</c> bound <c>Type.GetType</c> and
|
||||
/// <c>Process.Start</c> by name without naming either, <c>System.Xml.Linq</c> / <c>System.Formats.Tar</c>
|
||||
/// read and wrote files, <c>System.Timers</c> / <c>BackgroundWorker</c> / <c>AsParallel</c> started
|
||||
/// background work, and <c>Serilog.Log.Logger</c> 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.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Deny-list prefix match. <c>System.Net</c> catches <c>System.Net.Http</c>,
|
||||
/// <c>System.Net.Sockets</c>, <c>System.Net.NetworkInformation</c>, 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 <see cref="ScriptContext"/> surface, not by unlocking the namespace.
|
||||
/// <b>What a script may name.</b>
|
||||
/// <list type="bullet">
|
||||
/// <item>The <c>ctx</c> API — <see cref="ScriptContext"/> and its subclasses, <c>ScriptGlobals<T></c>,
|
||||
/// <c>DataValueSnapshot</c> / <c>DriverDataType</c>, and <c>Serilog.ILogger</c> (+ <c>LogEventLevel</c>)
|
||||
/// for <c>ctx.Logger</c>.</item>
|
||||
/// <item>Primitive and value types, <c>Math</c>, <c>Convert</c>, <c>BitConverter</c>, <c>string</c>,
|
||||
/// <c>DateTime</c>/<c>DateTimeOffset</c>/<c>TimeSpan</c>/<c>TimeZoneInfo</c>, tuples, delegates
|
||||
/// (<c>Func</c>/<c>Action</c>/…), <c>System.Exception</c> and its <c>System</c> subclasses — see
|
||||
/// <see cref="AllowedTypes"/>.</item>
|
||||
/// <item>The collection namespaces (<see cref="AllowedNamespaces"/>), LINQ-to-objects
|
||||
/// (<c>System.Linq.Enumerable</c> — not <c>ParallelEnumerable</c> or <c>Queryable</c>),
|
||||
/// <c>StringBuilder</c> / <c>Encoding</c>, <c>System.Text.RegularExpressions</c>, and the read-only
|
||||
/// formatting types of <c>System.Globalization</c>.</item>
|
||||
/// <item><c>System.Type</c> and <c>CancellationToken</c> as values, but only the members listed in
|
||||
/// <see cref="RestrictedTypeMembers"/> — <c>typeof(x).Name</c> works, <c>typeof(x).Assembly</c> does
|
||||
/// not.</item>
|
||||
/// </list>
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// A namespace-prefix deny-list is necessary but not sufficient: dangerous types
|
||||
/// such as <c>System.Environment</c>, <c>System.AppDomain</c>, <c>System.GC</c>,
|
||||
/// and <c>System.Activator</c> live <em>directly</em> in the <c>System</c>
|
||||
/// namespace inside <c>System.Private.CoreLib</c> — the same allow-listed assembly
|
||||
/// that supplies primitives (<c>int</c>, <c>string</c>, <c>Math</c>). They cannot
|
||||
/// be blocked by namespace because <c>System</c> itself must stay allowed. They
|
||||
/// are therefore denied <em>type-granularly</em> via
|
||||
/// <see cref="ForbiddenFullTypeNames"/>. <c>Environment.Exit</c> /
|
||||
/// <c>Environment.FailFast</c> kill the in-process OPC UA server outright;
|
||||
/// <c>Activator.CreateInstance</c> is a reflection-equivalent escape; <c>GC</c>
|
||||
/// and <c>AppDomain</c> expose process-wide control. Legitimate <c>System</c>
|
||||
/// types (<c>Math</c>, <c>String</c>, <c>Convert</c>, <c>DateTime</c>, …) are not
|
||||
/// on the list and stay usable.
|
||||
/// <b>The rules.</b> (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 <see cref="AllowedMembers"/>), must not
|
||||
/// be in <see cref="ForbiddenMembers"/>, and its type arguments and return type must be allowed. Rule (2)'s
|
||||
/// return-type check is what keeps reflection handles out of reach: <c>Exception.TargetSite</c> is a member
|
||||
/// of an allowed type but returns a <c>MethodBase</c>. (3) A few syntactic forms are refused outright
|
||||
/// (<see cref="IsForbiddenSyntax"/>): <c>__makeref</c>/<c>__refvalue</c>/<c>__reftype</c>/<c>__arglist</c>,
|
||||
/// <c>lock</c> (a blocking primitive on a possibly-shared object) and <c>extern</c> local functions.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <b>Defence in depth.</b> <see cref="ScriptSandbox"/> 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 —
|
||||
/// <c>System.Private.CoreLib</c> carries <c>File</c>, <c>Thread</c>, <c>Assembly</c>, <c>Environment</c> —
|
||||
/// so this analyzer remains the gate, and its own test (<c>ForbiddenTypeAnalyzerTests</c>) runs every
|
||||
/// bypass against every assembly the host can load.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <b>Adding to the list.</b> 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
|
||||
/// <see cref="ScriptContext"/> 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.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public static class ForbiddenTypeAnalyzer
|
||||
{
|
||||
/// <summary>
|
||||
/// 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 <c>System.IO</c> catches <c>System.IO.File</c>,
|
||||
/// <c>System.IO.Pipes</c>, and any future subnamespace without needing explicit
|
||||
/// enumeration.
|
||||
/// </summary>
|
||||
public static readonly IReadOnlyList<string> ForbiddenNamespacePrefixes =
|
||||
/// <summary>Namespaces whose every type is allowed. Exact match — a sub-namespace is NOT included.</summary>
|
||||
public static readonly IReadOnlyList<string> 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",
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
/// Types that stay reachable although their namespace is in
|
||||
/// <see cref="ForbiddenNamespacePrefixes"/>. Matched by exact fully-qualified name against the
|
||||
/// resolved type symbol (generic constructions unwrapped). The whole of <c>System.Threading</c> is
|
||||
/// denied; these three are the sync-free primitives with no blocking surface — a
|
||||
/// <see cref="CancellationToken"/> is read-only state, <see cref="Interlocked"/> and
|
||||
/// <see cref="Volatile"/> are single-instruction memory operations.
|
||||
/// Types a script may name, as <c>Namespace.Name</c> without generic arity (so <c>System.Func</c> covers every
|
||||
/// <c>Func<…></c>). A nested type is allowed when its containing type is. Every <c>System.Exception</c>
|
||||
/// subclass declared in the <c>System</c> namespace is allowed in addition to this list.
|
||||
/// </summary>
|
||||
public static readonly IReadOnlyList<string> AllowedTypesInForbiddenNamespaces =
|
||||
public static readonly IReadOnlyList<string> 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",
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
/// Members scripts are NOT allowed to call on otherwise-allowed types, as
|
||||
/// <c>(declaring type, member name)</c>. <c>System.Type</c> must stay reachable
|
||||
/// (<c>typeof</c>, <c>Name</c>, <c>IsValueType</c> are ordinary metadata reads) but its reflection
|
||||
/// entry points obtain a type or member by NAME — <c>Type.GetType("System.IO.File")</c> reaches a
|
||||
/// forbidden type without ever naming it syntactically, and <c>GetMethod*</c> / <c>GetProperty</c>
|
||||
/// / <c>InvokeMember</c> / … hand back a <c>System.Reflection</c> handle (which pass 2 catches when
|
||||
/// declared, but not when consumed inline). Instance <c>object.GetType()</c> is declared on
|
||||
/// <c>System.Object</c> 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). <c>System.Type</c> is the reflection gateway — <c>typeof(x)</c>,
|
||||
/// <c>o.GetType() == typeof(double)</c> and <c>Convert.ChangeType(v, typeof(int))</c> are ordinary, but
|
||||
/// <c>Assembly</c>, <c>Module</c>, <c>GetMethod</c>, <c>MakeGenericType</c>, <c>TypeHandle</c>, … are not.
|
||||
/// <c>CancellationToken</c> (<c>ctx.CancellationToken</c>) may be polled but not <c>Register</c>ed against
|
||||
/// (a callback that runs off the evaluation) nor waited on through its <c>WaitHandle</c>.
|
||||
/// </summary>
|
||||
public static readonly IReadOnlyDictionary<string, IReadOnlyList<string>> RestrictedTypeMembers =
|
||||
new Dictionary<string, IReadOnlyList<string>>(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",
|
||||
],
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Members allowed although their declaring type is not: <c>typeof(int).Name</c> binds to
|
||||
/// <c>System.Reflection.MemberInfo.Name</c> (<c>Type</c> inherits it without overriding).
|
||||
/// </summary>
|
||||
public static readonly IReadOnlyList<(string Type, string Member)> AllowedMembers =
|
||||
[
|
||||
("System.Reflection.MemberInfo", "Name"),
|
||||
];
|
||||
|
||||
/// <summary>Members refused on otherwise-allowed types: process-wide state.</summary>
|
||||
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"),
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
/// 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. <c>System.Runtime.CompilerServices</c> hosts both <c>MethodImplOptions</c> and
|
||||
/// <c>RuntimeHelpers</c>) so a namespace-prefix rule would over-block. Matched by exact
|
||||
/// fully-qualified name against the resolved <em>type</em> symbol — every member of
|
||||
/// the type (including read-only ones) is therefore rejected.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <list type="bullet">
|
||||
/// <item><c>System.Environment</c> — <c>Exit</c> / <c>FailFast</c> terminate
|
||||
/// the host process; the whole type is denied (the read members have no
|
||||
/// legitimate SCADA-predicate use either).</item>
|
||||
/// <item><c>System.AppDomain</c> — process-wide assembly-load /
|
||||
/// unhandled-exception control.</item>
|
||||
/// <item><c>System.GC</c> — <c>Collect</c> / <c>AddMemoryPressure</c> perturb
|
||||
/// the process memory subsystem.</item>
|
||||
/// <item><c>System.Activator</c> — <c>CreateInstance</c> is a
|
||||
/// reflection-equivalent escape that constructs a forbidden type by name
|
||||
/// without ever naming it syntactically.</item>
|
||||
/// <item><c>System.Runtime.CompilerServices.Unsafe</c> — exposes raw type-
|
||||
/// reinterpretation (<c>As<TFrom,TTo></c>, <c>As<T>(object)</c>)
|
||||
/// that bypasses the CLR type system without requiring an <c>unsafe</c> context at
|
||||
/// the call site; enables type-confusion and managed heap corruption.</item>
|
||||
/// <item><c>System.Runtime.CompilerServices.RuntimeHelpers</c> —
|
||||
/// <c>GetUninitializedObject</c> constructs an instance of any type (a forbidden
|
||||
/// one included) with no constructor and no syntactic type name beyond a
|
||||
/// <c>Type</c> value; <c>PrepareMethod</c> / <c>RunClassConstructor</c> reach
|
||||
/// runtime internals.</item>
|
||||
/// </list>
|
||||
/// <para>
|
||||
/// <c>System.Threading.Thread</c> / <c>ThreadPool</c> / <c>Timer</c> used to be listed
|
||||
/// here; since the whole <c>System.Threading</c> namespace is denied (with a type-granular
|
||||
/// allow-list, see <see cref="AllowedTypesInForbiddenNamespaces"/>) the prefix rule reaches
|
||||
/// them first.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public static readonly IReadOnlyList<string> ForbiddenFullTypeNames =
|
||||
[
|
||||
"System.Environment",
|
||||
"System.AppDomain",
|
||||
"System.GC",
|
||||
"System.Activator",
|
||||
// System.Runtime.CompilerServices.Unsafe exposes raw type-reinterpretation
|
||||
// (Unsafe.As<TFrom, TTo>, Unsafe.As<T>(object)) that bypasses the CLR type system
|
||||
// without requiring an 'unsafe' compilation context at the call site. In a script,
|
||||
// calling Unsafe.As<string>(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<string> AllowedNamespaceSet = new(AllowedNamespaces, StringComparer.Ordinal);
|
||||
private static readonly HashSet<string> AllowedTypeSet = new(AllowedTypes, StringComparer.Ordinal);
|
||||
private static readonly HashSet<(string, string)> AllowedMemberSet = new(AllowedMembers);
|
||||
private static readonly HashSet<(string, string)> ForbiddenMemberSet = new(ForbiddenMembers);
|
||||
|
||||
/// <summary>
|
||||
/// Scan the <paramref name="compilation"/> 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 <paramref name="compilation"/> 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.
|
||||
/// </summary>
|
||||
/// <param name="compilation">The compilation to analyze.</param>
|
||||
/// <returns>A list of forbidden type rejections, or empty if the script is clean.</returns>
|
||||
/// <param name="compilation">The compilation to analyze (the synthesized <c>CompiledScript.Run</c> wrapper).</param>
|
||||
/// <returns>The rejections, or empty if the script is clean.</returns>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// The walker has two passes per node. Pass (1) is the member / call surface:
|
||||
/// <c>ObjectCreationExpressionSyntax</c>, <c>InvocationExpressionSyntax</c> with
|
||||
/// a member-access target, <c>MemberAccessExpressionSyntax</c>, and bare
|
||||
/// <c>IdentifierNameSyntax</c> are resolved via
|
||||
/// <see cref="SemanticModel"/>.<c>GetSymbolInfo</c>. This catches static calls
|
||||
/// (<c>System.IO.File.ReadAllText</c>) and constructors, and is deliberately
|
||||
/// narrow: resolving <c>GetSymbolInfo</c> on <em>every</em> node would flag
|
||||
/// harmless inherited members (e.g. <c>typeof(int).Name</c> resolves
|
||||
/// <c>Name</c> to <c>System.Reflection.MemberInfo</c>, the base type that
|
||||
/// declares it, even though the receiver type <c>System.Type</c> is allowed).
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Pass (2) resolves the <em>type</em> of every
|
||||
/// <c>TypeSyntax</c> node via <c>GetTypeInfo</c>. The old walker only inspected
|
||||
/// the four node kinds above, so a forbidden type named through
|
||||
/// <c>typeof(System.IO.File)</c>, a generic argument
|
||||
/// (<c>List<System.IO.FileInfo></c>), a cast
|
||||
/// (<c>(System.IO.Stream)null</c>), an <c>is</c> / <c>as</c> type pattern,
|
||||
/// <c>default(System.Reflection.Assembly)</c>, an array-creation element type,
|
||||
/// or an explicitly-typed local declaration produced no examined node and so
|
||||
/// slipped through. Every <c>TypeSyntax</c> resolves to a concrete
|
||||
/// <see cref="ITypeSymbol"/>; generic type arguments and array element types
|
||||
/// are unwrapped recursively so a forbidden type nested at any depth is caught.
|
||||
/// </para>
|
||||
/// The wrapper's own header — <c>using</c> directives, the namespace, and the <c>Run</c> method's return and
|
||||
/// parameter types (chosen by the host, e.g. <c>ScriptGlobals<VirtualTagContext></c>) — is not
|
||||
/// analyzed; everything else in the tree is, including the wrapper's <c>var ctx = globals.ctx;</c> and any
|
||||
/// member a malformed source manages to inject (the publish gate separately refuses injection, LMX001/002).
|
||||
/// </remarks>
|
||||
public static IReadOnlyList<ForbiddenTypeRejection> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reject <paramref name="type"/> 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.
|
||||
/// <c>List<System.IO.FileInfo></c> — is still caught.
|
||||
/// </summary>
|
||||
private static void CheckTypeSymbol(ITypeSymbol? type, TextSpan span, List<ForbiddenTypeRejection> rejections)
|
||||
/// <summary>The wrapper header spans the host writes (see <see cref="Analyze"/>'s remarks).</summary>
|
||||
private static List<TextSpan> TrustedWrapperSpans(SyntaxNode root)
|
||||
{
|
||||
if (type is null) return;
|
||||
|
||||
CheckSymbol(type, span, rejections);
|
||||
|
||||
switch (type)
|
||||
var spans = new List<TextSpan>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Member deny-list check on its own (no type / namespace rule): rejects a method or property whose declaring
|
||||
/// type and name are listed in <see cref="ForbiddenMembers"/>. Exact declaring-type match, so an inherited
|
||||
/// harmless member is never flagged.
|
||||
/// Syntax refused regardless of binding: the undocumented <c>TypedReference</c> keywords, <c>lock</c> (a
|
||||
/// blocking monitor on an object that may be shared with the host, e.g. <c>lock (typeof(string))</c>), and
|
||||
/// <c>extern</c> local functions (a native entry point).
|
||||
/// </summary>
|
||||
private static bool TryRejectMember(ISymbol? symbol, TextSpan span, string ns, List<ForbiddenTypeRejection> rejections)
|
||||
/// <param name="node">The node.</param>
|
||||
/// <returns>A description of the construct, or null when the node is allowed.</returns>
|
||||
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<ForbiddenTypeRejection> 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<ForbiddenTypeRejection> rejections)
|
||||
/// <summary><c>Namespace.Name</c> without generic arity; nested types as <c>Outer.Inner</c>.</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A single forbidden-type reference in a user script.</summary>
|
||||
/// <summary>A single reference in a user script that is outside the sandbox allow-list.</summary>
|
||||
public sealed record ForbiddenTypeRejection(
|
||||
TextSpan Span,
|
||||
string TypeName,
|
||||
@@ -448,7 +482,7 @@ public sealed record ForbiddenTypeRejection(
|
||||
string Message);
|
||||
|
||||
/// <summary>Thrown from <see cref="ScriptEvaluator{TContext, TResult}.Compile"/> when the
|
||||
/// post-compile forbidden-type analyzer finds references to denied namespaces.</summary>
|
||||
/// post-compile <see cref="ForbiddenTypeAnalyzer"/> finds references outside the sandbox allow-list.</summary>
|
||||
public sealed class ScriptSandboxViolationException : Exception
|
||||
{
|
||||
/// <summary>Gets the list of forbidden type rejections that triggered this exception.</summary>
|
||||
@@ -465,7 +499,7 @@ public sealed class ScriptSandboxViolationException : Exception
|
||||
private static string BuildMessage(IReadOnlyList<ForbiddenTypeRejection> 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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,9 +30,9 @@ namespace ZB.MOM.WW.OtOpcUa.Core.Scripting;
|
||||
/// <see cref="ScriptSandbox"/> allow-list — catches syntax errors, unresolved
|
||||
/// types (the sandbox's first line of defense), and most type-resolution
|
||||
/// failures, throwing <see cref="CompilationErrorException"/>; (2)
|
||||
/// <see cref="ForbiddenTypeAnalyzer"/> runs against the semantic model — catches
|
||||
/// sandbox escapes that slipped past reference restrictions due to .NET's type
|
||||
/// forwarding, throwing <see cref="ScriptSandboxViolationException"/>; (3) emit
|
||||
/// <see cref="ForbiddenTypeAnalyzer"/> 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 <see cref="ScriptSandboxViolationException"/>; (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 <see cref="ScriptStackGuard.Check"/> on entry to every script-declared body, so unbounded
|
||||
@@ -128,8 +128,8 @@ public sealed class ScriptEvaluator<TContext, TResult> : 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<TContext, TResult> : IDisposable
|
||||
/// <summary>
|
||||
/// A digest of everything that decides what <see cref="CompileToImage"/> 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 <typeparamref name="TContext"/> / <typeparamref name="TResult"/>. 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.
|
||||
|
||||
@@ -4,22 +4,17 @@ using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
namespace ZB.MOM.WW.OtOpcUa.Core.Scripting;
|
||||
|
||||
/// <summary>
|
||||
/// 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 <c>System.IO</c>, no
|
||||
/// <c>System.Net</c>, no <c>System.Diagnostics.Process</c>, no
|
||||
/// <c>System.Reflection</c>. 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 <c>ctx</c> API lives in plus the few BCL assemblies listed in
|
||||
/// <see cref="BclAssemblyNames"/>. An API outside that set fails to bind (a compiler error pointing at the
|
||||
/// span); an API inside it that is not on the <see cref="ForbiddenTypeAnalyzer"/> allow-list is rejected by
|
||||
/// the analyzer. Either way the operator sees the rejection before publish, not at evaluation.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// Roslyn would otherwise pull in every type in the BCL transitively via
|
||||
/// <c>mscorlib</c> / <c>System.Runtime</c> — this class overrides that with an
|
||||
/// explicit minimal allow-list. The list is the same regardless of whether
|
||||
/// <see cref="ScriptEvaluator{TContext, TResult}"/> uses the legacy
|
||||
/// <c>CSharpScript</c> path or the collectible-<c>AssemblyLoadContext</c> path:
|
||||
/// both go through <see cref="Build"/>.
|
||||
/// The analyzer is the gate; this reference set is defence in depth (lmxopcua#971). The same set is used by
|
||||
/// the publish gate (<see cref="ScriptEvaluator{TContext, TResult}"/>) and by the AdminUI script editor, so
|
||||
/// the editor's completions and diagnostics cover exactly what publish compiles.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Namespaces pre-imported so scripts don't have to write <c>using</c> 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<MetadataReference>();
|
||||
// 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);
|
||||
|
||||
/// <summary>
|
||||
/// The BCL assemblies a script is compiled against: the ones holding the types on
|
||||
/// <see cref="ForbiddenTypeAnalyzer.AllowedTypes"/>, 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).
|
||||
/// </summary>
|
||||
public static readonly IReadOnlyList<string> 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<string> 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<string>(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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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
|
||||
/// <em>allow-list</em>: a script may name only the <c>ctx</c> API and an explicit set of value / collection / text
|
||||
/// types, so each snippet is refused.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Each snippet is asserted twice. <see cref="Bypass_snippet_is_refused_at_publish"/> runs the real publish gate
|
||||
/// (<see cref="ScriptEvaluator{TContext, TResult}.Compile"/>), where a snippet may now also fail to bind because
|
||||
/// the narrowed reference set no longer carries its assembly. <see cref="Allow_list_alone_rejects_bypass_snippet"/>
|
||||
/// 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.
|
||||
/// </remarks>
|
||||
[Trait("Category", "Unit")]
|
||||
public sealed class ForbiddenTypeAnalyzerTests
|
||||
{
|
||||
/// <summary>The eight K-1 bypasses (the background-work row is three snippets) plus a few siblings.</summary>
|
||||
public static TheoryData<string, string> BypassSnippets => new()
|
||||
{
|
||||
// 1. Delegate.CreateDelegate binds Type.GetType by name, then File.ReadAllText on the returned type.
|
||||
{ "CreateDelegate-file-read", """
|
||||
var getType = (Func<string, Type>)Delegate.CreateDelegate(typeof(Func<string, Type>), typeof(Type), "GetType");
|
||||
var file = getType("System.IO.File");
|
||||
var read = (Func<string, string>)Delegate.CreateDelegate(typeof(Func<string, string>), 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<Func<Type>>(
|
||||
System.Linq.Expressions.Expression.Call(typeof(Type), "GetType", null, name)).Compile();
|
||||
var processType = getType();
|
||||
var start = System.Linq.Expressions.Expression.Lambda<Func<object>>(
|
||||
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<int> f = () => 1; return f.Method.Name;""" },
|
||||
{ "Delegate-DynamicInvoke", """Func<int> 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;""" },
|
||||
};
|
||||
|
||||
|
||||
/// <summary>Each bypass snippet is refused by the publish gate.</summary>
|
||||
/// <param name="name">Row label.</param>
|
||||
/// <param name="source">The script body.</param>
|
||||
[Theory]
|
||||
[MemberData(nameof(BypassSnippets))]
|
||||
public void Bypass_snippet_is_refused_at_publish(string name, string source)
|
||||
{
|
||||
_ = name;
|
||||
SandboxRefusal.Refuses(source);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// With every loadable assembly referenced (so the snippet binds), the allow-list analyzer on its own
|
||||
/// rejects it.
|
||||
/// </summary>
|
||||
/// <param name="name">Row label.</param>
|
||||
/// <param name="source">The script body.</param>
|
||||
[Theory]
|
||||
[MemberData(nameof(BypassSnippets))]
|
||||
public void Allow_list_alone_rejects_bypass_snippet(string name, string source)
|
||||
{
|
||||
_ = name;
|
||||
SandboxRefusal.AnalyzerAloneRejects(source);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="source">The script body.</param>
|
||||
[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);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
[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<double> { 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();
|
||||
}
|
||||
|
||||
/// <summary>A rejection names the type, and the message points at the allow-list.</summary>
|
||||
[Fact]
|
||||
public void Rejection_names_the_type_and_the_allow_list()
|
||||
{
|
||||
var ex = Should.Throw<ScriptSandboxViolationException>(() =>
|
||||
ScriptEvaluator<FakeScriptContext, object?>.Compile("""return Delegate.CreateDelegate(typeof(Func<int>), typeof(int), "x");"""));
|
||||
ex.Rejections.ShouldContain(r => r.TypeName.StartsWith("System.Delegate", StringComparison.Ordinal));
|
||||
ex.Message.ShouldContain("allow-list");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <c>System.Type</c> is usable as a value with a member allow-list: metadata reads work, the reflection
|
||||
/// handles do not; the rejection names the member.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task Type_is_a_value_with_a_member_allow_list()
|
||||
{
|
||||
using var ok = ScriptEvaluator<FakeScriptContext, object?>.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<ScriptSandboxViolationException>(() =>
|
||||
ScriptEvaluator<FakeScriptContext, object?>.Compile("""return typeof(int).TypeHandle;"""));
|
||||
ex.Rejections.ShouldContain(r => r.TypeName == "System.Type.TypeHandle");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
[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<INamedTypeSymbol>();
|
||||
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<Microsoft.CodeAnalysis.CSharp.Syntax.TypeOfExpressionSyntax>().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<string>();
|
||||
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<INamedTypeSymbol> into)
|
||||
{
|
||||
into.AddRange(ns.GetTypeMembers());
|
||||
foreach (var child in ns.GetNamespaceMembers()) Collect(child, into);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Shared assertions for "the sandbox refuses this script" (lmxopcua#971).</summary>
|
||||
internal static class SandboxRefusal
|
||||
{
|
||||
private static readonly Lazy<MetadataReference[]> FullHostReferences = new(() =>
|
||||
{
|
||||
var tpa = ((string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")!)
|
||||
.Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries);
|
||||
var paths = new HashSet<string>(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();
|
||||
});
|
||||
|
||||
/// <summary>
|
||||
/// The publish gate refuses <paramref name="source"/>: 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.
|
||||
/// </summary>
|
||||
/// <param name="source">The script body.</param>
|
||||
/// <returns>The refusal.</returns>
|
||||
public static Exception Refuses(string source)
|
||||
{
|
||||
var ex = Should.Throw<Exception>(() => ScriptEvaluator<FakeScriptContext, object?>.Compile(source));
|
||||
(ex is ScriptSandboxViolationException or CompilationErrorException).ShouldBeTrue(
|
||||
$"expected a sandbox / compile refusal, got {ex.GetType().Name}: {ex.Message}");
|
||||
return ex;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Compiled against every assembly the test host can load (so the snippet binds), the analyzer on its own
|
||||
/// rejects <paramref name="source"/>.
|
||||
/// </summary>
|
||||
/// <param name="source">The script body.</param>
|
||||
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();
|
||||
}
|
||||
|
||||
/// <summary>The script wrapped like the publish gate wraps it, compiled against the full host surface.</summary>
|
||||
/// <param name="body">The script body.</param>
|
||||
/// <returns>The compilation.</returns>
|
||||
public static CSharpCompilation CompileAgainstFullHost(string body) => CompileAgainst(body, FullHostReferences.Value);
|
||||
|
||||
/// <summary>The script wrapped like the publish gate wraps it, compiled against <paramref name="references"/>.</summary>
|
||||
/// <param name="body">The script body.</param>
|
||||
/// <param name="references">The references.</param>
|
||||
/// <returns>The compilation.</returns>
|
||||
public static CSharpCompilation CompileAgainst(string body, IEnumerable<MetadataReference> 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<global::ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests.FakeScriptContext> 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));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
using System.Text.RegularExpressions;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// 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 <c>src/</c> and <c>tests/</c> (511 that compiled before) found none that stopped compiling
|
||||
/// apart from the one expression-tree test, which is intentional.
|
||||
/// </summary>
|
||||
[Trait("Category", "Unit")]
|
||||
public sealed class ScriptAllowListRegressionTests
|
||||
{
|
||||
/// <summary>Authoring idioms that must keep compiling (and running) under the allow-list.</summary>
|
||||
public static TheoryData<string> 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<string, double> { ["a"] = 1, ["b"] = 5, ["c"] = 3 };
|
||||
var set = new System.Collections.Generic.HashSet<int> { 1, 2 };
|
||||
var q = new System.Collections.Generic.Queue<int>(); 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<DayOfWeek>("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<int> 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<string, int> { ["a"] = 1 }) { var (k, v) = kv; total += v + k.Length; }
|
||||
return total;
|
||||
""",
|
||||
// Writes.
|
||||
"""
|
||||
ctx.SetVirtualTag("Out", 42);
|
||||
return true;
|
||||
""",
|
||||
};
|
||||
|
||||
/// <summary>Each idiom compiles through the publish gate and runs.</summary>
|
||||
/// <param name="source">The script body.</param>
|
||||
[Theory]
|
||||
[MemberData(nameof(Idioms))]
|
||||
public async Task Idiom_compiles_and_runs(string source)
|
||||
{
|
||||
using var evaluator = ScriptEvaluator<FakeScriptContext, object?>.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);
|
||||
}
|
||||
|
||||
/// <summary>Every script sample in the operator docs and the seed SQL compiles through the publish gate.</summary>
|
||||
[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<string>();
|
||||
foreach (var (origin, source) in samples)
|
||||
{
|
||||
try { ScriptEvaluator<FakeScriptContext, object?>.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);
|
||||
}
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// lmxopcua#971: the BCL half of the reference set is exactly <see cref="ScriptSandbox.BclAssemblyNames"/> — every
|
||||
/// listed assembly is found, and nothing carrying I/O, networking, XML, archives, expression trees, component
|
||||
/// model, crypto, the console or processes is referenced.
|
||||
/// </summary>
|
||||
[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));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -67,24 +67,26 @@ public sealed class ScriptSandboxTests
|
||||
[Fact]
|
||||
public void Rejects_HttpClient_at_compile()
|
||||
{
|
||||
Should.Throw<ScriptSandboxViolationException>(() =>
|
||||
ScriptEvaluator<FakeScriptContext, int>.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);
|
||||
}
|
||||
|
||||
/// <summary>Verifies that Process.Start is rejected at compile time.</summary>
|
||||
[Fact]
|
||||
public void Rejects_Process_Start_at_compile()
|
||||
{
|
||||
Should.Throw<ScriptSandboxViolationException>(() =>
|
||||
ScriptEvaluator<FakeScriptContext, int>.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);
|
||||
}
|
||||
|
||||
/// <summary>Verifies that Assembly.Load is rejected at compile time.</summary>
|
||||
@@ -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<ScriptSandboxViolationException>(() =>
|
||||
ScriptEvaluator<FakeScriptContext, int>.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);
|
||||
}
|
||||
|
||||
/// <summary>Verifies that typeof a forbidden type inside Activator is rejected at compile time.</summary>
|
||||
[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<ScriptSandboxViolationException>(() =>
|
||||
ScriptEvaluator<FakeScriptContext, int>.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);
|
||||
}
|
||||
|
||||
/// <summary>Verifies that an allowed generic type argument still compiles.</summary>
|
||||
@@ -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<ScriptSandboxViolationException>(() =>
|
||||
ScriptEvaluator<FakeScriptContext, int>.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.
|
||||
|
||||
/// <summary>Verifies that ThreadPool.QueueUserWorkItem is rejected at compile time.</summary>
|
||||
[Fact]
|
||||
|
||||
+20
-2
@@ -43,10 +43,28 @@ public sealed class ScriptStackGuardInjectionTests
|
||||
|
||||
/// <summary>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.</summary>
|
||||
/// <remarks>
|
||||
/// Since lmxopcua#971 a script cannot write an expression tree at all (<c>System.Linq.Expressions</c> 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.
|
||||
/// </remarks>
|
||||
[Fact]
|
||||
public void An_expression_tree_lambda_is_not_rewritten()
|
||||
{
|
||||
Run("System.Linq.Expressions.Expression<System.Func<int, int>> e = x => x + 1; return (int)e.Body.NodeType;")
|
||||
.ShouldBe((int)System.Linq.Expressions.ExpressionType.Add);
|
||||
Should.Throw<CompilationErrorException>(() => ScriptEvaluator<FakeScriptContext, object?>.Compile(
|
||||
"System.Linq.Expressions.Expression<System.Func<int, int>> e = x => x + 1; return 0;"));
|
||||
|
||||
var tree = Microsoft.CodeAnalysis.CSharp.CSharpSyntaxTree.ParseText(
|
||||
"class C { static object Run() { System.Linq.Expressions.Expression<System.Func<int, int>> 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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<string, Type>)Delegate.CreateDelegate(typeof(Func<string, Type>), 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<int> 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<string, Type>)Delegate.CreateDelegate(typeof(Func<string, Type>), 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<string, int> { ["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<ZB.MOM.WW.OtOpcUa.Core.VirtualTags.VirtualTagContext, object?>.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"));
|
||||
|
||||
Reference in New Issue
Block a user