From 40533b4f2df0c06d2b137918fd2d160bda2fe5a3 Mon Sep 17 00:00:00 2001 From: "OpenGenesis (MPL 2.0)" <153564363+opengenesislink@users.noreply.github.com> Date: Sat, 7 Nov 2026 19:24:16 +0100 Subject: [PATCH] test(net10/yengine): gate typed script state and legacy BinaryFormatter rejection --- .../workflows/ogl-yengine-binaryformatter.yml | 34 ++++ .../BINARYFORMATTER_RUNTIME_CLEANUP.md | 40 ++++ .../Program.cs | 173 ++++++++++++++++++ .../YEngineBinaryFormatterRegression.csproj | 13 ++ .../verify_yengine_binaryformatter_safety.py | 30 +++ 5 files changed, 290 insertions(+) create mode 100644 .github/workflows/ogl-yengine-binaryformatter.yml create mode 100644 doc/NexVerse/BINARYFORMATTER_RUNTIME_CLEANUP.md create mode 100644 tools/ci/YEngineBinaryFormatterRegression/Program.cs create mode 100644 tools/ci/YEngineBinaryFormatterRegression/YEngineBinaryFormatterRegression.csproj create mode 100644 tools/ci/verify_yengine_binaryformatter_safety.py diff --git a/.github/workflows/ogl-yengine-binaryformatter.yml b/.github/workflows/ogl-yengine-binaryformatter.yml new file mode 100644 index 00000000..653a54c1 --- /dev/null +++ b/.github/workflows/ogl-yengine-binaryformatter.yml @@ -0,0 +1,34 @@ +name: OGL .NET 10 BinaryFormatter YEngine Safety + +on: + pull_request: + paths: + - 'OpenSim/Framework/Util.cs' + - 'OpenSim/Region/ScriptEngine/YEngine/**' + - 'tools/ci/YEngineBinaryFormatterRegression/**' + - 'tools/ci/verify_yengine_binaryformatter_safety.py' + - '.github/workflows/ogl-yengine-binaryformatter.yml' + workflow_dispatch: + +permissions: + contents: read + +jobs: + yengine-binaryformatter-gate: + runs-on: ubuntu-latest + timeout-minutes: 35 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-dotnet@v4 + with: + dotnet-version: '10.0.x' + - name: Verify old unsafe YEngine paths are disabled + run: python3 tools/ci/verify_yengine_binaryformatter_safety.py + - name: Generate OpenSim .NET 10 solution + run: | + chmod +x runprebuild.sh + ./runprebuild.sh + - name: Build full OpenGenesisLINK G1 .NET 10 solution + run: dotnet build OpenSim.sln -c Release + - name: Exercise YEngine safe state roundtrips and legacy rejection + run: dotnet run --project tools/ci/YEngineBinaryFormatterRegression/YEngineBinaryFormatterRegression.csproj -c Release diff --git a/doc/NexVerse/BINARYFORMATTER_RUNTIME_CLEANUP.md b/doc/NexVerse/BINARYFORMATTER_RUNTIME_CLEANUP.md new file mode 100644 index 00000000..9875e846 --- /dev/null +++ b/doc/NexVerse/BINARYFORMATTER_RUNTIME_CLEANUP.md @@ -0,0 +1,40 @@ +# OpenGenesisLINK G1: BinaryFormatter removal and YEngine state compatibility + +**State:** new `.NET 10` safety changes are staged in a separate PR, not +merged or deployed to production. + +## Runtime paths inventoried + +| Area | Previously unsafe call | Current remediation | +| --- | --- | --- | +| KeyframeMotion | BinaryFormatter serializing persistent prim movements | Typed OGKF v1 and explicit offline NRBF converter in **PR #396** | +| YEngine script state | `Ser.SYSERIAL` / `Ser.THROWNEX` serialize/deserialize arbitrary CLR graphs | Allowlisted typed exception codec and dedicated `SYSERIALSAFE` / `THROWNEXSAFE` tags in this PR | +| Generic framework helpers | `Util.SerializeToFile`, `DeserializeFromFile` | No in-tree callers; fail closed with `NotSupportedException`. The two APIs stay as obsolete signatures to make external callers fail explicitly. | +| ubOdeMesh cache | Commented-out historical BinaryFormatter code | No active BinaryFormatter call; no mesh cache change in this PR | + +## YEngine saved script state recovery requirements + +YEngine legacy snapshots use a **different format** from the KeyframeMotion +BLOBs. Never run the KeyframeMotion converter against a YEngine `.state` file. + +New YEngine state uses explicit, bounded serializations of known exception types. +Old `Ser.SYSERIAL` and `Ser.THROWNEX` records are **rejected** rather +than interpreted as .NET object graphs. The original persisted XML is kept: +startup does not delete the `.state` file, reset global variables or +rerun `state_entry` after a failed restore. State writes now use a +bounded 8-MiB XML document and atomic same-directory replacement. + +**Existing legacy script state is NOT automatically migrated.** When a script +contains an unsupported historic exception graph, its restart must fail +loudly, preserving the original data. A runtime-side transparent migration +would reintroduce unsafe arbitrary object activation and is prohibited. + +Before deployment: stop the staging simulator, snapshot all `.state` +files and inventories, restore a representative script archive on +`/opt/developer`, inspect which legacy states cannot load, and verify +critical scripts (economy, rentals, land, permissions, teleports, payments) +do not silently replay side effects. An approved per-state offline +conversion/restart policy is needed for such records. + +This PR does **not** automatically rewrite or remove old script data, affect +the primary `main` branch or change the standalone Keyframe migration PR. diff --git a/tools/ci/YEngineBinaryFormatterRegression/Program.cs b/tools/ci/YEngineBinaryFormatterRegression/Program.cs new file mode 100644 index 00000000..ec3d3784 --- /dev/null +++ b/tools/ci/YEngineBinaryFormatterRegression/Program.cs @@ -0,0 +1,173 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Xml; +using OpenSim.Framework; +using OpenSim.Region.ScriptEngine.Yengine; + +static void Check(bool condition, string message) +{ + if (!condition) throw new Exception("YEngine BinaryFormatter regression: " + message); +} +static void Reject(Action action, string reason) where T : Exception +{ + try { action(); } + catch (T) { return; } + throw new Exception("Expected " + typeof(T).Name + ": " + reason); +} +static XMRInstance Fake() +{ + return (XMRInstance)RuntimeHelpers.GetUninitializedObject(typeof(XMRInstance)); +} +static void SetField(XMRInstance instance, string name, object value) +{ + FieldInfo field = typeof(XMRInstance).GetField(name, + BindingFlags.Instance | BindingFlags.NonPublic) + ?? throw new Exception("Missing YEngine field " + name); + field.SetValue(instance, value); +} +static byte[] WriteStateValue(object value) +{ + XMRInstance instance = Fake(); + using MemoryStream memory = new MemoryStream(); + using BinaryWriter writer = new BinaryWriter(memory); + SetField(instance, "migrateOutWriter", writer); + SetField(instance, "migrateOutObjects", new Dictionary()); + instance.SendObjValue(value); + writer.Flush(); + return memory.ToArray(); +} +static object ReadStateValue(byte[] data) +{ + XMRInstance instance = Fake(); + using MemoryStream memory = new MemoryStream(data, false); + using BinaryReader reader = new BinaryReader(memory); + SetField(instance, "migrateInReader", reader); + SetField(instance, "migrateInObjects", new Dictionary()); + return instance.RecvObjValue(); +} +static T InvokeState(string name, params object[] args) +{ + MethodInfo method = typeof(XMRInstance).GetMethod(name, + BindingFlags.Static | BindingFlags.NonPublic) + ?? throw new Exception("Missing YEngine state helper " + name); + try { return (T)method.Invoke(null, args); } + catch (TargetInvocationException ex) when (ex.InnerException != null) + { + System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(ex.InnerException).Throw(); + throw; + } +} + +try +{ + // Live serializer/deserializer: the .NET 10 branches must be exercised, + // not just a static check that the unsafe API text disappeared. + foreach (Exception original in new Exception[] { + new InvalidOperationException("safe-test"), + new NullReferenceException("null-test"), + new ArgumentException("arg-test"), + new FormatException("format-test") + }) + { + byte[] payload = WriteStateValue(original); + Check(payload[0] == 23, "new SYSERIALSAFE tag"); + Exception restored = ReadStateValue(payload) as Exception; + Check(restored != null && + restored.GetType() == original.GetType() && + restored.Message == original.Message, "exception typed roundtrip"); + } + + var thrown = (ScriptThrownException)ScriptThrownException.Wrap("LSL thrown-value"); + byte[] wrapped = WriteStateValue(thrown); + Check(wrapped[0] == 24, "new THROWNEXSAFE tag"); + var recovered = ReadStateValue(wrapped) as ScriptThrownException; + Check(recovered != null && (string)recovered.thrown == "LSL thrown-value", + "script-thrown wrapper value roundtrip"); + + int[] inputArray = { 10, 20, 30 }; + int[] roundtripArray = ReadStateValue(WriteStateValue(inputArray)) as int[]; + Check(roundtripArray != null && roundtripArray.Length == 3 && + roundtripArray[2] == 30, "allowlisted array roundtrip"); + + Reject(() => WriteStateValue(new Uri("https://example.invalid/")), + "arbitrary CLR objects must not be serialized"); + Reject(() => WriteStateValue(new SystemException("unlisted")), + "unknown CLR exception types must fail closed"); + Reject(() => WriteStateValue(new int[65537]), + "oversized array must not serialize"); + Reject(() => WriteStateValue(new string('x', 262145)), + "oversized string must not serialize"); + + // Original ordinal tag numbers are retained for backward compatibility. + // Legacy BinaryFormatter object graphs MUST NOT be executed or restored. + Reject(() => ReadStateValue(new byte[] { 21 }), + "legacy SYSERIAL must reject without reading an object graph"); + Reject(() => ReadStateValue(new byte[] { 22 }), + "legacy THROWNEX must reject without reading an object graph"); + + using (MemoryStream memory = new MemoryStream()) + { + using (BinaryWriter writer = new BinaryWriter(memory, System.Text.Encoding.UTF8, true)) + { + writer.Write((byte)9); // SYSARRAY + writer.Write("System.IO.FileInfo, mscorlib"); // forbidden type lookup + writer.Write(1); + } + Reject(() => ReadStateValue(memory.ToArray()), + "arbitrary CLR array types must not trigger reflection loading"); + } + + // Saved state XML is written atomically, bounded, and DTD-free. + string root = Path.Combine(Path.GetTempPath(), "ogl-yengine-regression-" + + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(root); + try + { + string path = Path.Combine(root, "test-script.state"); + File.WriteAllText(path, "old"); + Reject(() => + InvokeState("WriteStateFileAtomically", path, + new string('x', 8 * 1024 * 1024 + 1)), + "oversized XML write"); + Check(File.ReadAllText(path) == "old", + "bad state write preserved original bytes"); + Check(Directory.GetFiles(root).Length == 1, + "bad state write did not leave temporary files"); + + InvokeState("WriteStateFileAtomically", path, + "safe"); + XmlDocument loaded = InvokeState("ReadPersistedStateXmlFile", path); + Check(loaded.DocumentElement?.InnerText == "safe", + "atomic state file persisted and reloaded"); + + string dangerous = "]>" + + "&ext;"; + File.WriteAllText(path, dangerous); + Reject(() => + InvokeState("ReadPersistedStateXmlFile", path), + "DTD cannot resolve local file"); + Check(File.ReadAllText(path) == dangerous, + "invalid saved state remains preserved for migration"); + + File.WriteAllText(path, "original"); + Reject(() => Util.SerializeToFile(path, "new"), + "obsolete generic serializer must fail closed"); + Check(File.ReadAllText(path) == "original", + "generic serializer did not truncate existing state"); + Reject(() => Util.DeserializeFromFile(path), + "obsolete generic deserializer must fail closed"); + } + finally { Directory.Delete(root, true); } + + Console.WriteLine("PASS: YEngine .NET 10 safe script state: exception/LSL/array roundtrip, " + + "legacy tag rejection, protected .state files and Util fail-closed"); + return 0; +} +catch (Exception e) +{ + Console.Error.WriteLine(e); + return 1; +} diff --git a/tools/ci/YEngineBinaryFormatterRegression/YEngineBinaryFormatterRegression.csproj b/tools/ci/YEngineBinaryFormatterRegression/YEngineBinaryFormatterRegression.csproj new file mode 100644 index 00000000..734bdb9a --- /dev/null +++ b/tools/ci/YEngineBinaryFormatterRegression/YEngineBinaryFormatterRegression.csproj @@ -0,0 +1,13 @@ + + + Exe + net10.0 + enable + disable + false + + + + + + diff --git a/tools/ci/verify_yengine_binaryformatter_safety.py b/tools/ci/verify_yengine_binaryformatter_safety.py new file mode 100644 index 00000000..6f75b107 --- /dev/null +++ b/tools/ci/verify_yengine_binaryformatter_safety.py @@ -0,0 +1,30 @@ +#!/usr/bin/env python3 +"""Ensure .NET 10 YEngine and generic helpers never activate BinaryFormatter.""" +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +y = (ROOT / "OpenSim/Region/ScriptEngine/YEngine/XMRInstAbstract.cs").read_text() +codec = (ROOT / "OpenSim/Region/ScriptEngine/YEngine/ScriptStateExceptionCodec.cs").read_text() +util = (ROOT / "OpenSim/Framework/Util.cs").read_text() +ctor = (ROOT / "OpenSim/Region/ScriptEngine/YEngine/XMRInstCtor.cs").read_text() +capture = (ROOT / "OpenSim/Region/ScriptEngine/YEngine/XMRInstCapture.cs").read_text() +for name, src in [("YEngine", y), ("Codec", codec)]: + assert "new BinaryFormatter(" not in src, name + assert "new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter" not in src, name + assert "formatter.Deserialize(" not in src and "bformatter.Deserialize(" not in src, name +assert "case Ser.SYSERIAL:\n case Ser.THROWNEX:\n throw new InvalidDataException" in y +assert "SYSERIALSAFE" in y and "THROWNEXSAFE" in y +assert "ScriptStateExceptionCodec.Write(" in y +assert "ScriptStateExceptionCodec.Read(" in y +assert "Type.GetType(str, true)" not in y +assert "MaxMigrationDepth" in y and "MaxMigrationNodes" in y +assert "new BinaryFormatter(" not in util +assert "throw new NotSupportedException(" in util.split( + "public static void SerializeToFile(", 1)[1].split("public static string Compress", 1)[0] +assert "File.Delete(m_StateFileName)" not in ctor.split("private void LoadInitialState()", 1)[1].split( + "private static EventParams", 1)[0] +assert "ReadPersistedStateXmlFile(m_StateFileName)" in ctor +assert "WriteStateFileAtomically(m_StateFileName, scriptStateN.OuterXml)" in capture +assert "DtdProcessing = DtdProcessing.Prohibit" in capture +assert "File.Move(temporary, statePath, overwrite: true)" in capture +print("PASS: no BinaryFormatter activation in YEngine or Util, legacy state preserved")