Files
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

325 lines
16 KiB
C#

/* ========================================================================
* Copyright (c) 2005-2026 The OPC Foundation, Inc. All rights reserved.
* OPC Foundation MIT License 1.00. See LICENSE.txt in the repository root.
* ======================================================================*/
using System;
using System.IO;
using System.Linq;
using System.Text.Json.Nodes;
using System.Threading.Tasks;
using NUnit.Framework;
namespace Opc.Ua.OneFuzz.Validator.Tests
{
public sealed partial class ValidatorContractTests
{
[TestCase(false)]
[TestCase(true)]
public async Task SuppliedProfileGeneratesExactServiceConfigAndReplaysPublishedCallbacksAsync(
bool singleDictionary)
{
using var drop = new ContractDrop(m_fixture);
if (singleDictionary)
{
drop.Targets[0]!["dictionaries"] = ContractDrop.Strings([ContractDrop.FirstDictionary]);
}
JsonObject profile = CreateProfile(drop);
string profilePath = await SaveProfileAsync(drop, profile).ConfigureAwait(false);
ProcessResult configured = await RunAsync(
drop, "configure", "--drop", drop.Root, "--profile", profilePath).ConfigureAwait(false);
AssertSuccess(configured);
JsonObject actual = JsonNode.Parse(
await File.ReadAllTextAsync(drop.ConfigPath).ConfigureAwait(false))!.AsObject();
Assert.That(actual.Select(static property => property.Key),
Is.EquivalentTo(s_generatedConfigFields));
Assert.That(actual["ConfigVersion"]!.GetValue<int>(), Is.EqualTo(3));
JsonArray entries = actual["Entries"]!.AsArray();
Assert.That(entries, Has.Count.EqualTo(3));
for (int index = 0; index < entries.Count; index++)
{
JsonNode entry = entries[index]!;
JsonNode target = drop.Targets[index]!;
string id = target["id"]!.GetValue<string>();
foreach (var property in profile["ownership"]!.AsObject())
{
Assert.That(JsonNode.DeepEquals(entry[property.Key], property.Value), Is.True, property.Key);
}
Assert.That(entry["Fuzzer"]!["$type"]!.GetValue<string>(), Is.EqualTo("libfuzzerDotNet"));
Assert.That(entry["Fuzzer"]!["Dll"]!.GetValue<string>(), Is.EqualTo(ContractDrop.AssemblyDll));
Assert.That(entry["Fuzzer"]!["Class"]!.GetValue<string>(), Is.EqualTo(ContractDrop.CallbackType));
Assert.That(entry["Fuzzer"]!["Method"]!.GetValue<string>(),
Is.EqualTo(target["method"]!.GetValue<string>()));
JsonNode job = entry["OneFuzzJobs"]![0]!;
foreach (string field in new[] { "ProjectName", "TargetName", "SeedCorpusContainer" })
{
Assert.That(JsonNode.DeepEquals(job[field], profile["targets"]![index]![field]), Is.True, field);
}
string[] dependencies = [.. entry["JobDependencies"]!.AsArray()
.Select(static file => file!.GetValue<string>())];
Assert.That(dependencies, Is.SupersetOf(ContractDrop.PublishedFiles));
Assert.That(dependencies, Is.SupersetOf(drop.Inputs[id].Keys));
Assert.That(dependencies, Does.Contain("fuzz-targets.json"));
Assert.That(dependencies, Is.Ordered.Using<string>(StringComparer.Ordinal));
if (index != 0)
{
Assert.That(job.AsObject().ContainsKey("FuzzingTargetOptions"), Is.False);
}
}
string dictionary = singleDictionary
? ContractDrop.FirstDictionary
: "onefuzz-dictionaries/" + ContractDrop.InspectId + ".dict";
Assert.That(entries[0]!["OneFuzzJobs"]![0]!["FuzzingTargetOptions"]!.AsArray()
.Select(static option => option!.GetValue<string>()),
Is.EqualTo(new[] { "-dict={setup_dir}/" + dictionary }));
if (!singleDictionary)
{
Assert.That(await File.ReadAllLinesAsync(drop.PathFor(dictionary)).ConfigureAwait(false),
Is.EqualTo(s_mergedProfileTokens));
}
Assert.That(File.Exists(drop.PathFor(Path.GetFileName(profilePath))), Is.False);
ProcessResult replay = await ValidateAsync(drop).ConfigureAwait(false);
AssertCompleted(drop, replay, hasConfig: true);
}
[TestCase("schemaVersion", "2", "ownership profile requires schemaVersion 1")]
[TestCase("worker/os", "\"ubuntu\"", "supplied worker contract")]
[TestCase("worker/framework", "\"net8.0\"", "supplied worker contract")]
[TestCase("worker/architecture", "\"\"", "'architecture' must be a nonempty string")]
[TestCase("worker/architecture", "\"guessed\"", "supplied worker contract")]
[TestCase("worker/instrumentation", "\"local-sharpfuzz\"", "supplied worker contract")]
[TestCase("ownership/JobNotificationEmail", "\"\"", "'JobNotificationEmail' must be a nonempty string")]
[TestCase("ownership/SdlWorkItemId", "0", "valid supplied notification address")]
[TestCase("ownership/CodeCoverage/PipelineId", "\"REQUIRED\"", "contains a placeholder")]
[TestCase("ownership/AdoTemplate/AssignedTo", "\"$(owner)\"", "contains a placeholder")]
public async Task UnresolvedOrIncompatibleOwnershipProfileNeverEmitsFinalConfigAsync(
string property,
string json,
string diagnostic)
{
using var drop = new ContractDrop(m_fixture);
JsonObject profile = CreateProfile(drop);
SetJsonValue(profile, property, json);
string path = await SaveProfileAsync(drop, profile).ConfigureAwait(false);
ProcessResult result = await RunAsync(
drop, "configure", "--drop", drop.Root, "--profile", path).ConfigureAwait(false);
Assert.That(result.TimedOut, Is.False, result.Diagnostics);
Assert.That(result.ExitCode, Is.Not.Zero);
Assert.That(result.Diagnostics, Does.Contain(diagnostic));
Assert.That(File.Exists(drop.ConfigPath), Is.False);
Assert.That(Directory.EnumerateFiles(drop.Root, ".OneFuzzConfig-*.json"), Is.Empty);
Assert.That(Directory.Exists(drop.Results), Is.False);
}
[TestCase("missing")]
[TestCase("extra")]
[TestCase("duplicate")]
public async Task OwnershipTargetSetMustExactlyMatchTheManifestAsync(string change)
{
using var drop = new ContractDrop(m_fixture);
JsonObject profile = CreateProfile(drop);
JsonArray targets = profile["targets"]!.AsArray();
if (change == "missing")
{
targets.RemoveAt(0);
}
else
{
JsonNode copy = targets[0]!.DeepClone();
if (change == "extra")
{
copy["id"] = "synthetic.unmapped";
}
targets.Add(copy);
}
string path = await SaveProfileAsync(drop, profile).ConfigureAwait(false);
ProcessResult result = await RunAsync(
drop, "configure", "--drop", drop.Root, "--profile", path).ConfigureAwait(false);
Assert.That(result.TimedOut, Is.False, result.Diagnostics);
Assert.That(result.ExitCode, Is.Not.Zero);
Assert.That(result.Diagnostics, Does.Contain(change == "duplicate"
? "Duplicate ownership profile target"
: "must exactly cover the selected manifest targets"));
Assert.That(File.Exists(drop.ConfigPath), Is.False);
}
[Test]
public async Task ProfileGenerationRefusesToOverwriteAServiceConfigurationAsync()
{
using var drop = new ContractDrop(m_fixture);
drop.Save();
string before = ContractDrop.Hash(await File.ReadAllBytesAsync(drop.ConfigPath).ConfigureAwait(false));
string path = Path.Combine(drop.Home, "protected-profile.json");
await File.WriteAllTextAsync(path, CreateProfile(drop).ToJsonString()).ConfigureAwait(false);
ProcessResult result = await RunAsync(
drop, "configure", "--drop", drop.Root, "--profile", path).ConfigureAwait(false);
Assert.That(result.TimedOut, Is.False, result.Diagnostics);
Assert.That(result.ExitCode, Is.Not.Zero);
Assert.That(result.Diagnostics, Does.Contain("Refusing to replace an existing service configuration"));
Assert.That(ContractDrop.Hash(await File.ReadAllBytesAsync(drop.ConfigPath).ConfigureAwait(false)),
Is.EqualTo(before));
}
[Test]
public async Task MissingOwnershipProfileCannotGenerateAServiceConfigurationAsync()
{
using var drop = new ContractDrop(m_fixture, withConfig: false);
drop.Save();
ProcessResult result = await RunAsync(drop, "configure", "--drop", drop.Root).ConfigureAwait(false);
Assert.That(result.TimedOut, Is.False, result.Diagnostics);
Assert.That(result.ExitCode, Is.Not.Zero);
Assert.That(result.Diagnostics, Does.Contain("profile"));
Assert.That(File.Exists(drop.ConfigPath), Is.False);
}
[Test]
public async Task CompletedPublicDropCannotReceiveStaleServiceConfigurationEvidenceAsync()
{
using var drop = new ContractDrop(m_fixture);
string path = await SaveProfileAsync(drop, CreateProfile(drop)).ConfigureAwait(false);
const string publication = "{\"schemaVersion\":1,\"configurationGenerated\":false}";
drop.WriteText("publication.json", publication);
ProcessResult result = await RunAsync(
drop, "configure", "--drop", drop.Root, "--profile", path).ConfigureAwait(false);
Assert.That(result.TimedOut, Is.False, result.Diagnostics);
Assert.That(result.ExitCode, Is.Not.Zero);
Assert.That(result.Diagnostics, Does.Contain("Cannot configure a completed drop"));
Assert.That(File.Exists(drop.ConfigPath), Is.False);
Assert.That(await File.ReadAllTextAsync(drop.PathFor("publication.json")).ConfigureAwait(false),
Is.EqualTo(publication));
}
[Test]
public async Task ServiceConfigCannotBeGeneratedFromUnpublishedManifestCallbacksAsync()
{
using var drop = new ContractDrop(m_fixture);
drop.Targets[0]!["method"] = "NotPublished";
string path = await SaveProfileAsync(drop, CreateProfile(drop)).ConfigureAwait(false);
ProcessResult result = await RunAsync(
drop, "configure", "--drop", drop.Root, "--profile", path).ConfigureAwait(false);
Assert.That(result.TimedOut, Is.False, result.Diagnostics);
Assert.That(result.ExitCode, Is.Not.Zero);
Assert.That(result.Diagnostics, Does.Contain("Published callback inventory differs"));
Assert.That(File.Exists(drop.ConfigPath), Is.False);
}
[TestCase("ProjectName", "", "must be a nonempty string")]
[TestCase("TargetName", "$(target)", "contains a placeholder")]
[TestCase("SeedCorpusContainer", "Wrong--Container", "invalid explicit corpus container")]
public async Task ProfileJobsCannotGuessMissingOwnershipAsync(
string field,
string value,
string diagnostic)
{
using var drop = new ContractDrop(m_fixture);
JsonObject profile = CreateProfile(drop);
profile["targets"]![0]![field] = value;
string path = await SaveProfileAsync(drop, profile).ConfigureAwait(false);
ProcessResult result = await RunAsync(
drop, "configure", "--drop", drop.Root, "--profile", path).ConfigureAwait(false);
Assert.That(result.TimedOut, Is.False, result.Diagnostics);
Assert.That(result.ExitCode, Is.Not.Zero);
Assert.That(result.Diagnostics, Does.Contain(diagnostic));
Assert.That(File.Exists(drop.ConfigPath), Is.False);
Assert.That(Directory.EnumerateFiles(drop.Root, ".OneFuzzConfig-*.json"), Is.Empty);
}
[Test]
public async Task FailedGenerationRemovesOnlyNewDictionariesAndCanBeRetriedAsync()
{
using var drop = new ContractDrop(m_fixture);
drop.Targets[1]!["dictionaries"] = ContractDrop.Strings(
[ContractDrop.FirstDictionary, ContractDrop.SecondDictionary]);
const string first = "onefuzz-dictionaries/" + ContractDrop.InspectId + ".dict";
const string second = "onefuzz-dictionaries/" + ContractDrop.MeasureId + ".dict";
drop.WriteText(second, "preexisting fixture data");
string path = await SaveProfileAsync(drop, CreateProfile(drop)).ConfigureAwait(false);
ProcessResult failed = await RunAsync(
drop, "configure", "--drop", drop.Root, "--profile", path).ConfigureAwait(false);
Assert.That(failed.TimedOut, Is.False, failed.Diagnostics);
Assert.That(failed.ExitCode, Is.Not.Zero);
Assert.That(failed.Diagnostics, Does.Contain("Refusing to replace an existing merged dictionary"));
Assert.That(File.Exists(drop.ConfigPath), Is.False);
Assert.That(File.Exists(drop.PathFor(first)), Is.False);
Assert.That(await File.ReadAllTextAsync(drop.PathFor(second)).ConfigureAwait(false),
Is.EqualTo("preexisting fixture data"));
File.Delete(drop.PathFor(second));
ProcessResult configured = await RunAsync(
drop, "configure", "--drop", drop.Root, "--profile", path).ConfigureAwait(false);
AssertSuccess(configured);
ProcessResult replay = await ValidateAsync(drop).ConfigureAwait(false);
AssertCompleted(drop, replay, hasConfig: true);
}
private static JsonObject CreateProfile(ContractDrop drop)
{
var ownership = new JsonObject();
foreach (string field in new[] { "JobNotificationEmail", "AdoTemplate", "CodeCoverage", "SdlWorkItemId" })
{
ownership[field] = drop.Entries[0]![field]!.DeepClone();
}
var targets = new JsonArray();
for (int index = 0; index < drop.Targets.Count; index++)
{
JsonObject job = drop.Entries[index]!["OneFuzzJobs"]![0]!.DeepClone().AsObject();
job.Remove("FuzzingTargetOptions");
job["id"] = drop.Targets[index]!["id"]!.DeepClone();
targets.Add(job);
}
return new JsonObject
{
["schemaVersion"] = 1,
["worker"] = new JsonObject
{
["os"] = "azurelinux3",
["framework"] = "net10.0",
["architecture"] = "x64",
["instrumentation"] = "service"
},
["ownership"] = ownership,
["targets"] = targets
};
}
private static async Task<string> SaveProfileAsync(ContractDrop drop, JsonObject profile)
{
drop.Save();
File.Delete(drop.ConfigPath);
string path = Path.Combine(drop.Home, "protected-profile.json");
await File.WriteAllTextAsync(path, profile.ToJsonString()).ConfigureAwait(false);
return path;
}
private static readonly string[] s_generatedConfigFields = ["ConfigVersion", "Entries"];
private static readonly string[] s_mergedProfileTokens = ["\"alpha\"", "\"beta\"", "\"shared\""];
}
}