From 3c4f83b0381b11c91a2bf59f6631ba8632c48f28 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 23 Sep 2026 04:44:09 +0200 Subject: [PATCH] R-AG/R-AK: checked C# cursor-length arithmetic, a dispatch backstop, and the redundant guard R-AG. ReadLengthPrefixedFields tested pos + length > bytes.Length in int math; a length prefix near int.MaxValue overflowed the unchecked add, slipped past the guard, and Encoding.UTF8.GetString threw ArgumentOutOfRangeException instead of this method returning null the way every other malformed shape already does. Promotes to long before the add, which cannot itself overflow (both operands stay far under long's range), so the guard sees the true sum. CultNetRudpSchemaServer.DispatchAsync gains a catch around the handler invocation: HandleSnapshotRequestV1Async already answers cursor_invalid/selection_invalid/reference_outside_target for its three typed exceptions, but nothing stopped an untyped one from an unanticipated bug reaching DynamicInvoke's caller and stalling the poll loop for every other peer. Answers nothing on the wire (an exception this generic carries no typed refusal to report) and drops the one malformed dispatch, the same as an unregistered handler already does. Hostile-cursor tests (CultNetSelectionFixBatchTests.cs) feed CultNetSelectionCursor.Parse a length prefix near int.MaxValue (C#'s own proven overflow), near usize::MAX (Rust's proven overflow, fed here too per the ruling), wider than any integer type, and negative-looking - each asserted to throw the typed CultNetSelectionCursorException. R-AK. Deletes ReferenceMembers's `!member.IsReference` guard. CultCache.ReferencesOf (CultCache.cs:262-278) already searches only its own reference members for a role match and returns empty for anything else; index aliases are unique per descriptor, so a data member's own role string can never coincide with a reference member's. Verified before deleting: traced ReferencesOf's role lookup directly rather than trusting the ruling's premise. A second copy of the same exclusion here was duplicate authority, not a second decision. Co-Authored-By: Claude Sonnet 5 --- .../CultNetRudpSchemaServer.cs | 20 +++++- .../CultNetSelectionEvaluator.cs | 15 ++++- .../CultNetSelectionFixBatchTests.cs | 62 +++++++++++++++++++ 3 files changed, 92 insertions(+), 5 deletions(-) diff --git a/src/GameCult.Networking/CultNetRudpSchemaServer.cs b/src/GameCult.Networking/CultNetRudpSchemaServer.cs index 1abce308..f337dcd4 100644 --- a/src/GameCult.Networking/CultNetRudpSchemaServer.cs +++ b/src/GameCult.Networking/CultNetRudpSchemaServer.cs @@ -281,10 +281,24 @@ namespace GameCult.Networking return false; } - var result = handler.DynamicInvoke(message, new RudpCultNetSchemaServerPeer(this, delivered.Peer)); - if (result is Task task) + // R-AG: a handler is expected to catch its own typed refusals (HandleSnapshotRequestV1Async + // catches the three selection exceptions and answers cursor_invalid/selection_invalid/ + // reference_outside_target on the wire) - this catch is the backstop for whatever a + // handler does not, so an untyped exception from a malformed/hostile message can never + // reach the poll loop and stall the server for every other peer. It answers nothing on the + // wire (an exception this generic carries no typed refusal to report) and simply drops the + // one malformed dispatch, exactly as an unregistered handler already does just above. + try { - await task.ConfigureAwait(false); + var result = handler.DynamicInvoke(message, new RudpCultNetSchemaServerPeer(this, delivered.Peer)); + if (result is Task task) + { + await task.ConfigureAwait(false); + } + } + catch (Exception) + { + return false; } return true; } diff --git a/src/GameCult.Networking/CultNetSelectionEvaluator.cs b/src/GameCult.Networking/CultNetSelectionEvaluator.cs index 298eaae2..84f8631a 100644 --- a/src/GameCult.Networking/CultNetSelectionEvaluator.cs +++ b/src/GameCult.Networking/CultNetSelectionEvaluator.cs @@ -448,11 +448,16 @@ namespace GameCult.Networking return incoming; } + // R-AK: no `!member.IsReference` guard here - CultCache.ReferencesOf (CultCache.cs:262-278) + // already searches only its own RichMembers' reference members for a role match and + // returns empty for anything else, including a data member's own alias (index aliases are + // unique per descriptor, so a data member's role string can never coincide with a + // reference member's). A second copy of the same exclusion here was duplicate authority, + // not a second decision - CultCache owns "is this member a reference" once. private static IEnumerable ReferenceMembers(CultDocumentDescriptor descriptor, string? role) { foreach (var member in descriptor.DeclaredMembers) { - if (!member.IsReference) continue; if (role != null && (member.IndexAlias ?? member.MemberName) != role) continue; yield return member; } @@ -747,7 +752,13 @@ namespace GameCult.Networking if (!int.TryParse(lengthText, NumberStyles.None, CultureInfo.InvariantCulture, out var length)) return null; pos = colon + 1; - if (length < 0 || pos + length > bytes.Length) return null; + // R-AG: checked arithmetic - an attacker-supplied prefix near int.MaxValue makes + // `pos + length` overflow in unchecked int math (C#'s default), wrapping negative and + // slipping past this guard; GetString then throws ArgumentOutOfRangeException instead + // of this method returning null the way every other malformed shape does. `(long)` + // promotes before the add so the sum can never wrap - both operands are bounded well + // under long's range, so this can never itself overflow. + if (length < 0 || (long)pos + length > bytes.Length) return null; fields.Add(Encoding.UTF8.GetString(bytes, pos, length)); pos += length; } diff --git a/tests/GameCult.Networking.Tests/CultNetSelectionFixBatchTests.cs b/tests/GameCult.Networking.Tests/CultNetSelectionFixBatchTests.cs index b45c072d..d6653cf2 100644 --- a/tests/GameCult.Networking.Tests/CultNetSelectionFixBatchTests.cs +++ b/tests/GameCult.Networking.Tests/CultNetSelectionFixBatchTests.cs @@ -333,6 +333,68 @@ namespace GameCult.Networking.Tests Assert.That(second.NextCursor, Is.Null); } + /// + /// Builds a cursor body whose 5th (final) field carries a raw, hostile length-prefix + /// spelling instead of a well-formed `AppendString` field - R-AG. The first 4 fields are + /// well-formed so ReadLengthPrefixedFields reaches the hostile one mid-loop rather + /// than failing earlier for an unrelated reason. + /// + private static string CursorWithHostileLastField(string hostileField) + { + var body = new System.Text.StringBuilder(); + void AppendString(string value) => + body.Append(System.Text.Encoding.UTF8.GetByteCount(value)).Append(':').Append(value); + AppendString("1"); + AppendString("5"); + AppendString("schema-a"); + AppendString("k1"); + body.Append(hostileField); + var bytes = System.Text.Encoding.UTF8.GetBytes(body.ToString()); + return Convert.ToBase64String(bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_'); + } + + // R-AG: C#'s own proven overflow (CultNetSelectionEvaluator.cs, ReadLengthPrefixedFields, + // before this cut) - a length prefix of int.MaxValue (2147483647) made `pos + length` + // overflow int math and slip past the guard, so Encoding.UTF8.GetString threw + // ArgumentOutOfRangeException instead of Parse returning the typed cursor_invalid refusal. + [Test] + public void HostileCursor_LengthPrefixNearInt32Max_RefusesTypedNotUntyped() + { + var cursor = CursorWithHostileLastField("2147483647:x"); + Assert.Throws(() => CultNetSelectionCursor.Parse(cursor)); + } + + // R-AG: the mirror-image proven overflow, Rust's (packages/cultnet-rs/src/selection.rs, + // read_length_prefixed_fields, before this cut) - a length prefix of usize::MAX + // (18446744073709551615) overflowed Rust's usize guard and panicked. "Each runtime holding + // exactly the hole the other closed" means neither side's tests are evidence about the + // other - fed here too. int.TryParse refuses a value this wide outright (a different + // failure path than C#'s own overflow above), which must also refuse typed. + [Test] + public void HostileCursor_LengthPrefixNearUSizeMax_RefusesTypedNotUntyped() + { + var cursor = CursorWithHostileLastField("18446744073709551615:x"); + Assert.Throws(() => CultNetSelectionCursor.Parse(cursor)); + } + + // R-AG: a length prefix with more digits than any integer type holds. + [Test] + public void HostileCursor_LengthPrefixWiderThanAnyIntegerType_RefusesTypedNotUntyped() + { + var cursor = CursorWithHostileLastField("999999999999999999999999999999:x"); + Assert.Throws(() => CultNetSelectionCursor.Parse(cursor)); + } + + // R-AG: a negative-looking length prefix - int.TryParse(NumberStyles.None, ...) refuses the + // leading '-' outright (NumberStyles.None permits no sign), a third failure path (neither + // overflow nor digit-count) that must also refuse typed. + [Test] + public void HostileCursor_NegativeLengthPrefix_RefusesTypedNotUntyped() + { + var cursor = CursorWithHostileLastField("-1:x"); + Assert.Throws(() => CultNetSelectionCursor.Parse(cursor)); + } + // R-J: any_of on a numeric alias compares TryGetIndexNumber's canonical rendering, not the // string getter's culture-dependent ToString() - a float large enough that .NET's default // ToString() renders exponent notation ("1E+21") must still match its canonical decimal form.