mirror of
https://github.com/OPCFoundation/UA-.NETStandard.git
synced 2026-10-21 17:16:16 +08:00
ce88955f70
# Description
Hardens the encoders and decoders against untrusted input and aligns
them with OPC 10000-6 (1.05) and OPC 10000-14. This comes from an audit
of every codec reachable from a peer:
- Binary, JSON and XML decoders and encoders;
- built-in and complex types;
- UA-TCP/UASC framing;
- PubSub UADP and PubSub JSON.
The audit found 97 issues: 1 critical, 7 high, 39 medium and 50 low.
They are all fixed here, one commit per finding (IDs B1-, J1-, X1-, T1-,
S1-, U1-, P1-, E1-, E2- in the commit subjects). Every fix was then
checked against the spec a second time, and the deviations that re-check
found were fixed as well (`*-spec` commits).
## Security (decoders reachable from unauthenticated peers)
- **Allocation from length prefixes (B1-1, B1-5, U1-1, U1-3).**
- Array, string and byte-string lengths are checked against the bytes
left in the message before anything is allocated.
- Arrays read element by element grow as elements are decoded, so nested
length prefixes can no longer multiply memory.
- UADP discovery counts and chunk reassembly buffers are bounded the
same way.
- **Stack exhaustion.** Nesting is checked for remaining stack
(`RuntimeHelpers.EnsureSufficientExecutionStack` mapped to
`BadEncodingLimitsExceeded`), and the large Variant read/write methods
were split into scalar, array and matrix methods. Measured on 1 MB and
256 KB threads, no codec overflows at the default limits any more.
- **XML element depth (X1-1).** XmlElement values and raw
ExtensionObject bodies are copied node by node with a depth limit,
instead of with the recursive `InnerXml`, `ImportNode`, `InnerText` and
`DeepEquals` calls.
- **Limit bypasses:**
- JSON NodeId, QualifiedName and opaque strings now respect
MaxStringLength and MaxByteStringLength (J1-1).
- Matrix rank is limited to 32.
- Decimal size is bounded (T1-3).
- XML base64 is checked before it is decoded.
- XML arrays are checked before each element is read.
- **CPU and algorithmic cost:**
- UADP reassembly uses an O(1) overlap check with a per-message chunk
cap (U1-2).
- PubSub JSON matches fields to metadata through a name index (P1-2).
- LocalizedText "mul" text is parsed lazily (T1-5).
- Unknown SecurityTokenIds trigger a throttled background SKS refresh
instead of an inline call per datagram (U1-9).
- **PubSub metadata poisoning (P1-1).** Inbound metadata is registered
only for identities a configured reader expects, is capped, and an
unauthenticated message can no longer pin a version.
- **Exception contract.** Decoders fail with `ServiceResultException`
(BadDecodingError / BadEncodingLimitsExceeded) instead of letting
ArgumentException, InvalidOperationException, TypeLoadException and
similar escape.
- **UASC (S1-*):**
- OPN and CLO must be single final chunks.
- The certificate of an unsigned OPN is ignored.
- The padding and ExtraPadding bytes are validated.
- A renewed token is activated only after a chunk has been verified with
it.
- A policy change on renewal is rejected before the channel certificate
is touched.
- Secured chunk length arithmetic is bounded.
## Wire-visible behaviour changes
All follow the spec exactly; there is no reader for the old forms unless
noted.
- **UA Binary:**
- Variant type ids 26-31 decode as ByteString.
- Picoseconds without their timestamp are ignored, and values of 10000
and above are clamped to 9999.
- A Null-type Variant with the array flag consumes its length and
dimensions.
- **UA JSON:**
- Messages are ExtensionObjects with the body inline; there is no
`UaBody` envelope any more (5.4.9 / 5.4.2.16).
- The Variant `Value` is omitted exactly for NULLs of nullable types
(Table 41).
- RawData keeps nested UaType/UaTypeId and the StatusCode Symbol.
- Duplicate member names are rejected.
- `{}` decodes as a null ExtensionObject.
- Numbers and identifiers are parsed strictly and culture-independently.
- QualifiedName follows 5.4.2.14.
- Opaque bodies of known types carry the DataType id.
- Enumerations without a literal are written as the number.
- **UA XML:**
- The earliest DateTime is written as `0001-01-01T00:00:00Z`.
- Null typed scalars and null array elements are written with `xsi:nil`.
- An ExtensionObject without a body has no `Body` element.
- Strings XML cannot represent are rejected.
- Only the xs:dateTime and xs:date forms are accepted; a value without a
zone is still read as UTC, because published model files use it.
- Only the Part 6 Guid form is accepted.
- Booleans are case-sensitive in XmlDecoder.
- **UA-TCP:**
- OPNC/OPNA/CLOC/CLOA fault the channel. Older releases that split a
long-chain OPN into chunks are rejected, so this needs a release note.
- The sender truncates the certificate chain to fit a single chunk.
- The received certificate chain is sized from the chunk size.
- Hello buffer sizes down to 1024 bytes are honoured; below that, an ERR
with Bad_TcpInternalError is sent.
- A 4096-byte Error reason is accepted, and the SecurityPolicyUri limit
is 255 bytes.
- **PubSub UADP:**
- Chunk NetworkMessages use the Part 14 7.2.4.4.4 layout, and each chunk
is secured on its own with its own sequence number.
- The Sizes array is part of the secured payload.
- Padded RawData keeps its length prefix, and null values are written as
-1.
- DataSetMessages with the valid bit clear are skipped.
- Null discovery arrays are accepted.
- **PubSub JSON:**
- Variants use `UaType`/`Value`, with the 7.2.5.4.2 top-level collapse.
The deprecated `Type`/`Body` form is still read.
- Status is written as a `{Code,Symbol}` object; a numeric Status is
still accepted.
- Discovery messages follow Tables 188-192, with GUID MessageIds.
- Enumeration fields are written as `Name_Value`.
- Fields appended with a MinorVersion bump are accepted.
## Known deviations and limitations (documented, not changed)
- A known type whose ExtensionObject XML body fails to decode fails the
message, like a failing binary body. 5.2.2.15 only says the decoder
*should* continue, and continuing reopens the log-flooding path.
- Reserved Variant type ids 26-31 are passed to the application as
ByteString without the raw type id.
- JSON UaTypeId of an opaque body of an *unknown* type stays the
encoding id, because no type system is available to map it.
- PubSub JSON encoder:
- Structure fields without a subtype are still wrapped with a UaType,
and concrete multi-dimensional or abstract-rank fields still carry a
UaType (Table 186).
- Namespace-0 enumerations without EnumDataTypes are written as a
numeric string.
- Chunked transcoded frames have no writer group, so their sequence
numbers continue from the source number.
- Pre-existing and out of scope: the HTTPS JSON binding uses
Content-Type `application/opcua+uajson`, while 1.05 7.4.5 requires
`application/json`.
## Tests
- Every fix has a regression test.
- Tests that pinned non-conformant behaviour were updated, and their
commit messages say so.
- Fuzz seeds were regenerated where the wire changed.
Local results:
net10.0, 27 suites green (Types 11354, Core.Encoders 2933, Encoders.Fuzz
8112, Core 5955 + 1 known intermittent ActivityTraceFlags metrics test
that passes alone, Client 2732, Server 7802, Sessions 790, GDS 1234,
Subscriptions 641, SourceGeneration.Core 4266, PubSub 1490 and all
PubSub transport suites). Full UA.slnx build 0 warnings / 0 errors on
net10.0 and net48.
## Related Issues
- Follow-up: #4598 (possible throughput regression of per-element binary
array reads).
## 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.
- [ ] I ran **all** tests locally using the **UA.slnx** solution against
at least .net **framework** and .net **10**, and all passed. (net10.0
suites run; net48 build only)
- [ ] I fixed **all** failing and flaky tests in the CI pipelines and
**all** CodeQL warnings.
- [ ] I have addressed **all** PR feedback received.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
191 lines
9.0 KiB
C#
191 lines
9.0 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.Text.Json;
|
|
using Opc.Ua.PubSub.Encoding;
|
|
using Opc.Ua.PubSub.Encoding.Json;
|
|
using Opc.Ua.PubSub.Encoding.Uadp;
|
|
|
|
namespace Opc.Ua.Fuzzing
|
|
{
|
|
public static partial class Testcases
|
|
{
|
|
public static void Run(string workPath, ITelemetryContext telemetry)
|
|
{
|
|
ArgumentException.ThrowIfNullOrWhiteSpace(workPath);
|
|
_ = telemetry;
|
|
foreach ((string bucket, string name, byte[] data) in CreatePubSubSeeds())
|
|
{
|
|
string directory = workPath + "." + bucket;
|
|
Directory.CreateDirectory(directory);
|
|
File.WriteAllBytes(Path.Combine(directory, name), data);
|
|
}
|
|
}
|
|
|
|
internal static IEnumerable<(string Bucket, string Name, byte[] Data)> CreatePubSubSeeds()
|
|
{
|
|
yield return ("Json", "metadata-keyframe-verbose.json", CreateJsonSeed(JsonEncodingMode.Verbose));
|
|
yield return ("Json", "metadata-keyframe-compact.json", CreateJsonSeed(JsonEncodingMode.Compact));
|
|
yield return ("Json", "metadata-keyframe-raw.json", CreateJsonSeed(JsonEncodingMode.RawData));
|
|
yield return ("Json", "metadata-keyframe-datavalue.json",
|
|
CreateJsonSeed(JsonEncodingMode.Verbose, PubSubFieldEncoding.DataValue));
|
|
yield return ("Uadp", "metadata-keyframe-variant.uadp", CreateUadpSeed(PubSubFieldEncoding.Variant));
|
|
yield return ("Uadp", "metadata-keyframe-datavalue.uadp", CreateUadpSeed(PubSubFieldEncoding.DataValue));
|
|
byte[] rawData = CreateUadpSeed(PubSubFieldEncoding.RawData);
|
|
yield return ("Uadp", "metadata-keyframe-raw.uadp", rawData);
|
|
|
|
var chunker = new UadpChunker();
|
|
yield return ("Chunks", "metadata-keyframe-complete.bin",
|
|
chunker.Split(rawData, 42, rawData.Length + UadpChunker.ChunkHeaderSize)[0]);
|
|
IReadOnlyList<byte[]> chunks = chunker.Split(rawData, 42, 42);
|
|
for (int i = 0; i < chunks.Count; i++)
|
|
{
|
|
yield return ("Chunks", FormattableString.Invariant($"metadata-keyframe-chunk-{i:000}.bin"), chunks[i]);
|
|
}
|
|
}
|
|
|
|
internal static byte[] CreateJsonSeed(
|
|
JsonEncodingMode mode,
|
|
PubSubFieldEncoding fieldEncoding = PubSubFieldEncoding.Variant)
|
|
{
|
|
using var stream = new MemoryStream();
|
|
using (var writer = new Utf8JsonWriter(stream))
|
|
{
|
|
writer.WriteStartObject();
|
|
writer.WriteString("MessageId", FormattableString.Invariant($"retained-{mode}-{fieldEncoding}"));
|
|
writer.WriteString("MessageType", "ua-data");
|
|
writer.WriteString("PublisherId", "300");
|
|
writer.WriteString("DataSetClassId", FuzzableCode.SeedDataSetClassId.ToString());
|
|
writer.WriteStartArray("Messages");
|
|
writer.WriteStartObject();
|
|
writer.WriteNumber("DataSetWriterId", 1);
|
|
writer.WriteNumber("SequenceNumber", 42);
|
|
writer.WriteString("MessageType", "ua-keyframe");
|
|
writer.WriteString("Timestamp", FuzzableCode.SeedTime);
|
|
writer.WriteStartObject("MetaDataVersion");
|
|
writer.WriteNumber("MajorVersion", 1);
|
|
writer.WriteNumber("MinorVersion", 2);
|
|
writer.WriteEndObject();
|
|
// Verbose fields with a concrete FieldMetaData type are collapsed to
|
|
// bare values (Part 14 §7.2.5.4.2); encode the Verbose seed without
|
|
// metadata so it keeps exercising the UaType/Value Variant envelope.
|
|
JsonFieldEncoder.EncodeFields(
|
|
writer,
|
|
CreateFields(fieldEncoding),
|
|
mode == JsonEncodingMode.Verbose ? null : FuzzableCode.CreateMetaData(),
|
|
mode,
|
|
FuzzableCode.NewContext().MessageContext);
|
|
writer.WriteEndObject();
|
|
writer.WriteEndArray();
|
|
writer.WriteEndObject();
|
|
}
|
|
return stream.ToArray();
|
|
}
|
|
|
|
internal static byte[] CreateUadpSeed(PubSubFieldEncoding fieldEncoding)
|
|
{
|
|
return UadpEncoder.EncodeData(CreateUadpMessage(fieldEncoding), FuzzableCode.NewContext());
|
|
}
|
|
|
|
internal static UadpNetworkMessage CreateUadpMessage(PubSubFieldEncoding fieldEncoding)
|
|
{
|
|
DataSetMetaDataType metaData = FuzzableCode.CreateMetaData();
|
|
return new UadpNetworkMessage
|
|
{
|
|
ContentMask =
|
|
UadpNetworkMessageContentMask.PublisherId |
|
|
UadpNetworkMessageContentMask.GroupHeader |
|
|
UadpNetworkMessageContentMask.WriterGroupId |
|
|
UadpNetworkMessageContentMask.PayloadHeader |
|
|
UadpNetworkMessageContentMask.SequenceNumber |
|
|
UadpNetworkMessageContentMask.DataSetClassId |
|
|
UadpNetworkMessageContentMask.Timestamp,
|
|
PublisherId = FuzzableCode.SeedPublisherId,
|
|
WriterGroupId = 1,
|
|
SequenceNumber = 42,
|
|
DataSetClassId = FuzzableCode.SeedDataSetClassId,
|
|
Timestamp = new DateTimeUtc(FuzzableCode.SeedTime),
|
|
MetaData = metaData,
|
|
DataSetMessages =
|
|
[
|
|
new UadpDataSetMessage
|
|
{
|
|
ContentMask =
|
|
UadpDataSetMessageContentMask.SequenceNumber |
|
|
UadpDataSetMessageContentMask.MajorVersion |
|
|
UadpDataSetMessageContentMask.MinorVersion |
|
|
UadpDataSetMessageContentMask.Timestamp,
|
|
DataSetWriterId = 1,
|
|
SequenceNumber = 42,
|
|
MessageType = PubSubDataSetMessageType.KeyFrame,
|
|
FieldEncoding = fieldEncoding,
|
|
FieldContentMask =
|
|
DataSetFieldContentMask.StatusCode |
|
|
DataSetFieldContentMask.SourceTimestamp |
|
|
DataSetFieldContentMask.ServerTimestamp |
|
|
DataSetFieldContentMask.SourcePicoSeconds |
|
|
DataSetFieldContentMask.ServerPicoSeconds,
|
|
MetaDataVersion = metaData.ConfigurationVersion,
|
|
Timestamp = new DateTimeUtc(FuzzableCode.SeedTime),
|
|
Fields = CreateFields(fieldEncoding)
|
|
}
|
|
]
|
|
};
|
|
}
|
|
|
|
internal static ArrayOf<DataSetField> CreateFields(PubSubFieldEncoding encoding)
|
|
{
|
|
return
|
|
[
|
|
CreateField("Running", Variant.From(true), encoding),
|
|
CreateField("Count", Variant.From(42), encoding) with { StatusCode = StatusCodes.Uncertain },
|
|
CreateField("Temperature", Variant.From(21.5), encoding),
|
|
CreateField("Label", Variant.From("pubsub"), encoding)
|
|
];
|
|
}
|
|
|
|
private static DataSetField CreateField(string name, Variant value, PubSubFieldEncoding encoding)
|
|
{
|
|
return new DataSetField
|
|
{
|
|
Name = name,
|
|
Value = value,
|
|
Encoding = encoding,
|
|
SourceTimestamp = new DateTimeUtc(FuzzableCode.SeedTime),
|
|
ServerTimestamp = new DateTimeUtc(FuzzableCode.SeedTime.AddSeconds(1)),
|
|
SourcePicoSeconds = 10,
|
|
ServerPicoSeconds = 20
|
|
};
|
|
}
|
|
}
|
|
}
|