diff --git a/.github/workflows/nexjast-ci.yml b/.github/workflows/nexjast-ci.yml index f20c32f3..f39839e0 100644 --- a/.github/workflows/nexjast-ci.yml +++ b/.github/workflows/nexjast-ci.yml @@ -684,6 +684,11 @@ jobs: shell: bash run: dotnet run --configuration Release --project tools/ci/OglWarpMeshRegression/OglWarpMeshRegression.csproj + - name: Regression-test CAPS mesh upload instance bounds and malformed payloads + run: | + dotnet run --configuration Release --project tools/ci/OglMeshCapsIndexRegression/OglMeshCapsIndexRegression.csproj + python3 tools/ci/verify_ogl_mesh_caps_guard.py + - name: Regression-test LLSD mesh upload fee instances shell: bash run: dotnet run --configuration Release --project tools/ci/NexMeshUploadFeeRegression/NexMeshUploadFeeRegression.csproj diff --git a/OpenSim/Region/ClientStack/Linden/Caps/BunchOfCaps/BunchOfCaps.cs b/OpenSim/Region/ClientStack/Linden/Caps/BunchOfCaps/BunchOfCaps.cs index 64e7a065..8532230c 100644 --- a/OpenSim/Region/ClientStack/Linden/Caps/BunchOfCaps/BunchOfCaps.cs +++ b/OpenSim/Region/ClientStack/Linden/Caps/BunchOfCaps/BunchOfCaps.cs @@ -649,6 +649,8 @@ namespace OpenSim.Region.ClientStack.Linden { lock (m_ModelCost) m_FileAgentInventoryState = FileAgentInventoryState.processUpload; + try + { m_log.DebugFormat( "[BUNCH OF CAPS]: Uploaded asset {0} for inventory item {1}, inv type {2}, asset type {3}", @@ -727,7 +729,35 @@ namespace OpenSim.Region.ClientStack.Linden List positions = new List(); List rotations = new List(); - OSDMap request = (OSDMap)OSDParser.DeserializeLLSDXml(data); + OSDMap request; + try + { + request = OSDParser.DeserializeLLSDXml(data) as OSDMap; + } + catch (Exception ex) when (ex is FormatException || + ex is InvalidCastException || ex is ArgumentException || + ex is IndexOutOfRangeException || ex is NullReferenceException) + { + m_log.WarnFormat("[MESH UPLOAD]: Malformed uploaded mesh LLSD ({0}).", + ex.GetType().Name); + error = "Invalid mesh upload data."; + lock (m_ModelCost) + m_FileAgentInventoryState = FileAgentInventoryState.idle; + return; + } + if (request == null || + !request.TryGetValue("instance_list", out OSD instancesOSD) || + instancesOSD is not OSDArray || + !request.TryGetValue("mesh_list", out OSD meshesOSD) || + meshesOSD is not OSDArray || + !request.TryGetValue("texture_list", out OSD texturesOSD) || + texturesOSD is not OSDArray) + { + error = "Mesh upload is missing a valid instance, mesh or texture list."; + lock (m_ModelCost) + m_FileAgentInventoryState = FileAgentInventoryState.idle; + return; + } // compare and get updated information /* does nothing still we do need something to avoid special viewer to upload something diferent from the cost estimation @@ -752,6 +782,50 @@ namespace OpenSim.Region.ClientStack.Linden OSDArray texture_list = (OSDArray)request["texture_list"]; SceneObjectGroup grp = null; + // Upload bytes must be validated again: the viewer's fee + // request may not describe the data actually uploaded. + // Reject bad indices BEFORE storing any texture/mesh assets. + float primScaleMin = m_ModelCost.PrimScaleMin; + int validInstances = 0; + foreach (OSD instance in instance_list) + { + if (instance is not OSDMap modelInstance || + !modelInstance.TryGetValue("scale", out OSD scaleOSD) || + !modelInstance.TryGetValue("face_list", out OSD facesOSD) || + facesOSD is not OSDArray faces) + { + error = "Mesh upload contains an invalid object instance."; + lock (m_ModelCost) + m_FileAgentInventoryState = FileAgentInventoryState.idle; + return; + } + + Vector3 uploadScale = scaleOSD.AsVector3(); + if (uploadScale.X < primScaleMin || + uploadScale.Y < primScaleMin || + uploadScale.Z < primScaleMin) + continue; + + if (modelInstance.ContainsKey("mesh") && + !MeshUploadIndexGuard.TryResolveSides( + modelInstance["mesh"].AsInteger(), mesh_list.Count, + meshesSides, faces.Count, out _)) + { + error = "Mesh upload references a missing or invalid mesh index."; + lock (m_ModelCost) + m_FileAgentInventoryState = FileAgentInventoryState.idle; + return; + } + validInstances++; + } + if (!MeshUploadIndexGuard.HasRenderableRoot(validInstances)) + { + error = "Mesh upload contains no renderable object instances."; + lock (m_ModelCost) + m_FileAgentInventoryState = FileAgentInventoryState.idle; + return; + } + // create and store texture assets bool doTextInv = (!istest && ConfigOptions.enableModelUploadTextureToInventory && texturesFolder != UUID.Zero); @@ -878,7 +952,6 @@ namespace OpenSim.Region.ClientStack.Linden } int skipedMeshs = 0; - float primScaleMin = m_ModelCost.PrimScaleMin; // build prims from instances for (int i = 0; i < instance_list.Count; i++) { @@ -899,12 +972,21 @@ namespace OpenSim.Region.ClientStack.Linden if (inner_instance_list.ContainsKey("mesh")) // seems to happen always but ... { int meshindx = inner_instance_list["mesh"].AsInteger(); - if (meshAssets.Count > meshindx) + if (MeshUploadIndexGuard.TryResolveSides( + meshindx, meshAssets.Count, meshesSides, face_list.Count, + out int meshSideCount)) { - if(meshesSides != null && meshesSides.Length > meshindx) - pbs = PrimitiveBaseShape.CreateMesh(meshesSides[i], meshAssets[meshindx]); - else - pbs = PrimitiveBaseShape.CreateMesh(face_list.Count, meshAssets[meshindx]); + // meshSideCount uses meshindx, not instance i: + // several instances can refer to one mesh. + pbs = PrimitiveBaseShape.CreateMesh( + meshSideCount, meshAssets[meshindx]); + } + else + { + error = "Mesh upload references a missing or invalid mesh index."; + lock (m_ModelCost) + m_FileAgentInventoryState = FileAgentInventoryState.idle; + return; } } if(pbs == null) // fallback @@ -945,7 +1027,8 @@ namespace OpenSim.Region.ClientStack.Linden if (scalet != 0) f.RepeatV = scalet; - if (textures.Count > textureNum) + // A negative texture index must not index the list. + if (textureNum >= 0 && textureNum < textures.Count) f.TextureID = textures[textureNum]; textureEntry.FaceTextures[face] = f; @@ -1035,6 +1118,13 @@ namespace OpenSim.Region.ClientStack.Linden grp.AddPart(prim); } + if (!MeshUploadIndexGuard.HasRenderableRoot(positions.Count) || grp == null) + { + error = "Mesh upload contains no renderable root object."; + lock (m_ModelCost) + m_FileAgentInventoryState = FileAgentInventoryState.idle; + return; + } Vector3 rootPos = positions[0]; if (grp.Parts.Length > 1) @@ -1170,8 +1260,14 @@ namespace OpenSim.Region.ClientStack.Linden } } - lock (m_ModelCost) - m_FileAgentInventoryState = FileAgentInventoryState.idle; + } + finally + { + // A rejected or malformed mesh upload must never leave the + // viewer stuck in the processUpload/busy state. + lock (m_ModelCost) + m_FileAgentInventoryState = FileAgentInventoryState.idle; + } } public void CreateInventoryCategory(IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) @@ -2708,9 +2804,28 @@ namespace OpenSim.Region.ClientStack.Linden handlerUpLoad = OnUpLoad; if (handlerUpLoad != null) { - handlerUpLoad(m_assetName, m_assetDes, newAssetID, inv, parentFolder, data, m_invType, m_assetType, - m_cost, m_texturesFolder, m_nreqtextures, m_nreqmeshs, m_nreqinstances, m_IsAtestUpload, - ref m_error, ref m_nextOwnerMask, ref m_groupMask, ref m_everyoneMask, m_meshesSides); + try + { + handlerUpLoad(m_assetName, m_assetDes, newAssetID, inv, parentFolder, data, m_invType, m_assetType, + m_cost, m_texturesFolder, m_nreqtextures, m_nreqmeshs, m_nreqinstances, m_IsAtestUpload, + ref m_error, ref m_nextOwnerMask, ref m_groupMask, ref m_everyoneMask, m_meshesSides); + } + catch (Exception exception) when (m_assetType == "mesh" && + (exception is IndexOutOfRangeException || + exception is ArgumentOutOfRangeException || + exception is InvalidCastException || + exception is KeyNotFoundException || + exception is FormatException || + exception is NullReferenceException)) + { + // Malformed LLSD/mesh payloads are client input errors. + // Report a failed upload to the viewer, never an + // unhandled HTTP 500. The handler's finally block + // restores the per-agent upload state. + m_log.WarnFormat("[MESH UPLOAD]: Invalid uploaded mesh payload ({0}).", + exception.GetType().Name); + m_error = "Invalid or unsupported mesh upload data."; + } } uploadComplete.new_next_owner_mask = m_nextOwnerMask; diff --git a/OpenSim/Region/ClientStack/Linden/Caps/BunchOfCaps/MeshUploadIndexGuard.cs b/OpenSim/Region/ClientStack/Linden/Caps/BunchOfCaps/MeshUploadIndexGuard.cs new file mode 100644 index 00000000..9700f66b --- /dev/null +++ b/OpenSim/Region/ClientStack/Linden/Caps/BunchOfCaps/MeshUploadIndexGuard.cs @@ -0,0 +1,35 @@ +// SPDX-License-Identifier: MPL-2.0 +#nullable enable +using System; + +namespace OpenSim.Region.ClientStack.Linden +{ + /// + /// Bounds-check the mesh index supplied by each uploaded instance. + /// Instances and meshes are different lists: many instances may refer + /// to a single mesh. The mesh sides lookup MUST use meshIndex, never + /// the index in instance_list. + /// + public static class MeshUploadIndexGuard + { + public static bool TryResolveSides(int meshIndex, int meshCount, + int[]? meshSides, int instanceFaceCount, out int sides) + { + sides = 0; + if (meshIndex < 0 || meshIndex >= meshCount || meshCount < 1) + return false; + + // Older or custom viewers may send a missing/short fee-side + // array. In that case use the instance's face count, as before. + // At least one face is needed when constructing the prim shape. + sides = meshSides != null && meshIndex < meshSides.Length && + meshSides[meshIndex] > 0 + ? meshSides[meshIndex] + : Math.Max(1, instanceFaceCount); + return true; + } + + public static bool HasRenderableRoot(int renderableInstanceCount) + => renderableInstanceCount > 0; + } +} diff --git a/tools/ci/OglMeshCapsIndexRegression/OglMeshCapsIndexRegression.csproj b/tools/ci/OglMeshCapsIndexRegression/OglMeshCapsIndexRegression.csproj new file mode 100644 index 00000000..f53c32a9 --- /dev/null +++ b/tools/ci/OglMeshCapsIndexRegression/OglMeshCapsIndexRegression.csproj @@ -0,0 +1,13 @@ + + + Exe + net10.0 + enable + enable + true + + + + + diff --git a/tools/ci/OglMeshCapsIndexRegression/Program.cs b/tools/ci/OglMeshCapsIndexRegression/Program.cs new file mode 100644 index 00000000..6ddb5ce7 --- /dev/null +++ b/tools/ci/OglMeshCapsIndexRegression/Program.cs @@ -0,0 +1,51 @@ +using OpenSim.Region.ClientStack.Linden; + +static void Check(bool result, string message) +{ + if (!result) throw new InvalidOperationException(message); +} + +// The actual stacktrace case: one mesh reused by three instances. +// Previously the loop used meshesSides[instanceIndex], so instance #2 +// could access the one-element mesh sides array outside bounds. +int[] meshSides = { 7 }; +foreach (int instanceIndex in new[] { 0, 1, 2 }) +{ + Check(MeshUploadIndexGuard.TryResolveSides(0, 1, meshSides, 3, out int faces), + $"Instance {instanceIndex}: shared mesh index unexpectedly rejected"); + Check(faces == 7, $"Instance {instanceIndex}: mesh side count differs by instance"); +} + +// Different instances can refer to meshes in any order; the side count +// belongs to the referenced mesh, not the object's position in the list. +int[] mixedSides = { 3, 9 }; +foreach (var test in new[] {(index: 1, expected: 9), (index: 0, expected: 3), (index: 1, expected: 9)}) +{ + Check(MeshUploadIndexGuard.TryResolveSides(test.index, 2, mixedSides, 2, out int sides), + "Valid mesh instance rejected"); + Check(sides == test.expected, "Wrong mesh-side array index used"); +} + +// Fee-side arrays may be null, partial, or contain an invalid zero entry. +// These cases fall back to the uploaded instance's face count. +Check(MeshUploadIndexGuard.TryResolveSides(1, 2, new[] { 3 }, 4, out int fallback) + && fallback == 4, "Short mesh-side list should use instance face count"); +Check(MeshUploadIndexGuard.TryResolveSides(0, 1, null, 6, out fallback) + && fallback == 6, "Null mesh-side list should use instance face count"); +Check(MeshUploadIndexGuard.TryResolveSides(0, 1, new[] { 0 }, 4, out fallback) + && fallback == 4, "Zero mesh-side value must fall back"); +Check(MeshUploadIndexGuard.TryResolveSides(0, 1, new[] { 0 }, 0, out fallback) + && fallback == 1, "Mesh must receive at least one side"); + +// Invalid index references must be rejected, never silently used. +Check(!MeshUploadIndexGuard.TryResolveSides(-1, 1, meshSides, 3, out _), + "Negative mesh index accepted"); +Check(!MeshUploadIndexGuard.TryResolveSides(1, 1, meshSides, 3, out _), + "Out-of-range mesh index accepted"); +Check(!MeshUploadIndexGuard.TryResolveSides(0, 0, meshSides, 3, out _), + "Missing mesh accepted"); +Check(!MeshUploadIndexGuard.HasRenderableRoot(0), + "All filtered instances must not cause positions[0] access"); +Check(MeshUploadIndexGuard.HasRenderableRoot(2), + "Valid model must keep its root instance"); +Console.WriteLine("OGL mesh CAPS instance/mesh index, side fallback, negative index and empty root: PASS"); diff --git a/tools/ci/verify_ogl_mesh_caps_guard.py b/tools/ci/verify_ogl_mesh_caps_guard.py new file mode 100644 index 00000000..1350c2d8 --- /dev/null +++ b/tools/ci/verify_ogl_mesh_caps_guard.py @@ -0,0 +1,17 @@ +#!/usr/bin/env python3 +"""Verify production CAPS path uses the same bounds-checked resolver as tests.""" +from pathlib import Path + +source = Path("OpenSim/Region/ClientStack/Linden/Caps/BunchOfCaps/BunchOfCaps.cs").read_text() +assert "MeshUploadIndexGuard.TryResolveSides(" in source +assert source.count("MeshUploadIndexGuard.TryResolveSides(") >= 2 +assert "meshesSides[i]" not in source, "Instance-indexed mesh side access reintroduced" +assert "meshindx, meshAssets.Count, meshesSides, face_list.Count" in source +assert "if (textureNum >= 0 && textureNum < textures.Count)" in source +assert "MeshUploadIndexGuard.HasRenderableRoot(validInstances)" in source +assert "MeshUploadIndexGuard.HasRenderableRoot(positions.Count)" in source +assert "error = \"Mesh upload contains no renderable object instances.\"" in source +assert 'exception is IndexOutOfRangeException' in source +assert 'm_error = "Invalid or unsupported mesh upload data."' in source +assert 'A rejected or malformed mesh upload must never leave the' in source +print("OGL production CAPS mesh-index and empty-root guard wiring: PASS")