fix(scripting): #971 review — refuse async lambdas/local functions, stackalloc and runtime-binding [MethodImpl] flags
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 <noreply@anthropic.com>
This commit is contained in:
+1
-1
@@ -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<int>`).
|
||||
The rules (`ForbiddenTypeAnalyzer`): every type a script names, and every type an expression evaluates or converts to, must be allowed (generic arguments and array elements included); every member used must be declared on an allowed type (or be in `AllowedMembers`), must not be in `ForbiddenMembers` (`CultureInfo.CurrentCulture` and the other ambient-culture setters, `TimeZoneInfo.ClearCachedData`, `Encoding.RegisterProvider`, `Regex.CacheSize`), and its return type must be allowed — which is what keeps reflection handles out of reach (`Exception.TargetSite` is a member of an allowed type but returns a `MethodBase`; `Delegate.Method` / `DynamicInvoke` are declared on the un-listed `System.Delegate`). `__makeref` / `__refvalue` / `__reftype` / `__arglist`, `lock`, and `extern` local functions are refused syntactically, and so — since the 2026-12-02 security review — are **`async` lambdas / anonymous methods / local functions** and **`stackalloc`**: each compiled through the allow-list *and* the deploy gate and then terminated the host (exit 134). An `async void` body's exception is rethrown on the thread pool by a compiler-synthesized builder no allow-list check sees, and one over-sized `stackalloc` overflows the stack inside a single frame, before any stack guard runs. `[MethodImpl]` on a local function may set only the JIT hints (`NoInlining` / `NoOptimization` / `AggressiveInlining` / `AggressiveOptimization`): `InternalCall` passed the gate and then failed to load, and `Synchronized` is a `lock`. Members the compiler calls without a name in the source — query operators, `foreach`'s enumerator pattern, `Deconstruct`, a collection initializer's `Add` — are checked like named ones. Pre-imported namespaces are unchanged (`System`, `System.Linq`, `ZB.MOM.WW.OtOpcUa.Core.Abstractions`, `ZB.MOM.WW.OtOpcUa.Core.Scripting`) — a collection still needs its full name (`System.Collections.Generic.List<int>`).
|
||||
|
||||
`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.
|
||||
|
||||
|
||||
@@ -49,7 +49,11 @@ namespace ZB.MOM.WW.OtOpcUa.Core.Scripting;
|
||||
/// 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.
|
||||
/// <c>lock</c> (a blocking primitive on a possibly-shared object), <c>extern</c> local functions,
|
||||
/// <c>async</c> lambdas / local functions and <c>stackalloc</c> (each terminated the host —
|
||||
/// lmxopcua#971 review 2026-12-02); <c>[MethodImpl]</c> is limited to the JIT hint bits. (4) Members the
|
||||
/// compiler calls without a name in the source — query operators, <c>foreach</c>'s enumerator pattern,
|
||||
/// <c>Deconstruct</c>, a collection initializer's <c>Add</c> — are checked like named ones.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <b>Defence in depth.</b> <see cref="ScriptSandbox"/> also references only the handful of BCL assemblies
|
||||
@@ -255,9 +259,28 @@ public static class ForbiddenTypeAnalyzer
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// blocking monitor on an object that may be shared with the host, e.g. <c>lock (typeof(string))</c>),
|
||||
/// <c>extern</c> local functions (a native entry point), <c>async</c> lambdas / anonymous methods / local
|
||||
/// functions, and <c>stackalloc</c>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// <b><c>async</c> (lmxopcua#971 review 2026-12-02).</b> 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
|
||||
/// <c>async void</c> body's exception is not returned to the caller: <c>AsyncVoidMethodBuilder</c>
|
||||
/// rethrows it on the thread pool, where nothing catches it and the runtime terminates the host
|
||||
/// (<c>async void Boom() { throw … } Boom();</c> — and an <c>async</c> lambda converted to
|
||||
/// <c>Action</c> is the same thing). A script is synchronous by contract
|
||||
/// (<see cref="ScriptEvaluator{TContext, TResult}.RunAsync"/>) and <c>System.Threading.Tasks</c> is not
|
||||
/// on the allow-list, so there is no legitimate <c>async</c> script code: every form is refused, which
|
||||
/// also covers <c>await</c>, <c>await foreach</c> and <c>await using</c> (legal only inside one).
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <b><c>stackalloc</c>.</b> One <c>stackalloc byte[1_500_000_000]</c> overflows the thread's stack inside
|
||||
/// a single frame — before the next <c>ScriptStackGuard.Check()</c> can run — and a stack overflow is
|
||||
/// uncatchable. Scripts have heap arrays and <c>Span</c> over them; there is no need for stack buffers.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
/// <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
|
||||
@@ -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,
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// The <see cref="System.Runtime.CompilerServices.MethodImplOptions"/> bits a script's <c>[MethodImpl]</c> may
|
||||
/// set: JIT inlining / optimization hints only. <c>InternalCall</c> / <c>ForwardRef</c> / <c>Unmanaged</c> /
|
||||
/// <c>PreserveSig</c> change how the runtime binds the method (an <c>InternalCall</c> local function passes the
|
||||
/// compiler and fails to load — the publish gate accepted what the runtime refuses), and <c>Synchronized</c>
|
||||
/// takes a monitor (the <c>lock</c> the analyzer refuses).
|
||||
/// </summary>
|
||||
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<ForbiddenTypeRejection> 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);
|
||||
}
|
||||
|
||||
/// <summary>Refuses <c>[MethodImpl]</c> flags outside <see cref="AllowedMethodImplBits"/>, however spelled.</summary>
|
||||
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);
|
||||
|
||||
@@ -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 (<c>Expression<T></c>) 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 <c>System.Threading.Tasks</c>, so a script cannot
|
||||
/// produce one that compiles).
|
||||
/// local functions are left alone: <see cref="ForbiddenTypeAnalyzer"/> refuses every <c>async</c> form
|
||||
/// (lmxopcua#971 review — an <c>async void</c> one compiled without naming <c>System.Threading.Tasks</c> and
|
||||
/// its exception terminated the host), so none reaches this rewrite.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Runs after <see cref="ForbiddenTypeAnalyzer"/>, so the analyzer only ever sees the user's code; the
|
||||
|
||||
@@ -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<int> 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<byte> s = stackalloc byte[1_500_000_000]; s[0] = 1; return s.Length;""" },
|
||||
{ "stackalloc-implicit", """Span<int> s = stackalloc[] { 1, 2, 3 }; return s.Length;""" },
|
||||
{ "stackalloc-nested", """return M(stackalloc int[4]); static int M(Span<int> 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();""" },
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="source">The script body.</param>
|
||||
[Theory]
|
||||
[InlineData("""System.Collections.Generic.IEnumerable<int> 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<int> l = [1, 2, 3]; Span<int> 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<int> xs) => xs.Length; return F(1, 2, 3);""")]
|
||||
[InlineData("""using var e = new System.Collections.Generic.List<int> { 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<FakeScriptContext, object?>.Compile(source);
|
||||
_ = await evaluator.RunAsync(new FakeScriptContext(), TestContext.Current.CancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Constructs the C# grammar or the wrapper already refuses — no type, record, finalizer, static constructor or
|
||||
/// <c>unsafe</c> / <c>fixed</c> / 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.
|
||||
/// </summary>
|
||||
/// <param name="source">The script body.</param>
|
||||
[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);
|
||||
|
||||
|
||||
/// <summary>Each bypass snippet is refused by the publish gate.</summary>
|
||||
/// <param name="name">Row label.</param>
|
||||
|
||||
Reference in New Issue
Block a user