From 7ecaeea82e2237e8abf00c36ecfe04232046ddba Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 12:01:25 -0500 Subject: [PATCH] =?UTF-8?q?fix(scripting):=20#971=20review=20=E2=80=94=20r?= =?UTF-8?q?efuse=20async=20lambdas/local=20functions,=20stackalloc=20and?= =?UTF-8?q?=20runtime-binding=20[MethodImpl]=20flags?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three scripts passed the allow-list and the deploy gate and then terminated the host (exit 134): an async void local function / async lambda (the compiler's AsyncVoidMethodBuilder rethrows on the thread pool) and an over-sized stackalloc (overflows in one frame, before the #779 guard). IsForbiddenSyntax now refuses every async form (await included) and both stackalloc forms. Siblings: [MethodImpl] may set only the JIT-hint bits (InternalCall passed the gate then failed to load; Synchronized is a lock; numeric casts are checked by constant value), and a collection initializer's compiler-called Add is checked like a named member. Regression rows for each, plus rows pinning the lowered constructs that stay safe (iterators, goto, checked, filters, collection expressions, interpolation handlers, params Span, using/deconstruction) and the declarations the wrapper already refuses (records, local types, finalizers, static ctors, unsafe/fixed, SkipLocalsInit, ThreadStatic). Co-Authored-By: Claude --- docs/VirtualTags.md | 2 +- .../ForbiddenTypeAnalyzer.cs | 80 ++++++++++++++++++- .../ScriptStackGuardInjector.cs | 5 +- .../ForbiddenTypeAnalyzerTests.cs | 55 +++++++++++++ 4 files changed, 135 insertions(+), 7 deletions(-) diff --git a/docs/VirtualTags.md b/docs/VirtualTags.md index f2c93b3c3..7503ee98c 100644 --- a/docs/VirtualTags.md +++ b/docs/VirtualTags.md @@ -42,7 +42,7 @@ A script may name only: - `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`). +The rules (`ForbiddenTypeAnalyzer`): every type a script names, and every type an expression evaluates or converts to, must be allowed (generic arguments and array elements included); every member used must be declared on an allowed type (or be in `AllowedMembers`), must not be in `ForbiddenMembers` (`CultureInfo.CurrentCulture` and the other ambient-culture setters, `TimeZoneInfo.ClearCachedData`, `Encoding.RegisterProvider`, `Regex.CacheSize`), and its return type must be allowed — which is what keeps reflection handles out of reach (`Exception.TargetSite` is a member of an allowed type but returns a `MethodBase`; `Delegate.Method` / `DynamicInvoke` are declared on the un-listed `System.Delegate`). `__makeref` / `__refvalue` / `__reftype` / `__arglist`, `lock`, and `extern` local functions are refused syntactically, and so — since the 2026-12-02 security review — are **`async` lambdas / anonymous methods / local functions** and **`stackalloc`**: each compiled through the allow-list *and* the deploy gate and then terminated the host (exit 134). An `async void` body's exception is rethrown on the thread pool by a compiler-synthesized builder no allow-list check sees, and one over-sized `stackalloc` overflows the stack inside a single frame, before any stack guard runs. `[MethodImpl]` on a local function may set only the JIT hints (`NoInlining` / `NoOptimization` / `AggressiveInlining` / `AggressiveOptimization`): `InternalCall` passed the gate and then failed to load, and `Synchronized` is a `lock`. Members the compiler calls without a name in the source — query operators, `foreach`'s enumerator pattern, `Deconstruct`, a collection initializer's `Add` — are checked like named ones. Pre-imported namespaces are unchanged (`System`, `System.Linq`, `ZB.MOM.WW.OtOpcUa.Core.Abstractions`, `ZB.MOM.WW.OtOpcUa.Core.Scripting`) — a collection still needs its full name (`System.Collections.Generic.List`). `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. diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ForbiddenTypeAnalyzer.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ForbiddenTypeAnalyzer.cs index 21744aa9f..fbaa17fb1 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ForbiddenTypeAnalyzer.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ForbiddenTypeAnalyzer.cs @@ -49,7 +49,11 @@ namespace ZB.MOM.WW.OtOpcUa.Core.Scripting; /// return-type check is what keeps reflection handles out of reach: Exception.TargetSite is a member /// of an allowed type but returns a MethodBase. (3) A few syntactic forms are refused outright /// (): __makeref/__refvalue/__reftype/__arglist, -/// lock (a blocking primitive on a possibly-shared object) and extern local functions. +/// lock (a blocking primitive on a possibly-shared object), extern local functions, +/// async lambdas / local functions and stackalloc (each terminated the host — +/// lmxopcua#971 review 2026-12-02); [MethodImpl] is limited to the JIT hint bits. (4) Members the +/// compiler calls without a name in the source — query operators, foreach's enumerator pattern, +/// Deconstruct, a collection initializer's Add — are checked like named ones. /// /// /// Defence in depth. also references only the handful of BCL assemblies @@ -255,9 +259,28 @@ public static class ForbiddenTypeAnalyzer /// /// Syntax refused regardless of binding: the undocumented TypedReference keywords, lock (a - /// blocking monitor on an object that may be shared with the host, e.g. lock (typeof(string))), and - /// extern local functions (a native entry point). + /// blocking monitor on an object that may be shared with the host, e.g. lock (typeof(string))), + /// extern local functions (a native entry point), async lambdas / anonymous methods / local + /// functions, and stackalloc. /// + /// + /// + /// async (lmxopcua#971 review 2026-12-02). The compiler lowers an async body into a state + /// machine driven by a method builder the script never names, so no allow-list check sees it. An + /// async void body's exception is not returned to the caller: AsyncVoidMethodBuilder + /// rethrows it on the thread pool, where nothing catches it and the runtime terminates the host + /// (async void Boom() { throw … } Boom(); — and an async lambda converted to + /// Action is the same thing). A script is synchronous by contract + /// () and System.Threading.Tasks is not + /// on the allow-list, so there is no legitimate async script code: every form is refused, which + /// also covers await, await foreach and await using (legal only inside one). + /// + /// + /// stackalloc. One stackalloc byte[1_500_000_000] overflows the thread's stack inside + /// a single frame — before the next ScriptStackGuard.Check() can run — and a stack overflow is + /// uncatchable. Scripts have heap arrays and Span over them; there is no need for stack buffers. + /// + /// /// The node. /// A description of the construct, or null when the node is allowed. internal static string? IsForbiddenSyntax(SyntaxNode node) => node switch @@ -268,9 +291,28 @@ public static class ForbiddenTypeAnalyzer ExpressionSyntax e when e.IsKind(SyntaxKind.ArgListExpression) => "__arglist", LockStatementSyntax => "lock", LocalFunctionStatementSyntax f when f.Modifiers.Any(SyntaxKind.ExternKeyword) => "extern local function", + LocalFunctionStatementSyntax f when f.Modifiers.Any(SyntaxKind.AsyncKeyword) => "async local function", + AnonymousFunctionExpressionSyntax f when f.AsyncKeyword.IsKind(SyntaxKind.AsyncKeyword) => "async lambda", + AwaitExpressionSyntax => "await", + StackAllocArrayCreationExpressionSyntax or ImplicitStackAllocArrayCreationExpressionSyntax => "stackalloc", _ => null, }; + /// + /// The bits a script's [MethodImpl] may + /// set: JIT inlining / optimization hints only. InternalCall / ForwardRef / Unmanaged / + /// PreserveSig change how the runtime binds the method (an InternalCall local function passes the + /// compiler and fails to load — the publish gate accepted what the runtime refuses), and Synchronized + /// takes a monitor (the lock the analyzer refuses). + /// + private const int AllowedMethodImplBits = + (int)(System.Runtime.CompilerServices.MethodImplOptions.NoInlining + | System.Runtime.CompilerServices.MethodImplOptions.NoOptimization + | System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining + | System.Runtime.CompilerServices.MethodImplOptions.AggressiveOptimization); + + private const string MethodImplAttributeFullName = "System.Runtime.CompilerServices.MethodImplAttribute"; + private sealed class Walker(Compilation compilation, SemanticModel semantic, List rejections) { public void Visit(SyntaxNode node) @@ -283,9 +325,19 @@ public static class ForbiddenTypeAnalyzer } // Members the compiler calls with no name in the source: query-clause operators, foreach's - // GetEnumerator / MoveNext / Current, and a deconstruction's Deconstruct. + // GetEnumerator / MoveNext / Current, a deconstruction's Deconstruct, and a collection initializer's Add. switch (node) { + case AttributeSyntax attribute: + CheckMethodImpl(attribute); + break; + case InitializerExpressionSyntax initializer when initializer.IsKind(SyntaxKind.CollectionInitializerExpression): + foreach (var element in initializer.Expressions) + { + var addInfo = semantic.GetCollectionInitializerSymbolInfo(element); + CheckOptional(addInfo.Symbol, element.Span); + } + break; case QueryClauseSyntax clause: var clauseInfo = semantic.GetQueryClauseInfo(clause); CheckOptional(clauseInfo.OperationInfo.Symbol, clause.Span); @@ -318,6 +370,26 @@ public static class ForbiddenTypeAnalyzer CheckType(typeInfo.ConvertedType, expr.Span); } + /// Refuses [MethodImpl] flags outside , however spelled. + private void CheckMethodImpl(AttributeSyntax attribute) + { + if (semantic.GetSymbolInfo(attribute).Symbol is not IMethodSymbol { ContainingType: { } attributeType } + || TypeKey(attributeType.OriginalDefinition) != MethodImplAttributeFullName + || attribute.ArgumentList is null) + return; + + foreach (var argument in attribute.ArgumentList.Arguments) + { + if (argument.NameEquals is not null) continue; // named (MethodCodeType = …): its type is checked as usual + var constant = semantic.GetConstantValue(argument.Expression); + var bits = constant is { HasValue: true, Value: { } value } ? Convert.ToInt64(value, System.Globalization.CultureInfo.InvariantCulture) : -1; + if (bits < 0 || (bits & ~AllowedMethodImplBits) != 0) + Add(argument.Span, "MethodImplOptions", "System.Runtime.CompilerServices", + "[MethodImpl] may only set NoInlining, NoOptimization, AggressiveInlining or AggressiveOptimization " + + "in a script (sandbox: see ForbiddenTypeAnalyzer.AllowedMethodImplBits)."); + } + } + private void CheckOptional(ISymbol? symbol, TextSpan span) { if (symbol is not null) CheckSymbol(symbol, span); diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptStackGuardInjector.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptStackGuardInjector.cs index fbd43b5da..bd9fed528 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptStackGuardInjector.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptStackGuardInjector.cs @@ -28,8 +28,9 @@ namespace ZB.MOM.WW.OtOpcUa.Core.Scripting; /// compiler actually picked, so the block form is compatible with the same delegate type and nothing /// re-binds differently. Lambdas converted to an expression tree (Expression<T>) are left alone: /// a block body is not legal there and an expression tree does not execute script frames. Async lambdas and -/// local functions are left alone (the sandbox denies System.Threading.Tasks, so a script cannot -/// produce one that compiles). +/// local functions are left alone: refuses every async form +/// (lmxopcua#971 review — an async void one compiled without naming System.Threading.Tasks and +/// its exception terminated the host), so none reaches this rewrite. /// /// /// Runs after , so the analyzer only ever sees the user's code; the diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ForbiddenTypeAnalyzerTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ForbiddenTypeAnalyzerTests.cs index 9b6990d10..693be8107 100644 --- a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ForbiddenTypeAnalyzerTests.cs +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ForbiddenTypeAnalyzerTests.cs @@ -77,8 +77,63 @@ public sealed class ForbiddenTypeAnalyzerTests { "AsQueryable", """return new[] { 1, 2 }.AsQueryable().Count();""" }, // ... and the undocumented TypedReference keywords. { "makeref", """int i = 1; var r = __makeref(i); return 0;""" }, + + // Review 2026-12-02 (lmxopcua#971): constructs that passed the allow-list AND the deploy gate and then + // terminated the host process (exit 134). An async void body's exception is rethrown on the thread pool, + // where nothing catches it; an over-sized stackalloc overflows the stack in one frame, before any guard. + { "async-void-local-function", """async void Boom() { throw new InvalidOperationException(); } Boom(); return 0;""" }, + { "static-async-local-function", """static async void Boom() { throw new InvalidOperationException(); } Boom(); return 0;""" }, + { "async-lambda", """Action a = async () => throw new InvalidOperationException(); a(); return 0;""" }, + { "async-simple-lambda", """Action a = async x => throw new InvalidOperationException(); a(1); return 0;""" }, + { "async-anonymous-method", """Action a = async delegate { throw new InvalidOperationException(); }; a(); return 0;""" }, + { "stackalloc", """Span s = stackalloc byte[1_500_000_000]; s[0] = 1; return s.Length;""" }, + { "stackalloc-implicit", """Span s = stackalloc[] { 1, 2, 3 }; return s.Length;""" }, + { "stackalloc-nested", """return M(stackalloc int[4]); static int M(Span s) => s.Length;""" }, + // Siblings: [MethodImpl] flags the runtime acts on. InternalCall passes the gate and then fails to LOAD + // (TypeLoadException at run time — the gate and the runtime disagree); Synchronized takes a monitor (the + // `lock` the analyzer already refuses); a numeric cast must not launder either. + { "MethodImpl-InternalCall", """[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.InternalCall)] static int F() => 1; return F();""" }, + { "MethodImpl-Synchronized", """[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.Synchronized)] static int F() => 1; return F();""" }, + { "MethodImpl-numeric", """[System.Runtime.CompilerServices.MethodImpl((System.Runtime.CompilerServices.MethodImplOptions)4096)] static int F() => 1; return F();""" }, + { "MethodImpl-short-ctor", """[System.Runtime.CompilerServices.MethodImpl((short)32)] static int F() => 1; return F();""" }, }; + /// + /// Siblings of the lmxopcua#971 review that are SAFE and must keep compiling: compiler-lowered constructs whose + /// synthesized code runs on the evaluating thread, inside the run, under the stack guard. + /// + /// The script body. + [Theory] + [InlineData("""System.Collections.Generic.IEnumerable F() { for (var i = 0; ; i++) yield return i; } return F().Take(3).Sum();""")] + [InlineData("""var i = 0; top: i++; if (i < 10) goto top; return i;""")] + [InlineData("""int x = int.MaxValue; try { return checked(x + 1); } catch (OverflowException) { return -1; }""")] + [InlineData("""try { throw new InvalidOperationException(); } catch (Exception e) when (e.Message.Length > 0) { return 1; }""")] + [InlineData("""System.Collections.Generic.List l = [1, 2, 3]; Span s = [4, 5]; int[] a = [.. l, .. s]; return a.Length;""")] + [InlineData("""var x = 1.5; return $"{x:F2} {x,8} {nameof(x)}";""")] + [InlineData("""static int F(params ReadOnlySpan xs) => xs.Length; return F(1, 2, 3);""")] + [InlineData("""using var e = new System.Collections.Generic.List { 1 }.GetEnumerator(); var (a, b) = (1, 2); return a + b;""")] + [InlineData("""[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining | System.Runtime.CompilerServices.MethodImplOptions.NoOptimization)] static int F() => 1; return F();""")] + public async Task Compiler_lowered_construct_still_compiles_and_runs(string source) + { + using var evaluator = ScriptEvaluator.Compile(source); + _ = await evaluator.RunAsync(new FakeScriptContext(), TestContext.Current.CancellationToken); + } + + /// + /// Constructs the C# grammar or the wrapper already refuses — no type, record, finalizer, static constructor or + /// unsafe / fixed / pointer code can be declared in a script body — so no synthesized member + /// of a script-declared type can run outside the walker's view. + /// + /// The script body. + [Theory] + [InlineData("""record R(int A); return new R(1);""")] + [InlineData("""class C { ~C() { } static C() { } } return 0;""")] + [InlineData("""unsafe { int x = 1; int* p = &x; return *p; }""")] + [InlineData("""var a = new int[1]; unsafe { fixed (int* p = a) { return *p; } }""")] + [InlineData("""[System.Runtime.CompilerServices.SkipLocalsInit] static int F() => 1; return F();""")] + [InlineData("""[ThreadStatic] static int F() => 1; return F();""")] + public void Declaration_the_wrapper_cannot_hold_is_refused(string source) => SandboxRefusal.Refuses(source); + /// Each bypass snippet is refused by the publish gate. /// Row label.