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

This commit is contained in:
Joseph Doherty
2026-12-03 12:27:35 -05:00
25 changed files with 1299 additions and 71 deletions
@@ -20,12 +20,31 @@ namespace ZB.MOM.WW.OtOpcUa.Core.Scripting;
/// </para>
/// <para>
/// <b>Limits.</b> The check runs on entry to script-declared code only. A recursion that never re-enters
/// script code (a BCL call that recurses on its own) is not seen — the sandbox gives scripts no such API
/// today. Frames of BCL code between two script frames (a LINQ operator invoking a script lambda) must fit
/// script code (a BCL call that recurses on its own) is not seen. The 2026-12-02 review (lmxopcua#971)
/// found such APIs did exist — <c>Tuple</c> / <c>ValueTuple</c> / <c>KeyValuePair</c> / anonymous-type
/// <c>ToString</c> / <c>Equals</c> / <c>GetHashCode</c> over a structure a script nested a million deep in a
/// loop, a self-referencing <c>Lazy</c>, <c>StructuralComparisons</c> over a self-containing array, an
/// inner-exception chain's <c>ToString</c> — so <c>ForbiddenTypeAnalyzer</c> now refuses the constructs that
/// build such structures (open-element holders, <c>Lazy</c>, the structural comparers, exception
/// constructors taking an inner exception, held <c>FormattableString</c>s, host records with an
/// <c>object</c> member). Frames of BCL code between two script frames (a LINQ operator invoking a script lambda) must fit
/// in the margin; they are a few hundred bytes. The check is per frame, so it bounds depth by the stack
/// that remains, not by a fixed count: the same script may fail at a different depth on a thread with a
/// different stack size (the platform's default thread stack size differs between Windows, Linux and macOS).
/// </para>
/// <para>
/// <b>Exception handlers (lmxopcua#971 review 2026-12-02).</b> Checking frames is not enough on its own: a
/// <c>catch</c> or <c>finally</c> block runs as a funclet <em>on top of</em> the frames being unwound, so a
/// handler that throws (<c>throw;</c>, <c>throw new …</c>, a call that fails the check) starts a nested
/// exception dispatch deeper still — several KB per level. A script that catches-and-rethrows on every frame
/// therefore overflowed the stack while unwinding from the guard's own exception, and 300 frames that each
/// rethrow overflowed with no guard involvement at all. The rewrite also guards every script handler with
/// <see cref="CanHandle"/>: a <c>catch</c> gains the filter <c>when (CanHandle() &amp;&amp; …)</c> and a
/// <c>finally</c> body runs only <c>if (CanHandle())</c>. Once the stack is low, script handlers are skipped,
/// the exception in flight passes to the host in one dispatch (a filter runs and returns without growing the
/// stack), and the run fails with it. Skipping a <c>finally</c> is only possible on a run that is already
/// failing on an exhausted stack.
/// </para>
/// </remarks>
[EditorBrowsable(EditorBrowsableState.Never)]
public static class ScriptStackGuard
@@ -38,6 +57,14 @@ public static class ScriptStackGuard
if (!RuntimeHelpers.TryEnsureSufficientExecutionStack())
throw new ScriptStackExhaustedException();
}
/// <summary>
/// True while the current thread has stack to spare for a script exception handler (see the remarks). Called
/// by compiled scripts from every <c>catch</c> filter and <c>finally</c> block; not part of the script
/// authoring surface.
/// </summary>
/// <returns>False when the remaining stack is below the runtime's safety margin.</returns>
public static bool CanHandle() => RuntimeHelpers.TryEnsureSufficientExecutionStack();
}
/// <summary>
@@ -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
@@ -102,9 +106,13 @@ public static class ForbiddenTypeAnalyzer
// 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",
// Not System.Comparison: it is the only way a script supplies comparer code, and Array / List Sort and
// BinarySearch rethrow a comparer's exception from a catch funclet, so a recursion through Sort overflowed
// the stack while unwinding (lmxopcua#971 review). Order with OrderBy / ThenBy.
"System.Func", "System.Action", "System.Predicate", "System.Converter",
// Small helpers and interfaces. Not System.Lazy: its ToString renders Value, so a Lazy whose value is itself
// recursed forever in BCL code with no script frame for the stack guard (lmxopcua#971 review).
"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",
@@ -133,6 +141,21 @@ public static class ForbiddenTypeAnalyzer
"Serilog.ILogger", "Serilog.Events.LogEventLevel",
];
/// <summary>
/// Types refused although their namespace is in <see cref="AllowedNamespaces"/> (or, for exceptions, they are a
/// <c>System.Exception</c> subclass in <c>System</c>): each one recurses, in BCL code where the stack guard
/// cannot see it, over a structure a script can make cyclic or arbitrarily deep (lmxopcua#971 review).
/// <c>StructuralComparisons</c> / <c>IStructuralEquatable</c> / <c>IStructuralComparable</c> compare an array
/// that contains itself forever; <c>DictionaryEntry.ToString</c> renders an <c>object</c> key and value;
/// <c>AggregateException.Message</c> / <c>ToString</c> render every inner exception.
/// </summary>
public static readonly IReadOnlyList<string> ExcludedTypes =
[
"System.Collections.StructuralComparisons", "System.Collections.IStructuralEquatable",
"System.Collections.IStructuralComparable", "System.Collections.DictionaryEntry",
"System.AggregateException",
];
/// <summary>
/// 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>,
@@ -167,7 +190,7 @@ public static class ForbiddenTypeAnalyzer
("System.Reflection.MemberInfo", "Name"),
];
/// <summary>Members refused on otherwise-allowed types: process-wide state.</summary>
/// <summary>Members refused on otherwise-allowed types: process-wide state, and the untyped array factory.</summary>
public static readonly IReadOnlyList<(string Type, string Member)> ForbiddenMembers =
[
// Ambient culture is process / pool-thread state (lmxopcua#792): name InvariantCulture or GetCultureInfo.
@@ -182,6 +205,9 @@ public static class ForbiddenTypeAnalyzer
// Process-wide regex cache size.
("System.Text.RegularExpressions.Regex", "CacheSize"),
("System.Text.RegularExpressions.Regex", "CompileToAssembly"),
// An object[] behind a System.Array-typed value: the array-element rule (see CheckType) cannot see it.
("System.Array", "CreateInstance"),
("System.Array", "CreateInstanceFromArrayType"),
];
private const string ScriptContextFullName = "ZB.MOM.WW.OtOpcUa.Core.Scripting.ScriptContext";
@@ -189,6 +215,22 @@ public static class ForbiddenTypeAnalyzer
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> ExcludedTypeSet = new(ExcludedTypes, StringComparer.Ordinal);
/// <summary>
/// Generic value holders whose <c>ToString</c> / <c>Equals</c> / <c>GetHashCode</c> / <c>CompareTo</c> recurse
/// into their elements (anonymous types' compiler-synthesized members do the same). With an <em>open</em>
/// element type (<see cref="IsOpenSlot"/>) a script can nest one inside another in a loop —
/// <c>o = Tuple.Create(o)</c> a million times — and any of those members then recurses a million BCL frames
/// deep with no script frame for the stack guard to check: the host died with "Stack overflow." (lmxopcua#971
/// review). With closed element types the nesting depth is fixed by the source.
/// </summary>
private static readonly HashSet<string> RecursiveHolderTypes = new(StringComparer.Ordinal)
{
"System.Tuple", "System.ValueTuple", "System.Collections.Generic.KeyValuePair",
};
private const string FormattableStringFullName = "System.FormattableString";
private static readonly HashSet<(string, string)> AllowedMemberSet = new(AllowedMembers);
private static readonly HashSet<(string, string)> ForbiddenMemberSet = new(ForbiddenMembers);
@@ -255,9 +297,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 +329,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 +363,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);
@@ -310,12 +400,87 @@ public static class ForbiddenTypeAnalyzer
if (node is not ExpressionSyntax expr) return;
var symbol = semantic.GetSymbolInfo(expr).Symbol;
if (symbol is not null) CheckSymbol(symbol, expr.Span);
var deconstructionOnly = IsDeconstructionOnly(expr);
if (symbol is not null) CheckSymbol(symbol, expr.Span, deconstructionOnly);
var typeInfo = semantic.GetTypeInfo(expr);
CheckType(typeInfo.Type, expr.Span);
CheckType(typeInfo.Type, expr.Span, deconstructionOnly);
if (!SymbolEqualityComparer.Default.Equals(typeInfo.Type, typeInfo.ConvertedType))
CheckType(typeInfo.ConvertedType, expr.Span);
CheckType(typeInfo.ConvertedType, expr.Span, deconstructionOnly);
switch (expr)
{
// A FormattableString renders its holes with ToString, so one nested in another's hole in a loop is a
// deep structure like an open tuple. The only producer is an interpolated string converted to
// FormattableString / IFormattable; it may appear only as the argument FormattableString.Invariant /
// CurrentCulture format at once, so no FormattableString value is ever held.
case InterpolatedStringExpressionSyntax interpolated
when typeInfo.ConvertedType is INamedTypeSymbol converted
&& TypeKey(converted.OriginalDefinition) is FormattableStringFullName or "System.IFormattable"
&& !IsFormattableStringFormatArgument(interpolated):
Add(expr.Span, FormattableStringFullName, "System",
"An interpolated string may become a FormattableString only as the argument of " +
"FormattableString.Invariant(…) — a held FormattableString can be nested in another's hole " +
"without limit, and rendering it then recurses past the stack (see ForbiddenTypeAnalyzer).");
break;
// `snapshot with { Value = … }` builds a record whose synthesized Equals / GetHashCode recurse into an
// open-typed member (DataValueSnapshot.Value is object).
case WithExpressionSyntax with
when semantic.GetTypeInfo(with.Expression).Type is INamedTypeSymbol { IsRecord: true } record
&& !IsSourceSymbol(record) && OpenMember(record) is { } openMember:
Add(expr.Span, record.ToDisplayString(), record.ContainingNamespace?.ToDisplayString() ?? string.Empty,
$"A script may not build a '{record.ToDisplayString()}' (its member '{openMember}' holds any value, " +
"so one can be nested in another without limit; see ForbiddenTypeAnalyzer).");
break;
}
}
private bool IsFormattableStringFormatArgument(InterpolatedStringExpressionSyntax interpolated)
=> interpolated.Parent is ArgumentSyntax { Parent: ArgumentListSyntax { Parent: InvocationExpressionSyntax invocation } }
&& semantic.GetSymbolInfo(invocation).Symbol is IMethodSymbol { Name: "Invariant" or "CurrentCulture" } method
&& TypeKey(method.ContainingType.OriginalDefinition) == FormattableStringFullName;
/// <summary>
/// True when <paramref name="expr"/> is a tuple that only exists to be deconstructed — <c>var (a, b) = (x, y)</c>
/// (either side, and the assignment statement itself) or a <c>foreach (var (k, v) in …)</c> target. No
/// tuple value is held, so an open element type there cannot nest.
/// </summary>
private static bool IsDeconstructionOnly(ExpressionSyntax expr)
{
SyntaxNode node = expr;
if (node.Parent is DeclarationExpressionSyntax declaration && declaration.Type == node) node = declaration;
if (node is AssignmentExpressionSyntax { Left: TupleExpressionSyntax or DeclarationExpressionSyntax, Parent: ExpressionStatementSyntax })
return true;
// Only a tuple literal / declaration itself — never an element expression inside one, which is a value.
if (node is not (TupleExpressionSyntax or DeclarationExpressionSyntax)) return false;
while (node.Parent is ArgumentSyntax { Parent: TupleExpressionSyntax tuple }) node = tuple;
return node.Parent switch
{
AssignmentExpressionSyntax { Left: TupleExpressionSyntax or DeclarationExpressionSyntax, Parent: ExpressionStatementSyntax } assignment
=> assignment.Left == node || assignment.Right == node,
ForEachVariableStatementSyntax forEach => forEach.Variable == node,
_ => false,
};
}
/// <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)
@@ -329,12 +494,12 @@ public static class ForbiddenTypeAnalyzer
foreach (var nested in info.Nested) CheckDeconstruction(nested, span);
}
private void CheckSymbol(ISymbol symbol, TextSpan span)
private void CheckSymbol(ISymbol symbol, TextSpan span, bool deconstructionOnly = false)
{
switch (symbol)
{
case ITypeSymbol type:
CheckType(type, span);
CheckType(type, span, deconstructionOnly);
break;
case IMethodSymbol method:
if (method.MethodKind is MethodKind.LocalFunction or MethodKind.AnonymousFunction)
@@ -346,6 +511,7 @@ public static class ForbiddenTypeAnalyzer
CheckMember(method.ReducedFrom ?? method, span);
foreach (var arg in method.TypeArguments) CheckType(arg, span);
if (!method.ReturnsVoid) CheckType(method.ReturnType, span);
if (method.MethodKind == MethodKind.Constructor) CheckConstructor(method, span);
break;
case IPropertySymbol property:
CheckMember(property, span);
@@ -364,6 +530,33 @@ public static class ForbiddenTypeAnalyzer
}
}
/// <summary>
/// Constructors that would let a script nest a value inside one of the same kind without limit: an
/// exception constructor taking an inner exception (or any <c>object</c>, e.g.
/// <c>ArgumentOutOfRangeException</c>'s <c>actualValue</c>, which its <c>Message</c> renders) — a loop builds
/// a million-deep chain whose <c>ToString</c> / <c>Message</c> recurse past the stack, in the script or in
/// the host's log sink — and a host record with an open-typed member (<c>new DataValueSnapshot(o, …)</c>).
/// </summary>
private void CheckConstructor(IMethodSymbol constructor, TextSpan span)
{
var type = constructor.ContainingType;
if (type is null || IsSourceSymbol(type) || type.IsAnonymousType) return;
var ns = type.ContainingNamespace?.ToDisplayString() ?? string.Empty;
if (DerivesFrom(type, ExceptionFullName)
&& constructor.Parameters.FirstOrDefault(p => IsExceptionChainSlot(p.Type)) is { } inner)
{
Add(span, $"{TypeKey(type.OriginalDefinition)}..ctor", ns,
$"This '{type.Name}' constructor takes '{inner.Name}' ({inner.Type.ToDisplayString()}): a script may not " +
"wrap one exception (or an arbitrary value) inside another — a chain built in a loop overflows the " +
"stack when it is rendered (see ForbiddenTypeAnalyzer). Use a constructor taking only a message.");
return;
}
if (type.IsRecord && OpenMember(type) is { } openMember)
Add(span, $"{TypeKey(type.OriginalDefinition)}..ctor", ns,
$"A script may not build a '{type.ToDisplayString()}' (its member '{openMember}' holds any value, so one " +
"can be nested in another without limit; see ForbiddenTypeAnalyzer).");
}
private void CheckMember(ISymbol member, TextSpan span)
{
var declaring = member.ContainingType;
@@ -378,7 +571,7 @@ public static class ForbiddenTypeAnalyzer
if (ForbiddenMemberSet.Contains(pair))
{
Add(span, display, ns,
$"Member '{display}' is on the sandbox forbidden-member list: it changes process-wide state " +
$"Member '{display}' is on the sandbox forbidden-member list: it changes process-wide state or escapes another rule " +
"(see ForbiddenTypeAnalyzer.ForbiddenMembers).");
return;
}
@@ -400,7 +593,11 @@ public static class ForbiddenTypeAnalyzer
"sandbox allow-list (see ForbiddenTypeAnalyzer.AllowedTypes).");
}
private void CheckType(ITypeSymbol? type, TextSpan span)
/// <param name="type">The type.</param>
/// <param name="span">Where to report.</param>
/// <param name="deconstructionOnly">The expression is a tuple that is only deconstructed (never held), so a
/// tuple with an open element type is allowed there — see <see cref="IsDeconstructionOnly"/>.</param>
private void CheckType(ITypeSymbol? type, TextSpan span, bool deconstructionOnly = false)
{
switch (type)
{
@@ -409,7 +606,19 @@ public static class ForbiddenTypeAnalyzer
case ITypeParameterSymbol:
return;
case IArrayTypeSymbol array:
CheckType(array.ElementType, span);
// An array whose element can be an array (object[], Array[], IList[] …) can nest or contain itself;
// the HOST copies a returned array recursively (OwnedDataSample.CopyLegacy) and compares it
// structurally (VirtualTagActor.SameValue), so such a value overflowed the host's stack after the
// run (lmxopcua#971 review). Typed and jagged arrays (int[][]) nest only as deep as the source.
if (IsOpenSlot(array.ElementType) || array.ElementType.SpecialType == SpecialType.System_Array)
{
Add(span, type.ToDisplayString(), string.Empty,
$"An array of '{array.ElementType.ToDisplayString()}' can contain itself or nest without limit, " +
"which the server's own copy / compare of a script value recurses over — use a typed array " +
"(double[], string[], …) — see ForbiddenTypeAnalyzer.");
return;
}
CheckType(array.ElementType, span, deconstructionOnly);
return;
case IPointerTypeSymbol or IFunctionPointerTypeSymbol:
Add(span, type.ToDisplayString(), string.Empty, $"Pointer type '{type.ToDisplayString()}' is not allowed in a script.");
@@ -423,7 +632,16 @@ public static class ForbiddenTypeAnalyzer
"(see ForbiddenTypeAnalyzer.AllowedTypes / AllowedNamespaces).");
return;
}
foreach (var arg in named.TypeArguments) CheckType(arg, span);
if (!deconstructionOnly && OpenHolderElement(named) is { } open)
{
Add(span, named.ToDisplayString(), named.ContainingNamespace?.ToDisplayString() ?? string.Empty,
$"'{named.ToDisplayString()}' holds a value of type '{open.ToDisplayString()}', which can be " +
"another one of itself: nested in a loop, its ToString / Equals / GetHashCode then recurse past " +
"the stack and terminate the server. Give the tuple / pair / anonymous type a concrete element " +
"type (e.g. Convert.ToDouble(v.Value)) — see ForbiddenTypeAnalyzer.");
return;
}
foreach (var arg in named.TypeArguments) CheckType(arg, span, deconstructionOnly);
return;
default:
// dynamic and anything else unrecognised.
@@ -440,6 +658,7 @@ public static class ForbiddenTypeAnalyzer
var def = type.OriginalDefinition;
if (def.ContainingType is { } outer) return IsTypeAllowedShallow(outer);
var key = TypeKey(def);
if (ExcludedTypeSet.Contains(key)) return false;
if (AllowedTypeSet.Contains(key) || RestrictedTypeMembers.ContainsKey(key)) return true;
var ns = def.ContainingNamespace?.ToDisplayString() ?? string.Empty;
if (AllowedNamespaceSet.Contains(ns)) return true;
@@ -457,6 +676,41 @@ public static class ForbiddenTypeAnalyzer
}
}
/// <summary>
/// An element / member type that can hold an instance of the holder around it: <c>object</c>,
/// <c>ValueType</c>, an interface, a type parameter or <c>dynamic</c> (or a <c>Nullable</c> of one).
/// </summary>
private static bool IsOpenSlot(ITypeSymbol type) => type switch
{
{ SpecialType: SpecialType.System_Object or SpecialType.System_ValueType } => true,
{ TypeKind: TypeKind.Interface or TypeKind.TypeParameter or TypeKind.Dynamic } => true,
INamedTypeSymbol { OriginalDefinition.SpecialType: SpecialType.System_Nullable_T } nullable => IsOpenSlot(nullable.TypeArguments[0]),
_ => false,
};
/// <summary>The open element type of a <see cref="RecursiveHolderTypes"/> instance or anonymous type, if any.</summary>
private static ITypeSymbol? OpenHolderElement(INamedTypeSymbol type)
{
if (type.IsAnonymousType)
return type.GetMembers().OfType<IPropertySymbol>().Select(p => p.Type).FirstOrDefault(IsOpenSlot);
return RecursiveHolderTypes.Contains(TypeKey(type.OriginalDefinition))
? type.TypeArguments.FirstOrDefault(IsOpenSlot)
: null;
}
/// <summary>The name of a record's first instance property of an open type (its synthesized members recurse into it).</summary>
private static string? OpenMember(INamedTypeSymbol record)
=> record.GetMembers().OfType<IPropertySymbol>().FirstOrDefault(p => !p.IsStatic && IsOpenSlot(p.Type))?.Name;
/// <summary>A constructor parameter through which one exception can carry another (or any value).</summary>
private static bool IsExceptionChainSlot(ITypeSymbol type) => type switch
{
_ when IsOpenSlot(type) => true,
IArrayTypeSymbol array => IsExceptionChainSlot(array.ElementType),
INamedTypeSymbol named => DerivesFrom(named, ExceptionFullName) || named.TypeArguments.Any(IsExceptionChainSlot),
_ => false,
};
private static bool DerivesFrom(INamedTypeSymbol type, string fullName)
{
for (var t = type; t is not null; t = t.BaseType)
@@ -28,8 +28,16 @@ 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&lt;T&gt;</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>
/// <b>Exception handlers (lmxopcua#971 review).</b> Every script <c>catch</c> also gets the filter
/// <c>when (ScriptStackGuard.CanHandle() &amp;&amp; (original filter))</c>, and every <c>finally</c> body is
/// wrapped in <c>if (ScriptStackGuard.CanHandle()) { … }</c>: a handler runs on top of the frames being
/// unwound, so one that throws on every frame overflowed the stack while unwinding (see
/// <see cref="ScriptStackGuard"/>). On a healthy stack both are no-ops.
/// </para>
/// <para>
/// Runs after <see cref="ForbiddenTypeAnalyzer"/>, so the analyzer only ever sees the user's code; the
@@ -39,6 +47,7 @@ namespace ZB.MOM.WW.OtOpcUa.Core.Scripting;
internal static class ScriptStackGuardInjector
{
private const string CheckCall = "global::ZB.MOM.WW.OtOpcUa.Core.Scripting.ScriptStackGuard.Check()";
private const string CanHandleCall = "global::ZB.MOM.WW.OtOpcUa.Core.Scripting.ScriptStackGuard.CanHandle()";
/// <summary>Returns <paramref name="tree"/> with a stack check at the entry of every script-declared body.</summary>
/// <param name="compilation">The compiled (error-free, analyzer-clean) wrapper compilation.</param>
@@ -64,6 +73,25 @@ internal static class ScriptStackGuardInjector
private sealed class Rewriter(SemanticModel model) : CSharpSyntaxRewriter
{
/// <summary><c>catch … when (f)</c> becomes <c>catch … when (CanHandle() &amp;&amp; (f))</c> — see
/// <see cref="ScriptStackGuard"/>'s "Exception handlers" remarks.</summary>
public override SyntaxNode? VisitCatchClause(CatchClauseSyntax node)
{
var visited = (CatchClauseSyntax)base.VisitCatchClause(node)!;
ExpressionSyntax canHandle = ParseExpression(CanHandleCall);
var condition = visited.Filter is { } filter
? BinaryExpression(SyntaxKind.LogicalAndExpression, canHandle, ParenthesizedExpression(filter.FilterExpression))
: canHandle;
return visited.WithFilter(CatchFilterClause(condition));
}
/// <summary><c>finally { b }</c> becomes <c>finally { if (CanHandle()) { b } }</c>.</summary>
public override SyntaxNode? VisitFinallyClause(FinallyClauseSyntax node)
{
var visited = (FinallyClauseSyntax)base.VisitFinallyClause(node)!;
return visited.WithBlock(Block(IfStatement(ParseExpression(CanHandleCall), visited.Block)));
}
public override SyntaxNode? VisitMethodDeclaration(MethodDeclarationSyntax node)
{
// The only method in the wrapper is the synthesized CompiledScript.Run (ScriptEvaluator enforces that).