Files
UA-.NETStandard/Fuzzing/Common/Fuzz.Tests/FuzzTargetTestsBase.cs
Marc Schier 1c312e5559 Fix #3546: re-enable FuzzCrashAssets and harden BinaryDecoder (#3884)
# Description

Two coordinated fixes that close issue #3546 and remove the CI gap that
allowed the regression to slip past `dotnet test`:

1. **`BinaryDecoder` hardens matrix-dimension handling**
`Stack/Opc.Ua.Types/Encoders/BinaryDecoder.cs` — wraps the
matrix-construction switch in `ReadVariantValue` (all 24 BuiltInType
cases) and both `ReadEncodeableMatrix<T>` overloads in a try/catch that
converts the deliberate `ArgumentException` thrown by
`MatrixOf<T>(values, dimensions)` validation (overflow / negative /
length-mismatch) into a `ServiceResultException(BadDecodingError)`.
Attacker-controlled wire dimensions now flow through the standard
decoder rejection channel instead of escaping as an unhandled exception.
The `MatrixOf<T>` ctor validation itself (security hardening at
`MatrixOf.cs:178-217`) is unchanged.

2. **`FuzzCrashAssets` is now assertive**
`Fuzzing/Common/Fuzz.Tests/FuzzTargetTestsBase.cs` — replaces silent
log-and-count with `Assert.That(failures, Is.Empty, …listing failed
assets)`. CI now breaks loud the moment a residual `Assets/crash-*`
reproduces on any target. `.github/agents/fuzz-tester.agent.md` doc note
rewritten to match.

The originally reported "DataTypeNode / VariableNode `IsEqual`
non-determinism" symptom turned out to already be implicitly resolved by
the modern `Equals` overhaul (`ArrayOf<T>` value-equality,
`ExtensionObject.Equals` deep-compare, `IEquatable<T>` on
`ReferenceNode` / `RolePermissionType`). The 8 new synthetic round-trip
tests + 6 permanent corpus seeds confirm this end-to-end.

## Regression coverage

* `Tests/Opc.Ua.Types.Tests/Encoders/BinaryDecoderTests.cs` — 3 new
tests lock in the `BadDecodingError` contract for malformed matrix
dimensions (overflow, negative, length-mismatch).
* `Fuzzing/Opc.Ua.Encoders.Fuzz.Tests/Issue3546RoundTripTests.cs` — 8
synthetic round-trip tests for populated `DataTypeNode` and
`VariableNode`, exercising the implicated fields (non-empty References,
RolePermissions, `DataTypeDefinition` ExtensionObject body, `Value`
Variant carrying ExtensionObject, `ArrayDimensions` empty / null /
non-empty).
* `Fuzzing/Opc.Ua.Encoders.Fuzz.Tools/Encoders.Testcases.cs` +
`Fuzzing/Opc.Ua.Encoders.Fuzz.Corpus/Testcases.{Binary,Json,Xml}/` —
`DataTypeNodeMessage` / `VariableNodeMessage` seed generators plus 6
generated corpus files. These feed `FuzzGoodTestcases` automatically on
every test run.

## Verification

| Suite | TFM | Result |
|---|---|---|
| `Opc.Ua.Encoders.Fuzz.Tests` | net10.0 | **4625** / 0 |
| `Opc.Ua.Encoders.Fuzz.Tests` | net48   | **4625** / 0 |
| `Opc.Ua.Types.Tests` (BinaryDecoder / Matrix / Variant /
EncodeableMatrixRoundTrip subset) | net10.0 | **985** / 0 |

The single pre-existing
`Assets/crash-0483107a22caf892cff4f795c96ab14c581a8f55` no longer
escapes any fuzz target — the matrix-dimensions fix turns it into a
clean parser-rejected input.

## Related Issues

- Fixes #3546

## Checklist

- [x] I have signed the
[CLA](https://opcfoundation.org/license/cla/ContributorLicenseAgreementv1.0.pdf)
and read the
[CONTRIBUTING](https://github.com/OPCFoundation/UA-.NETStandard/blob/master/CONTRIBUTING.md)
doc.
- [x] I have added tests that prove my fix is effective or that my
feature works and increased code coverage.
- [x] I have added all necessary documentation.
- [x] I have verified that my changes do not introduce (new) build or
analyzer warnings.
- [x] I ran the affected tests locally (`Opc.Ua.Encoders.Fuzz.Tests` on
net10.0 + net48, targeted `Opc.Ua.Types.Tests` subset on net10.0); full
UA.slnx still pending CI.
- [ ] I fixed **all** failing and flaky tests in the CI pipelines and
**all** CodeQL warnings.
- [ ] I have addressed **all** PR feedback received.
2026-06-15 15:55:04 +02:00

199 lines
7.6 KiB
C#

/* ========================================================================
* Copyright (c) 2005-2026 The OPC Foundation, Inc. All rights reserved.
*
* OPC Foundation MIT License 1.00
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* The complete license agreement can be found here:
* http://opcfoundation.org/License/MIT/1.00/
* ======================================================================*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using NUnit.Framework;
using Opc.Ua.Tests;
namespace Opc.Ua.Fuzzing
{
[TestFixture]
[Category("Fuzzing")]
public abstract class FuzzTargetTestsBase
{
public static readonly TestcaseAsset[] GoodTestcases =
[
.. AssetCollection<TestcaseAsset>.CreateFromFiles(
TestUtils.EnumerateTestAssets("Testcases", "*.*"))
];
public static readonly TestcaseAsset[] CrashAssets =
[
.. AssetCollection<TestcaseAsset>.CreateFromFiles(
TestUtils.EnumerateTestAssets("Assets", "crash*.*"))
];
public static readonly TestcaseAsset[] TimeoutAssets =
[
.. AssetCollection<TestcaseAsset>.CreateFromFiles(
TestUtils.EnumerateTestAssets("Assets", "timeout*.*"))
];
public static readonly TestcaseAsset[] SlowAssets =
[
.. AssetCollection<TestcaseAsset>.CreateFromFiles(
TestUtils.EnumerateTestAssets("Assets", "slow*.*"))
];
[DatapointSource]
public static readonly string[] TestcaseEncoderSuffixes =
TestUtils.DiscoverTestcaseEncoderSuffixes("Testcases");
protected abstract Type FuzzableCodeType { get; }
public delegate void LibFuzzTemplate(ReadOnlySpan<byte> span);
[Theory]
public void FuzzGoodTestcases(
FuzzTargetFunction fuzzableCode,
[ValueSource(nameof(GoodTestcases))] TestcaseAsset messageEncoder)
{
FuzzTarget(fuzzableCode, messageEncoder.Testcase);
}
[Theory]
public void FuzzEmptyByteArray(FuzzTargetFunction fuzzableCode)
{
FuzzTarget(fuzzableCode, []);
}
[Theory]
public void FuzzCrashAssets(FuzzTargetFunction fuzzableCode)
{
var failures = new List<string>();
foreach (TestcaseAsset messageEncoder in CrashAssets)
{
try
{
TestContext.Out.WriteLine(messageEncoder);
FuzzTarget(fuzzableCode, messageEncoder.Testcase);
}
catch (Exception ex)
{
failures.Add(
$"asset={messageEncoder} -> {ex.GetType().Name}: {ex.Message}");
TestContext.Error.WriteLine($"Failed: {messageEncoder}\n{ex}");
}
}
// A crash asset under Assets/crash*.* is by definition an input that
// already produced an unhandled exception in a prior libfuzzer run.
// The contract is: once the regression has been fixed in the fuzz
// target (or the matching producer/decoder), replaying the asset
// through the target must NOT throw any more. The asset's continued
// existence in the tree therefore acts as a permanent regression
// gate. See https://github.com/OPCFoundation/UA-.NETStandard/issues/3546
// for the historical context that flipped this from
// log-and-swallow to assert-and-fail.
Assert.That(
failures,
Is.Empty,
"One or more crash assets reproduced under target " +
$"'{fuzzableCode.MethodInfo.Name}'. Each surfaced bug must be " +
"fixed (in the decoder/encoder/parser/whitelist) before the " +
"corresponding asset is left in place. Failures:" +
Environment.NewLine +
string.Join(Environment.NewLine, failures));
}
[Theory]
[CancelAfter(1000)]
public void FuzzTimeoutAssets(
FuzzTargetFunction fuzzableCode,
[ValueSource(nameof(TimeoutAssets))] TestcaseAsset messageEncoder)
{
FuzzTarget(fuzzableCode, messageEncoder.Testcase);
}
[Theory]
[CancelAfter(1000)]
public void FuzzSlowAssets(
FuzzTargetFunction fuzzableCode,
[ValueSource(nameof(SlowAssets))] TestcaseAsset messageEncoder)
{
FuzzTarget(fuzzableCode, messageEncoder.Testcase);
}
protected static FuzzTargetFunction[] CreateFuzzTargetFunctions(Type fuzzableCodeType)
{
return
[
.. fuzzableCodeType
.GetMethods(BindingFlags.Static | BindingFlags.Public)
.Where(f => f.GetParameters().Length == 1)
.Select(f => new FuzzTargetFunction(f))
];
}
protected virtual void OnFuzzTargetSetup(ITelemetryContext telemetry)
{
}
private void FuzzTarget(FuzzTargetFunction fuzzableCode, byte[] blob)
{
ITelemetryContext telemetry = NUnitTelemetryContext.Create();
OnFuzzTargetSetup(telemetry);
ParameterInfo[] parameters = fuzzableCode.MethodInfo.GetParameters();
if (parameters.Length != 1)
{
throw new InvalidOperationException(
"Fuzzable function must have exactly one parameter.");
}
if (parameters[0].ParameterType == typeof(string))
{
string text = Encoding.UTF8.GetString(blob);
_ = fuzzableCode.MethodInfo.Invoke(null, [text]);
}
else if (typeof(Stream).IsAssignableFrom(parameters[0].ParameterType))
{
using var stream = new MemoryStream(blob);
_ = fuzzableCode.MethodInfo.Invoke(null, [stream]);
}
else if (parameters[0].ParameterType == typeof(ReadOnlySpan<byte>))
{
var span = new ReadOnlySpan<byte>(blob);
#if NET8_0_OR_GREATER || NETSTANDARD2_1_OR_GREATER
LibFuzzTemplate fuzzFunction = fuzzableCode.MethodInfo
.CreateDelegate<LibFuzzTemplate>();
#else
var fuzzFunction = (LibFuzzTemplate)fuzzableCode.MethodInfo
.CreateDelegate(typeof(LibFuzzTemplate));
#endif
fuzzFunction(span);
}
}
}
}