Files
UA-.NETStandard/fuzzing/Common/Fuzz.Tests/FuzzTargetTestsBase.cs
Marc Schier f5ad124891 Additional fuzzing plus fixes for every defect the campaigns found (#4459)
# Description

Brings the stack's fuzz testing to parity with the fork
(`aio-opcua-sdk`), then fixes every defect the resulting campaigns
exposed.

The fork's fuzzing was used as the behavioural baseline: all **28
fork-local callbacks** and **13 OneFuzz registrations** are now
accounted for by an explicit mapping, not just by a larger target count.
The work extends the existing SharpFuzz/NUnit infrastructure rather than
introducing another framework.

### Coverage

- **84 continuous libFuzzer targets** and **81 AFL adapters** across
Encoders, Certificates, Network and PubSub.
- **PubSub area integrated** (Corpus/Tools/Tests siblings, solution
entries) — it previously had host source only and was absent from the
solution and replay infrastructure.
- Segmented binary adapters, binary-to-JSON and XML-to-JSON conversions,
standalone certificate loading, both chain-parser variants, CRL encoding
and canonical TBS round-trips.
- The 12 original fork message inputs are retained byte-identically
alongside richer deterministic generators; the three historical
crash/slow/timeout reproducers are unchanged (verified identical by
SHA-256).

### Production fixes found by fuzzing

These are real robustness and data-integrity bugs, each with a retained
regression input:

- `UadpBinaryReader.Advance` accepted attacker-controlled lengths on the
receive path. Declared payload sizes are now authoritative bounded
sections, with negative-count rejection and overflow-safe reassembly
arithmetic.
- PubSub JSON decoding leaked `InvalidOperationException` for invalid
UTF-8.
- `JsonEncoder.WriteExtensionObject` leaked
`System.Text.Json.JsonReaderException`.
- `JsonEncoder` silently emitted a lossy `{}` for an `ExtensionObject`
whose TypeId could not be represented in JSON.
- `JsonDecoder` wrapped a bodyless `ExtensionObject` envelope as a raw
JSON body instead of preserving `ExtensionObjectEncoding.None`.
- `Node.Encode` lost the null/empty collection distinction.
- Binary/XML Variant matrix dimensions are prevalidated rather than
relying on a caught `ArgumentException`.
- `X509CRL.ReadTime` pre-validates strict RFC 5280 whole-second Zulu
time forms.
- `Utils.ParseCertificateChainBlob` disposes correctly on partial-chain
failure.
- **`nodeid.dict` was unloadable by libFuzzer** (empty token, unescaped
quote). libFuzzer rejects the whole file on one bad line, so four parser
targets silently executed **zero** inputs. Fixed and now guarded by
dictionary validation.

### Infrastructure

- `fuzzing/fuzz-targets.json` manifest recording adapters, corpora,
dictionaries, oracles and fork-behaviour mappings, with
`validate-fuzz-manifest.ps1` and **27 negative controls**.
- Strict host/tools discovery and replay: `--list`, `--replay`, non-zero
exits on unknown targets, missing or empty corpora, and failed callbacks
(playback previously logged failures and returned success).
- A real process watchdog for the timeout/slow regressions — NUnit
`CancelAfter` cannot interrupt a synchronous fuzz callback.
- Runner scripts made non-destructive (unique work directories, no
generic `bin`/findings deletion) and corrected to the native driver's
single-`--target_arg` apphost contract.
- Opt-in `OneFuzz=true` class-library publication producing a
relocatable, **uninstrumented** drop, validated by exact callback
discovery, dependency closure, corpora and dictionaries.
- CI: fuzz replay matrix plus a public drop gate, triggered by corpus-,
dictionary- and script-only changes.

### Verification

| Gate | Result |
|---|---|
| Bounded campaigns, all 84 targets (1,000 inputs, seed 1) | 84/84,
84,000 executions, zero findings |
| OneFuzz drop | 84/84 published callbacks replayed, zero skips |
| Fuzz replay net10.0 / net8.0 / net9.0 | 9,470 passed each, 0 failed |
| Fuzz replay net48 | 8,996 passed, 0 failed (Network/PubSub are
modern-only) |
| `Opc.Ua.Types.Tests` / `Opc.Ua.Core.Tests` | 9,800 and 4,442 passed, 0
failed |
| Retained regression assets | 132 `crash-*` inputs replayed by every
target each run |

### Known gaps (deliberately not closed)

- **Fidelity is not enforced against the pipeline crash corpus.** The
differential binary-to-JSON targets assert both robustness (no unhandled
exception, expected of arbitrary bytes) and fidelity (a decoded value
re-encodes equivalently, a property of well formed values). The pipeline
supplies 22,293 blobs collected for the targets that existed before this
PR, none of which asserted fidelity; 522 of them violate it, and that
count did not move across two rounds of genuine fixes because each fix
only lets the mutator reach the next representability gap. Rather than
weaken the assertion, the two contracts are separated: fidelity failures
raise `EncodingFidelityException`; curated assets under `Assets/Repo`,
the curated `Testcases` corpus and every continuous libFuzzer campaign
stay strictly enforced, while externally supplied assets are gated on
robustness only and their fidelity findings are reported with counts and
bounded base64 reproducers.
- **Internal MSFT OneFuzz canary has not been run.** It needs an
owner-supplied ownership profile, pipeline authorisation and corpus
snapshot; none were available. The drop builds and validates locally and
records `serviceCanaryPerformed: false`. A build or upload is not a
successful worker run.
- **Legacy JSON wire forms are a partial mapping.** The fork accepts its
four original `TypeId`/`Body` messages; this stack rejects that retired
envelope (measured JSON-only control: fork `JsonEncoder` 630/1356 lines
vs 0/1007 here). Recorded as an explicit unresolved mapping rather than
an exemption. `LegacyNonReversible` is a RawData-derived profile and is
not counted as independent coverage.

## Related Issues

_No tracking issue was supplied for this work; happy to open one and
link it if maintainers prefer._

- Fixes #github-issue-number, ...

## Checklist

- [ ] 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 **all** tests locally using the **UA.slnx** solution against
at least .net **framework** and .net **10**, and all passed.
- [ ] I fixed **all** failing and flaky tests in the CI pipelines and
**all** CodeQL warnings.
- [ ] I have addressed **all** PR feedback received.

> Note on the checklist: the fuzz replay matrix, `Opc.Ua.Types.Tests`
and `Opc.Ua.Core.Tests` were run locally on **net48** and **net10.0**
(plus net8.0/net9.0) and all passed. CI and CodeQL results are not yet
available for this branch, so those boxes are left unchecked. The CLA
box is for the author to confirm.
2026-09-10 05:56:31 +02:00

361 lines
15 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.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
using Opc.Ua.Tests;
namespace Opc.Ua.Fuzzing
{
[TestFixture]
[Category("Fuzzing")]
public abstract class FuzzTargetTestsBase
{
private const int kMaxEmittedReproducers = 60;
private const int kMaxEmittedReproducerBytes = 4096;
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>();
var fidelityFindings = new List<string>();
int reproducers = 0;
foreach (TestcaseAsset messageEncoder in CrashAssets)
{
try
{
TestContext.Out.WriteLine(messageEncoder);
FuzzTarget(fuzzableCode, messageEncoder.Testcase);
continue;
}
catch (Exception ex)
{
string entry = $"asset={messageEncoder} -> {ex.GetType().Name}: {ex.Message}";
if (IsFidelityFinding(ex) && !IsCuratedAsset(messageEncoder))
{
fidelityFindings.Add(entry);
}
else
{
failures.Add(entry);
}
TestContext.Error.WriteLine($"Failed: {messageEncoder}\n{ex}");
// Crash corpora are frequently supplied by the pipeline rather than the
// tree, so a failure there is otherwise impossible to reproduce locally.
// Emit the reproducer inline, bounded so a systemic failure cannot bury
// the log. A passing run emits nothing.
if (reproducers++ < kMaxEmittedReproducers &&
messageEncoder.Testcase.Length <= kMaxEmittedReproducerBytes)
{
TestContext.Error.WriteLine(
$"REPRODUCER {messageEncoder} " +
Convert.ToBase64String(messageEncoder.Testcase));
}
}
}
if (fidelityFindings.Count > 0)
{
// Differential targets additionally assert that a decoded value re-encodes to
// an equivalent representation. That is a property of well formed values, and
// an externally supplied crash corpus is a set of arbitrary mutated blobs
// collected for other targets, so it cannot be expected to satisfy it. Report
// the findings and keep gating those inputs on robustness only. Curated assets
// in the tree stay strict, and continuous fuzzing still treats a fidelity
// mismatch as a crash, so new regressions are still caught.
TestContext.Error.WriteLine(
$"{fidelityFindings.Count} external crash assets reported encoding " +
$"fidelity findings under target '{fuzzableCode.MethodInfo.Name}'." +
Environment.NewLine +
string.Join(Environment.NewLine, fidelityFindings));
}
// 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));
}
/// <summary>
/// A fidelity finding means the stack stayed healthy but re-encoded a decoded value
/// differently. It is reported rather than enforced for externally supplied inputs.
/// <para>
/// Matched by name because the shared exception source is linked into every fuzz
/// target and test assembly, so the runtime types are not reference equal.
/// </para>
/// </summary>
private static bool IsFidelityFinding(Exception exception)
{
for (Exception current = exception; current != null; current = current.InnerException)
{
if (string.Equals(
current.GetType().FullName,
"Opc.Ua.Fuzzing.EncodingFidelityException",
StringComparison.Ordinal))
{
return true;
}
}
return false;
}
/// <summary>
/// Curated assets live under Assets/Repo in the tree and are always enforced strictly.
/// Everything else in the Assets folder is overlaid by the pipeline before the build.
/// </summary>
private static bool IsCuratedAsset(TestcaseAsset asset)
{
string path = asset.Path;
return path != null &&
path.Replace('\\', '/')
.IndexOf("/Assets/Repo/", StringComparison.OrdinalIgnoreCase) >= 0;
}
[Theory]
public async Task FuzzTimeoutAssetsAsync(
FuzzTargetFunction fuzzableCode,
[ValueSource(nameof(TimeoutAssets))] TestcaseAsset messageEncoder)
{
await ReplayWithWatchdogAsync(fuzzableCode, messageEncoder.Testcase).ConfigureAwait(false);
}
[Theory]
public async Task FuzzSlowAssetsAsync(
FuzzTargetFunction fuzzableCode,
[ValueSource(nameof(SlowAssets))] TestcaseAsset messageEncoder)
{
await ReplayWithWatchdogAsync(fuzzableCode, messageEncoder.Testcase).ConfigureAwait(false);
}
[Test]
public void RequiredCorpusAndTargetsArePresent()
{
Assert.That(GoodTestcases, Is.Not.Empty, "Required fuzz corpus was not copied to the test output.");
Assert.That(CreateFuzzTargetFunctions(FuzzableCodeType), Is.Not.Empty);
}
protected static FuzzTargetFunction[] CreateFuzzTargetFunctions(Type fuzzableCodeType)
{
return
[
.. fuzzableCodeType
.GetMethods(BindingFlags.Static | BindingFlags.Public)
.Where(f => f.ReturnType == typeof(void) &&
!f.ContainsGenericParameters &&
f.GetParameters().Length == 1 &&
(f.GetParameters()[0].ParameterType == typeof(Stream) ||
f.GetParameters()[0].ParameterType == typeof(string) ||
f.GetParameters()[0].ParameterType == typeof(ReadOnlySpan<byte>)))
.Select(f => new FuzzTargetFunction(f))
];
}
protected virtual void OnFuzzTargetSetup(ITelemetryContext telemetry)
{
}
private async Task ReplayWithWatchdogAsync(FuzzTargetFunction target, byte[] data)
{
string file = Path.Combine(Path.GetTempPath(), $"opcua-fuzz-{Guid.NewGuid():N}.bin");
File.WriteAllBytes(file, data);
try
{
string assembly = FuzzableCodeType.Assembly.Location;
#if NETFRAMEWORK
string executable = assembly;
string arguments = string.Empty;
#else
string executable = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? "dotnet";
string arguments = $"\"{assembly}\" ";
#endif
ProcessStartInfo startInfo = CreateReplayStartInfo(
$"{arguments}--fuzz-replay {target.MethodInfo.Name} \"{file}\"");
(int exitCode, bool timedOut, string standardOutput, string standardError) =
await FuzzProcessWatchdog.RunAsync(startInfo, TimeSpan.FromSeconds(30)).ConfigureAwait(false);
Assert.That(timedOut, Is.False, $"Replay exceeded the process budget: {target.MethodInfo.Name}");
Assert.That(exitCode, Is.Zero, standardOutput + Environment.NewLine + standardError);
}
finally
{
File.Delete(file);
}
}
private static ProcessStartInfo CreateReplayStartInfo(string arguments)
{
#if NETFRAMEWORK
string executable = typeof(FuzzTargetTestsBase).Assembly.Location;
#else
string executable = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? "dotnet";
#endif
return new ProcessStartInfo
{
FileName = executable,
Arguments = arguments,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true,
WorkingDirectory = AppContext.BaseDirectory
};
}
[TestCase("MissingFuzzTarget \"no-such-input\"")]
[TestCase("OnlyOneArgument")]
public async Task MalformedReplayRequestFailsInsteadOfReportingSuccessAsync(string replayArguments)
{
// The timeout/slow regressions assert a zero exit, so a replay child that
// cannot run the requested input must fail rather than fall through to the
// benchmark host and report a pass for an input that was never replayed.
#if NETFRAMEWORK
string prefix = string.Empty;
#else
string prefix = $"\"{typeof(FuzzTargetTestsBase).Assembly.Location}\" ";
#endif
ProcessStartInfo startInfo = CreateReplayStartInfo(
$"{prefix}--fuzz-replay {replayArguments}");
(int exitCode, bool timedOut, _, _) =
await FuzzProcessWatchdog.RunAsync(startInfo, TimeSpan.FromSeconds(30)).ConfigureAwait(false);
Assert.That(timedOut, Is.False);
Assert.That(exitCode, Is.Not.Zero);
}
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);
}
else
{
throw new InvalidOperationException("Unsupported fuzz target signature.");
}
}
}
}