fix(script-analysis): inspect ?. member bindings and CreateDelegate in the trust gate (CMN-1, WP1 task 1.1)
The reflection-gateway check ran only in VisitMemberAccessExpression, so recv?.GetMethod(...) (a MemberBindingExpression) was never inspected and Delegate.CreateDelegate turned the MethodInfo into a callable delegate: one character defeated the trust gate on all four call sites. - HardeningWalker gains VisitMemberBindingExpression with the same check. - CreateDelegate joins ReflectionGatewayMembers. - Pass 1 also flags a gateway-named framework member reached as a bare identifier (using static System.Delegate / System.Type). Tests: the review's probe script (compiles clean, now rejected, also on the minimal fallback set), the ?. variant of every .-form rejection test, every gateway member via ?., and legitimate ?. use stays clean.
This commit is contained in:
@@ -66,7 +66,9 @@ The scoping rationale: `System.Diagnostics.Process` is the dangerous type (spawn
|
||||
|
||||
The following member names are blocked regardless of the receiver type, to prevent reflection-based bypasses such as `typeof(x).Assembly.GetType("System.IO.File")`:
|
||||
|
||||
`GetType`, `GetTypeInfo`, `Assembly`, `Module`, `CreateInstance`, `InvokeMember`, `GetMethod`, `GetMethods`, `GetConstructor`, `GetConstructors`, `GetField`, `GetFields`, `GetProperty`, `GetProperties`, `GetMember`, `GetMembers`, `GetRuntimeMethod`, `GetRuntimeMethods`, `MethodHandle`, `TypeHandle`, `GetTypes`, `EntryPoint`, `DeclaredMethods`, `DeclaredMembers`, `DeclaredConstructors`, `DynamicInvoke`.
|
||||
`GetType`, `GetTypeInfo`, `Assembly`, `Module`, `CreateInstance`, `InvokeMember`, `GetMethod`, `GetMethods`, `GetConstructor`, `GetConstructors`, `GetField`, `GetFields`, `GetProperty`, `GetProperties`, `GetMember`, `GetMembers`, `GetRuntimeMethod`, `GetRuntimeMethods`, `MethodHandle`, `TypeHandle`, `GetTypes`, `EntryPoint`, `DeclaredMethods`, `DeclaredMembers`, `DeclaredConstructors`, `DynamicInvoke`, `CreateDelegate`.
|
||||
|
||||
The check applies to **every spelling** that reaches a member: a member access (`recv.GetMethod(...)`), a conditional member binding (`recv?.GetMethod(...)` — code review 2026-12-02 CMN-1: before this the `?.` form was not inspected at all, so one character defeated the gate), and a bare identifier that resolves to a framework member of that name (e.g. `CreateDelegate(...)` after `using static System.Delegate;`). `CreateDelegate` joined the list with CMN-1: `Delegate.CreateDelegate` turns a `MethodInfo` — obtainable from `System.Type`, which is not a forbidden scope — into a directly callable delegate without naming any `System.Reflection` member.
|
||||
|
||||
`Invoke` is **deliberately excluded** from this list: the syntactic pass rejects a gateway member regardless of receiver, and `delegate.Invoke()` (`Func<>`/`Action<>` invocation) is a legitimate, common script pattern. The reflection late-bind `MethodInfo.Invoke` is already caught semantically via the `System.Reflection` scope, so excluding `Invoke` here avoids a false-positive blast radius without weakening the reflection deny-list.
|
||||
|
||||
@@ -105,8 +107,8 @@ The two reference sets are deliberately distinct and must not be conflated:
|
||||
|
||||
**Pass 2 — syntactic reflection-gateway and identifier hardening (adapted from Inbound API)**
|
||||
|
||||
- Walks the syntax tree for member-access expressions and simple name references.
|
||||
- Flags any member name found in `ScriptTrustPolicy.ReflectionGatewayMembers`, regardless of receiver type.
|
||||
- Walks the syntax tree for member-access expressions, conditional member bindings (`?.`) and simple name references.
|
||||
- Flags any member name found in `ScriptTrustPolicy.ReflectionGatewayMembers`, regardless of receiver type, in both the `.` and the `?.` form. (Pass 1 additionally flags a gateway-named framework member reached as a bare identifier, e.g. through `using static`.)
|
||||
- Flags any identifier token found in `ScriptTrustPolicy.ForbiddenIdentifiers` (`dynamic`, `Activator`).
|
||||
|
||||
Violations from both passes are merged and deduplicated before being returned.
|
||||
|
||||
@@ -111,6 +111,11 @@ public static class ScriptTrustPolicy
|
||||
"DeclaredMembers",
|
||||
"DeclaredConstructors",
|
||||
"DynamicInvoke",
|
||||
// Code review 2026-12-02 CMN-1: Delegate.CreateDelegate / MethodInfo.CreateDelegate
|
||||
// turn a MethodInfo (obtainable from System.Type, which is not a forbidden scope)
|
||||
// into a directly-callable delegate, so a forbidden method can be invoked without
|
||||
// ever naming a System.Reflection member. No legitimate script use.
|
||||
"CreateDelegate",
|
||||
// DELIBERATELY EXCLUDED: "Invoke". The syntactic pass rejects a gateway
|
||||
// member regardless of receiver, and delegate.Invoke() is a legitimate,
|
||||
// common script pattern (Func<>/Action<> invocation). MethodInfo.Invoke
|
||||
|
||||
@@ -163,6 +163,20 @@ public static class ScriptTrustValidator
|
||||
var info = model.GetSymbolInfo(node);
|
||||
var symbol = info.Symbol ?? info.CandidateSymbols.FirstOrDefault();
|
||||
|
||||
// Code review 2026-12-02 CMN-1: a reflection-gateway member reached WITHOUT a
|
||||
// member-access spelling — a bare identifier brought in by `using static
|
||||
// System.Delegate;` / `using static System.Type;` — never reaches the syntactic
|
||||
// walker's member-access/member-binding checks. Judge it by the resolved
|
||||
// symbol's name instead. Only framework (metadata) members count, so a
|
||||
// script-declared helper that happens to share a gateway name is not flagged.
|
||||
// The message matches the syntactic pass's so a `.`-spelled use dedupes.
|
||||
if (symbol is IMethodSymbol or IPropertySymbol or IFieldSymbol or IEventSymbol
|
||||
&& ScriptTrustPolicy.ReflectionGatewayMembers.Contains(symbol.Name)
|
||||
&& symbol.Locations.All(l => l.IsInMetadata))
|
||||
{
|
||||
violations.Add($"forbidden reflection member access '.{symbol.Name}'");
|
||||
}
|
||||
|
||||
// The set of fully-qualified scopes this reference touches: the
|
||||
// resolved symbol's containing namespace and type, or — when the
|
||||
// symbol could not be resolved (a type from an unreferenced
|
||||
@@ -423,6 +437,24 @@ public static class ScriptTrustValidator
|
||||
base.VisitMemberAccessExpression(node);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Code review 2026-12-02 CMN-1: the member on the right of a conditional access
|
||||
/// (<c>recv?.GetMethod(...)</c>) is a <see cref="MemberBindingExpressionSyntax"/>, not
|
||||
/// a <see cref="MemberAccessExpressionSyntax"/>, so it never reached
|
||||
/// <see cref="VisitMemberAccessExpression"/>. Apply the same receiver-agnostic
|
||||
/// gateway check to it. (A <c>?.</c> chain is a conditional access whose
|
||||
/// <c>WhenNotNull</c> part holds the bindings, so every link is visited.)
|
||||
/// </summary>
|
||||
/// <param name="node">The member-binding node.</param>
|
||||
public override void VisitMemberBindingExpression(MemberBindingExpressionSyntax node)
|
||||
{
|
||||
var memberName = node.Name.Identifier.ValueText;
|
||||
if (ScriptTrustPolicy.ReflectionGatewayMembers.Contains(memberName))
|
||||
_violations.Add($"forbidden reflection member access '.{memberName}'");
|
||||
|
||||
base.VisitMemberBindingExpression(node);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public override void VisitIdentifierName(IdentifierNameSyntax node)
|
||||
{
|
||||
|
||||
+186
@@ -0,0 +1,186 @@
|
||||
using ZB.MOM.WW.ScadaBridge.ScriptAnalysis;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.ScriptAnalysis.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Code review 2026-12-02 CMN-1 (WP1 task 1.1): the reflection-gateway check used to run
|
||||
/// only inside <c>VisitMemberAccessExpression</c>, so the same member reached through a
|
||||
/// conditional access (<c>recv?.GetMethod(...)</c> — a <c>MemberBindingExpression</c>) was
|
||||
/// never inspected, and <c>Delegate.CreateDelegate</c> turned the resulting
|
||||
/// <c>MethodInfo</c> into a callable delegate without naming any forbidden scope. These
|
||||
/// tests pin the <c>?.</c> form of every <c>.</c>-form rejection in
|
||||
/// <see cref="ScriptTrustValidatorTests"/>, plus the probe script from the review.
|
||||
/// </summary>
|
||||
public class ScriptTrustValidatorConditionalAccessTests
|
||||
{
|
||||
/// <summary>
|
||||
/// The review's probe: reach <c>Type.GetType(string)</c> and <c>File.ReadAllText</c>
|
||||
/// with nothing but <c>?.</c> member bindings on permitted types and
|
||||
/// <c>Delegate.CreateDelegate</c>. The forbidden type is named only in a string
|
||||
/// literal. Before the fix this produced zero violations and compiled clean.
|
||||
/// </summary>
|
||||
private const string ProbeScript = """
|
||||
var getType = (Func<string, Type>)Delegate.CreateDelegate(
|
||||
typeof(Func<string, Type>),
|
||||
typeof(Type)?.GetMethod("GetType", new[] { typeof(string) }));
|
||||
var fileType = getType("System.IO.File");
|
||||
var read = (Func<string, string>)Delegate.CreateDelegate(
|
||||
typeof(Func<string, string>),
|
||||
fileType?.GetMethod("ReadAllText", new[] { typeof(string) }));
|
||||
return read("/etc/passwd");
|
||||
""";
|
||||
|
||||
/// <summary>The probe is a real program: it compiles against the script reference set.</summary>
|
||||
[Fact]
|
||||
public void Probe_CompilesCleanly_SoTheValidatorIsTheOnlyGate()
|
||||
{
|
||||
Assert.Empty(RoslynScriptCompiler.Compile(ProbeScript));
|
||||
}
|
||||
|
||||
/// <summary>The probe script is rejected by the trust validator.</summary>
|
||||
[Fact]
|
||||
public void Probe_IsRejected()
|
||||
{
|
||||
var violations = ScriptTrustValidator.FindViolations(ProbeScript);
|
||||
Assert.Contains(violations, v => v.Contains("'.GetMethod'", StringComparison.Ordinal));
|
||||
Assert.Contains(violations, v => v.Contains("'.CreateDelegate'", StringComparison.Ordinal));
|
||||
}
|
||||
|
||||
/// <summary>The probe is also rejected on the degraded (TPA-fallback) reference set.</summary>
|
||||
[Fact]
|
||||
public void Probe_IsRejected_OnMinimalFallbackReferences()
|
||||
{
|
||||
var minimal = ScriptTrustPolicy.BuildMinimalFallbackReferences();
|
||||
Assert.NotEmpty(ScriptTrustValidator.FindViolations(ProbeScript, minimal));
|
||||
}
|
||||
|
||||
/// <summary>The <c>?.</c> half of the probe alone (no CreateDelegate) is rejected.</summary>
|
||||
[Fact]
|
||||
public void ConditionalGetMethod_OffPermittedType_IsRejected()
|
||||
{
|
||||
var code = "var m = typeof(Type)?.GetMethod(\"GetType\", new[] { typeof(string) });";
|
||||
Assert.NotEmpty(ScriptTrustValidator.FindViolations(code));
|
||||
}
|
||||
|
||||
/// <summary><c>Delegate.CreateDelegate</c> is a reflection gateway in both access forms.</summary>
|
||||
/// <param name="code">The script source.</param>
|
||||
[Theory]
|
||||
[InlineData("var d = Delegate.CreateDelegate(typeof(Action), null, \"x\");")]
|
||||
[InlineData("var d = System.Delegate.CreateDelegate(typeof(Action), null, \"x\");")]
|
||||
[InlineData("Action a = () => {}; var d = a.Method?.CreateDelegate(typeof(Action));")]
|
||||
public void CreateDelegate_IsRejected(string code)
|
||||
{
|
||||
Assert.NotEmpty(ScriptTrustValidator.FindViolations(code));
|
||||
}
|
||||
|
||||
/// <summary>Every reflection-gateway member is rejected when reached through <c>?.</c>.</summary>
|
||||
/// <param name="member">A <see cref="ScriptTrustPolicy.ReflectionGatewayMembers"/> name.</param>
|
||||
[Theory]
|
||||
[MemberData(nameof(GatewayMembers))]
|
||||
public void EveryGatewayMember_ViaConditionalAccess_IsRejected(string member)
|
||||
{
|
||||
Assert.NotEmpty(ScriptTrustValidator.FindViolations($"object o = null; var x = o?.{member};"));
|
||||
Assert.NotEmpty(ScriptTrustValidator.FindViolations($"object o = null; var x = o?.{member}();"));
|
||||
// Chained: the gateway sits mid-chain behind another binding.
|
||||
Assert.NotEmpty(ScriptTrustValidator.FindViolations($"string s = null; var x = s?.Length.ToString()?.{member};"));
|
||||
}
|
||||
|
||||
/// <summary>Every reflection-gateway member is still rejected through plain <c>.</c> (control).</summary>
|
||||
/// <param name="member">A <see cref="ScriptTrustPolicy.ReflectionGatewayMembers"/> name.</param>
|
||||
[Theory]
|
||||
[MemberData(nameof(GatewayMembers))]
|
||||
public void EveryGatewayMember_ViaMemberAccess_IsRejected(string member)
|
||||
{
|
||||
Assert.NotEmpty(ScriptTrustValidator.FindViolations($"object o = null; var x = o.{member};"));
|
||||
}
|
||||
|
||||
/// <summary>The gateway member names, as theory data.</summary>
|
||||
/// <returns>One row per gateway member.</returns>
|
||||
public static IEnumerable<object[]> GatewayMembers() =>
|
||||
ScriptTrustPolicy.ReflectionGatewayMembers.Order(StringComparer.Ordinal).Select(m => new object[] { m });
|
||||
|
||||
/// <summary>
|
||||
/// The <c>?.</c> form of every <c>.</c>-form rejection test in
|
||||
/// <see cref="ScriptTrustValidatorTests"/> (where a <c>?.</c> spelling exists). Some of
|
||||
/// these are not valid C# for a static receiver, but the validator judges syntax and
|
||||
/// symbols, not compilability, and must reject them all.
|
||||
/// </summary>
|
||||
/// <param name="code">The script source.</param>
|
||||
[Theory]
|
||||
// MG1_RejectsRuntimeEscapeApis
|
||||
[InlineData("object o = new object(); System.Runtime.CompilerServices.Unsafe?.As<object, string>(ref o);")]
|
||||
[InlineData("System.Runtime.CompilerServices.RuntimeHelpers?.GetUninitializedObject(typeof(object));")]
|
||||
[InlineData("using U = System.Runtime.CompilerServices.Unsafe; object o = new object(); U?.As<object, string>(ref o);")]
|
||||
// Rejects_SystemIo_*
|
||||
[InlineData("using System.IO; var x = File?.ReadAllText(\"/etc/passwd\");")]
|
||||
[InlineData("var x = global::System.IO.File?.ReadAllText(\"x\");")]
|
||||
[InlineData("using IO = System.IO; var f = IO.File?.ReadAllText(\"x\");")]
|
||||
// Rejects_ReflectionGateway_OffPermittedType
|
||||
[InlineData("var t = typeof(string)?.Assembly?.GetType(\"System.IO.File\");")]
|
||||
[InlineData("var t = typeof(string)?.Assembly.GetType(\"System.IO.File\");")]
|
||||
[InlineData("var t = typeof(string).Assembly?.GetType(\"System.IO.File\");")]
|
||||
[InlineData("var a = typeof(string)?.Assembly;")]
|
||||
// Rejects_Dynamic_Keyword
|
||||
[InlineData("dynamic d = 5; d?.Foo();")]
|
||||
// Rejects_Activator_CreateInstance (+ verbatim / unicode-escape spellings)
|
||||
[InlineData("var o = Activator?.CreateInstance(typeof(string));")]
|
||||
[InlineData("var o = @Activator?.CreateInstance(typeof(string));")]
|
||||
[InlineData("var o = \\u0041ctivator?.CreateInstance(typeof(string));")]
|
||||
// Rejects_RuntimeInteropServices / Rejects_MicrosoftWin32
|
||||
[InlineData("using System.Runtime.InteropServices; var h = Marshal?.SizeOf<int>();")]
|
||||
[InlineData("using Microsoft.Win32; var k = Registry?.LocalMachine;")]
|
||||
// Rejects_Threading_Thread_Sleep / Rejects_DirectThreadingMutex_NotThreadSleep
|
||||
[InlineData("System.Threading.Thread?.Sleep(10);")]
|
||||
[InlineData("var m = new System.Threading.Mutex()?.SafeWaitHandle;")]
|
||||
// Rejects_All_SystemNet
|
||||
[InlineData("var w = new System.Net.WebClient()?.BaseAddress;")]
|
||||
// Rejects_ReflectionGateway_OffAllowedTaskType
|
||||
[InlineData("var a = System.Threading.Tasks.Task.CompletedTask?.GetType()?.Assembly;")]
|
||||
[InlineData("var a = System.Threading.Tasks.Task.CompletedTask?.GetType().Assembly;")]
|
||||
// Rejects_ForbiddenIo_NestedInAllowedTaskRunLambda
|
||||
[InlineData("await System.Threading.Tasks.Task.Run(() => System.IO.File?.ReadAllText(\"x\"));")]
|
||||
// Rejects_Process_QualifiedType / Rejects_Process_BareIdentifier_ViaUsing
|
||||
[InlineData("var p = System.Diagnostics.Process?.Start(\"x\");")]
|
||||
[InlineData("using System.Diagnostics; var p = Process?.Start(\"x\");")]
|
||||
// Rejects_ExtensionMethod_InForbiddenNamespace
|
||||
[InlineData("using System.Reflection; Assembly asm = null; var a = asm?.GetCustomAttribute<System.ObsoleteAttribute>();")]
|
||||
// Rejects_ForbiddenApi_InsideUnsafeBlock
|
||||
[InlineData("unsafe { var t = typeof(string)?.Assembly; }")]
|
||||
// FindViolations_Flags
|
||||
[InlineData("Environment?.Exit(0);")]
|
||||
[InlineData("var s = Environment?.GetEnvironmentVariable(\"SCADABRIDGE_API_KEY\");")]
|
||||
[InlineData("var c = new Microsoft.Data.SqlClient.SqlConnection(\"Server=attacker\")?.Database;")]
|
||||
// SyntacticPass_Flags
|
||||
[InlineData("typeof(string)?.Assembly?.GetTypes()")]
|
||||
[InlineData("typeof(string).Assembly?.GetTypes()")]
|
||||
[InlineData("asm?.EntryPoint")]
|
||||
public void ConditionalAccessVariant_IsRejected(string code)
|
||||
{
|
||||
Assert.NotEmpty(ScriptTrustValidator.FindViolations(code));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A gateway member reached as a bare identifier through <c>using static</c> never
|
||||
/// appears as a member access or binding; the semantic pass flags it by symbol name.
|
||||
/// </summary>
|
||||
/// <param name="code">The script source.</param>
|
||||
[Theory]
|
||||
[InlineData("using static System.Delegate; var d = CreateDelegate(typeof(Action), null, \"x\");")]
|
||||
[InlineData("using static System.Type; var t = GetType(\"System.IO.File\");")]
|
||||
public void UsingStaticGatewayMember_IsRejected(string code)
|
||||
{
|
||||
Assert.NotEmpty(ScriptTrustValidator.FindViolations(code));
|
||||
}
|
||||
|
||||
/// <summary>Legitimate <c>?.</c> use stays clean (no false positive from the new binding check).</summary>
|
||||
/// <param name="code">The script source.</param>
|
||||
[Theory]
|
||||
[InlineData("string s = null; var n = s?.Length;")]
|
||||
[InlineData("string s = null; var u = s?.Trim()?.ToUpperInvariant();")]
|
||||
[InlineData("Func<int,int> f = null; var r = f?.Invoke(3);")]
|
||||
[InlineData("var l = new List<int>(); var c = l?.Count;")]
|
||||
public void LegitimateConditionalAccess_IsAllowed(string code)
|
||||
{
|
||||
Assert.Empty(ScriptTrustValidator.FindViolations(code));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user