Skip to content

Free, open-source 3D sculpting for Linux, macOS and Windows: dense meshes, remeshing, painting, built-in AI (image/text to 3D), Send to Unreal, game-ready LODs, Gaussian splats and OpenUSD.

glTF import: validate accessor, buffer view and GLB sizes before use

islandmed48f0018c9ff4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 88619e7a..ed760c19 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -88,6 +88,8 @@ All notable changes to SculptForge are listed here. The format follows
### Fixed
- Maya input style (#32): <kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>Shift</kbd>+drag erases the mask instead of starting
the <kbd>Ctrl</kbd>+<kbd>Shift</kbd> visibility selection.
+- glTF import rejects malformed accessor and buffer sizes instead of crashing or reading out of bounds (reported by
+ @Agapenordev in #70).
## [0.10.5] - 2026-11-01
### Added
diff --git a/src/io/GltfIO.cpp b/src/io/GltfIO.cpp
index 0d6572e7..ff0e1526 100644
--- a/src/io/GltfIO.cpp
+++ b/src/io/GltfIO.cpp
@@ -12,6 +12,7 @@
#include <cmath>
#include <functional>
#include <iterator>
+#include <limits>
#include <map>
#include <unordered_map>
@@ -408,6 +409,52 @@ bool saveSplatGlb(const std::string& path, const SplatCloud& c, std::string& err
namespace {
+// Limits for files from outside. Real data is also bounded by the bytes actually present; these caps cover what a
+// small file can make us allocate anyway (zero-filled accessors, instanced meshes, morph targets, repeated buffers).
+constexpr uint64_t kMaxJsonInteger = uint64_t(1) << 53; // doubles hold whole numbers exactly up to here
+constexpr size_t kMaxZeroFilledElements = size_t(1) << 24; // one accessor without a bufferView
+constexpr size_t kMaxZeroFilledTotal = size_t(1) << 26; // all of them together
+constexpr size_t kMaxImportVertices = size_t(1) << 27; // positions gathered over the whole file
+constexpr size_t kMaxImportTriangles = size_t(1) << 28;
+constexpr size_t kMaxMorphTargets = 4096;
+constexpr size_t kMaxMorphDeltas = size_t(1) << 28; // targets x vertices
+constexpr size_t kMaxBuffers = 4096;
+constexpr uint64_t kMaxBufferBytes = uint64_t(1) << 32; // all buffers together
+
+// A JSON value as a whole number in [0, max]: false when it is missing, not a number, negative, fractional,
+// non-finite or larger than max (casting such doubles to an integer is undefined behaviour).
+bool wholeNumber(const Json& v, uint64_t max, size_t& out) {
+ if (!v.isNumber()) return false;
+ const double d = v.asNumber();
+ if (!(d >= 0.0) || d > double(std::min<uint64_t>(max, kMaxJsonInteger)) || d != std::floor(d)) return false;
+ out = size_t(d);
+ return true;
+}
+
+// Like wholeNumber, but a missing value is `fallback` (an invalid present value is still an error).
+bool optionalWhole(const Json& v, uint64_t max, size_t fallback, size_t& out) {
+ if (v.isNull()) {
+ out = fallback;
+ return true;
+ }
+ return wholeNumber(v, max, out);
+}
+
+// An object index (accessor, node, mesh...) or -1 when the value is not a valid one.
+int jsonIndex(const Json& v) {
+ size_t i;
+ return wholeNumber(v, uint64_t(std::numeric_limits<int>::max()), i) ? int(i) : -1;
+}
+
+// A small enum-like integer (componentType, mode) or -1.
+int jsonEnum(const Json& v) { return jsonIndex(v); }
+
+// Doubles outside float range are clamped (the plain conversion is undefined); inf and NaN pass through.
+float toFloat(double d) {
+ if (std::isfinite(d)) d = std::clamp(d, -double(std::numeric_limits<float>::max()), double(std::numeric_limits<float>::max()));
+ return float(d);
+}
+
std::vector<uint8_t> base64Decode(const std::string& in) {
static const auto table = [] {
std::array<int, 256> t;
@@ -417,11 +464,13 @@ std::vector<uint8_t> base64Decode(const std::string& in) {
return t;
}();
std::vector<uint8_t> out;
- out.reserve(in.size() * 3 / 4);
- int val = 0, bits = -8;
+ out.reserve(in.size() / 4 * 3 + 3);
+ // Only the last 14 bits matter (8 being emitted plus up to 6 pending), so the accumulator stays bounded.
+ uint32_t val = 0;
+ int bits = -8;
for (unsigned char c : in) {
if (table[c] < 0) continue;
- val = (val << 6) | table[c];
+ val = ((val << 6) | uint32_t(table[c])) & 0xFFFFFu;
bits += 6;
if (bits >= 0) {
out.push_back(uint8_t((val >> bits) & 0xff));
@@ -438,47 +487,64 @@ bool readFile(const std::filesystem::path& p, std::vector<uint8_t>& out) {
return true;
}
+// True when `count` elements of `element` bytes, `stride` apart, fit in `available` bytes (no overflow).
+bool elementsFit(size_t count, size_t stride, size_t element, size_t available) {
+ if (count == 0) return true;
+ if (element > available) return false;
+ if (stride == 0) return true;
+ return count - 1 <= (available - element) / stride;
+}
+
struct GltfReader {
Json doc;
std::vector<std::vector<uint8_t>> buffers;
std::string error;
+ size_t zeroFilled = 0; // elements handed out for accessors without a bufferView
// Reads accessor `index` as floats (VEC3) or indices (SCALAR); returns false on unsupported layouts.
bool readVec3(int index, std::vector<glm::vec3>& out) {
- const Json& acc = doc["accessors"][size_t(index)];
- if (acc["type"].asString() != "VEC3" || int(acc["componentType"].asNumber()) != 5126) {
+ const Json* acc;
+ size_t count;
+ if (!accessor(index, acc, count)) return false;
+ if ((*acc)["type"].asString() != "VEC3" || jsonEnum((*acc)["componentType"]) != 5126) {
error = "Only float VEC3 positions are supported";
return false;
}
- const size_t count = size_t(acc["count"].asNumber());
- out.assign(count, glm::vec3(0.0f));
- if (acc["bufferView"].isNull()) return true; // all zeros (sparse not supported)
+ if ((*acc)["bufferView"].isNull()) { // all zeros (sparse not supported)
+ if (!zeroFill(count)) return false;
+ out.assign(count, glm::vec3(0.0f));
+ return true;
+ }
const uint8_t* base;
- size_t stride, available;
- if (!view(acc, 12, base, stride, available)) return false;
- if (count && (count - 1) * stride + 12 > available) return fail("Accessor out of range");
+ size_t stride;
+ if (!view(*acc, count, 12, base, stride)) return false;
+ out.assign(count, glm::vec3(0.0f));
for (size_t i = 0; i < count; ++i) std::memcpy(&out[i], base + i * stride, 12);
return true;
}
// Reads `components` values per element as floats, decoding normalized integers.
bool readFloats(int index, int components, std::vector<float>& out) {
- const Json& acc = doc["accessors"][size_t(index)];
+ const Json* acc;
+ size_t count;
+ if (!accessor(index, acc, count)) return false;
static const std::map<std::string, int> typeComponents = {{"SCALAR", 1}, {"VEC2", 2}, {"VEC3", 3}, {"VEC4", 4}};
- auto tc = typeComponents.find(acc["type"].asString());
+ auto tc = typeComponents.find((*acc)["type"].asString());
if (tc == typeComponents.end() || tc->second != components) return fail("Unexpected accessor type");
- const int type = int(acc["componentType"].asNumber());
+ const int type = jsonEnum((*acc)["componentType"]);
const size_t size = type == 5126 ? 4 : (type == 5122 || type == 5123) ? 2 : (type == 5120 || type == 5121) ? 1 : 0;
if (!size) return fail("Unsupported accessor component type");
- const bool normalized = acc["normalized"].asBool(false);
- const size_t count = size_t(acc["count"].asNumber());
- out.assign(count * size_t(components), 0.0f);
- if (acc["bufferView"].isNull()) return true;
+ const bool normalized = (*acc)["normalized"].asBool(false);
+ if ((*acc)["bufferView"].isNull()) {
+ if (!zeroFill(count)) return false;
+ out.assign(count * size_t(components), 0.0f);
+ return true;
+ }
const uint8_t* base;
- size_t stride, available;
+ size_t stride;
const size_t element = size * size_t(components);
- if (!view(acc, element, base, stride, available)) return false;
- if (count && (count - 1) * stride + element > available) return fail("Accessor out of range");
+ if (!view(*acc, count, element, base, stride)) return false;
+ out.assign(count * size_t(components), 0.0f);
for (size_t i = 0; i < count; ++i)
for (int c = 0; c < components; ++c) {
const uint8_t* p = base + i * stride + size_t(c) * size;
@@ -505,36 +571,68 @@ struct GltfReader {
}
bool readIndices(int index, std::vector<uint32_t>& out) {
- const Json& acc = doc["accessors"][size_t(index)];
- const int type = int(acc["componentType"].asNumber());
+ const Json* acc;
+ size_t count;
+ if (!accessor(index, acc, count)) return false;
+ const int type = jsonEnum((*acc)["componentType"]);
const size_t size = type == 5125 ? 4 : type == 5123 ? 2 : type == 5121 ? 1 : 0;
if (!size) return fail("Unsupported index type");
- const size_t count = size_t(acc["count"].asNumber());
+ if ((*acc)["bufferView"].isNull()) { // glTF 2.0: an accessor without a bufferView is all zeros
+ if (!zeroFill(count)) return false;
+ out.assign(count, 0);
+ return true;
+ }
const uint8_t* base;
- size_t stride, available;
- if (!view(acc, size, base, stride, available)) return false;
- if (count && (count - 1) * stride + size > available) return fail("Accessor out of range");
+ size_t stride;
+ if (!view(*acc, count, size, base, stride)) return false;
out.resize(count);
for (size_t i = 0; i < count; ++i) {
const uint8_t* p = base + i * stride;
- out[i] = size == 4 ? uint32_t(p[0] | p[1] << 8 | p[2] << 16 | uint32_t(p[3]) << 24)
- : size == 2 ? uint32_t(p[0] | p[1] << 8)
+ out[i] = size == 4 ? uint32_t(p[0]) | uint32_t(p[1]) << 8 | uint32_t(p[2]) << 16 | uint32_t(p[3]) << 24
+ : size == 2 ? uint32_t(p[0]) | uint32_t(p[1]) << 8
: uint32_t(p[0]);
}
return true;
}
- bool view(const Json& acc, size_t elementSize, const uint8_t*& base, size_t& stride, size_t& available) {
- const Json& bv = doc["bufferViews"][size_t(acc["bufferView"].asNumber())];
- const size_t buf = size_t(bv["buffer"].asNumber());
- if (buf >= buffers.size()) return fail("Missing buffer");
- const size_t viewOffset = size_t(bv["byteOffset"].asNumber());
- const size_t viewLength = size_t(bv["byteLength"].asNumber());
- const size_t accOffset = size_t(acc["byteOffset"].asNumber());
- if (viewOffset + viewLength > buffers[buf].size() || accOffset > viewLength) return fail("Buffer view out of range");
+ // Looks up accessor `index` and its element count; nothing is allocated here.
+ bool accessor(int index, const Json*& acc, size_t& count) {
+ if (index < 0 || size_t(index) >= doc["accessors"].size()) return fail("Accessor index out of range");
+ acc = &doc["accessors"][size_t(index)];
+ if (!acc->isObject()) return fail("Accessor is not an object");
+ if (!wholeNumber((*acc)["count"], kMaxJsonInteger, count)) return fail("Invalid accessor count");
+ return true;
+ }
+
+ // Accounts for an accessor without a bufferView (zero-filled), refusing absurd sizes before allocating.
+ bool zeroFill(size_t count) {
+ if (count > kMaxZeroFilledElements || count > kMaxZeroFilledTotal - zeroFilled)
+ return fail("Accessor without data is too large");
+ zeroFilled += count;
+ return true;
+ }
+
+ // Resolves the accessor's bytes and checks all `count` elements lie inside its buffer view and buffer.
+ bool view(const Json& acc, size_t count, size_t elementSize, const uint8_t*& base, size_t& stride) {
+ const int bvIndex = jsonIndex(acc["bufferView"]);
+ if (bvIndex < 0 || size_t(bvIndex) >= doc["bufferViews"].size()) return fail("Buffer view index out of range");
+ const Json& bv = doc["bufferViews"][size_t(bvIndex)];
+ size_t buf, viewOffset, viewLength, accOffset;
+ if (!wholeNumber(bv["buffer"], kMaxJsonInteger, buf) || buf >= buffers.size()) return fail("Missing buffer");
+ if (!optionalWhole(bv["byteOffset"], kMaxJsonInteger, 0, viewOffset) ||
+ !wholeNumber(bv["byteLength"], kMaxJsonInteger, viewLength) ||
+ !optionalWhole(acc["byteOffset"], kMaxJsonInteger, 0, accOffset))
+ return fail("Invalid buffer view offset or length");
+ const size_t bufSize = buffers[buf].size();
+ if (viewLength > bufSize || viewOffset > bufSize - viewLength || accOffset > viewLength)
+ return fail("Buffer view out of range");
+ if (bv["byteStride"].isNull()) {
+ stride = elementSize;
+ } else if (!wholeNumber(bv["byteStride"], 252, stride) || stride < elementSize) {
+ return fail("Invalid buffer view stride");
+ }
+ if (!elementsFit(count, stride, elementSize, viewLength - accOffset)) return fail("Accessor out of range");
base = buffers[buf].data() + viewOffset + accOffset;
- stride = bv["byteStride"].isNumber() ? size_t(bv["byteStride"].asNumber()) : elementSize;
- available = viewLength - accOffset;
return true;
}
@@ -547,19 +645,17 @@ struct GltfReader {
glm::mat4 nodeMatrix(const Json& node) {
if (node["matrix"].size() == 16) {
glm::mat4 m;
- for (int i = 0; i < 16; ++i) glm::value_ptr(m)[i] = float(node["matrix"][size_t(i)].asNumber());
+ for (int i = 0; i < 16; ++i) glm::value_ptr(m)[i] = toFloat(node["matrix"][size_t(i)].asNumber());
return m;
}
+ auto f = [](const Json& a, size_t i) { return toFloat(a[i].asNumber()); };
glm::mat4 m(1.0f);
const Json& t = node["translation"];
- if (t.size() == 3)
- m = glm::translate(m, glm::vec3(float(t[0].asNumber()), float(t[1].asNumber()), float(t[2].asNumber())));
+ if (t.size() == 3) m = glm::translate(m, glm::vec3(f(t, 0), f(t, 1), f(t, 2)));
const Json& r = node["rotation"];
- if (r.size() == 4)
- m *= glm::mat4_cast(glm::quat(float(r[3].asNumber()), float(r[0].asNumber()), float(r[1].asNumber()),
- float(r[2].asNumber())));
+ if (r.size() == 4) m *= glm::mat4_cast(glm::quat(f(r, 3), f(r, 0), f(r, 1), f(r, 2)));
const Json& s = node["scale"];
- if (s.size() == 3) m = glm::scale(m, glm::vec3(float(s[0].asNumber()), float(s[1].asNumber()), float(s[2].asNumber())));
+ if (s.size() == 3) m = glm::scale(m, glm::vec3(f(s, 0), f(s, 1), f(s, 2)));
return m;
}
@@ -578,6 +674,50 @@ struct GltfObject {
bool uvs = false; // some primitive had TEXCOORD_0
};
+// Splits a GLB container into its JSON text and BIN chunk; false with `error` on a malformed container.
+bool parseGlb(const std::vector<uint8_t>& file, std::string& jsonText, std::vector<uint8_t>& bin, bool& hasBin,
+ std::string& error) {
+ uint32_t version, total;
+ std::memcpy(&version, file.data() + 4, 4);
+ std::memcpy(&total, file.data() + 8, 4);
+ if (version != 2) {
+ error = "Unsupported GLB version " + std::to_string(version);
+ return false;
+ }
+ // The header's length may not exceed the file; trailing bytes after it are ignored.
+ if (total < 12 || total > file.size()) {
+ error = "Truncated GLB file";
+ return false;
+ }
+ const size_t end = total;
+ size_t offset = 12;
+ bool hasJson = false;
+ while (end - offset >= 8) {
+ uint32_t len, type;
+ std::memcpy(&len, file.data() + offset, 4);
+ std::memcpy(&type, file.data() + offset + 4, 4);
+ offset += 8;
+ if (len > end - offset) {
+ error = "Truncated GLB file";
+ return false;
+ }
+ if (type == 0x4E4F534A && !hasJson) {
+ jsonText.assign(reinterpret_cast<const char*>(file.data() + offset), len);
+ hasJson = true;
+ } else if (type == 0x004E4942 && !hasBin) {
+ bin.assign(file.begin() + std::ptrdiff_t(offset), file.begin() + std::ptrdiff_t(offset + len));
+ hasBin = true;
+ }
+ // Chunks are 4-byte aligned; a last chunk may end without its padding.
+ offset += std::min<size_t>((size_t(len) + 3) & ~size_t(3), end - offset);
+ }
+ if (!hasJson) {
+ error = "GLB file has no JSON chunk";
+ return false;
+ }
+ return true;
+}
+
bool readGltf(const std::string& path, bool split, std::vector<MeshObject>& out, std::string& error,
SplatCloud* splatsOut) {
const std::filesystem::path fsPath(std::u8string(path.begin(), path.end()));
@@ -592,23 +732,7 @@ bool readGltf(const std::string& path, bool split, std::vector<MeshObject>& out,
std::vector<uint8_t> glbBin;
bool hasGlbBin = false;
if (file.size() >= 12 && std::memcmp(file.data(), "glTF", 4) == 0) {
- size_t offset = 12;
- while (offset + 8 <= file.size()) {
- uint32_t len, type;
- std::memcpy(&len, file.data() + offset, 4);
- std::memcpy(&type, file.data() + offset + 4, 4);
- offset += 8;
- if (offset + len > file.size()) {
- error = "Truncated GLB file";
- return false;
- }
- if (type == 0x4E4F534A) jsonText.assign(reinterpret_cast<const char*>(file.data() + offset), len);
- else if (type == 0x004E4942) {
- glbBin.assign(file.begin() + std::ptrdiff_t(offset), file.begin() + std::ptrdiff_t(offset + len));
- hasGlbBin = true;
- }
- offset += (len + 3) & ~size_t(3);
- }
+ if (!parseGlb(file, jsonText, glbBin, hasGlbBin, error)) return false;
} else {
jsonText.assign(file.begin(), file.end());
}
@@ -617,6 +741,11 @@ bool readGltf(const std::string& path, bool split, std::vector<MeshObject>& out,
return false;
}
+ if (r.doc["buffers"].size() > kMaxBuffers) {
+ error = "Too many buffers";
+ return false;
+ }
+ uint64_t bufferBytes = 0;
for (size_t i = 0; i < r.doc["buffers"].size(); ++i) {
const std::string& uri = r.doc["buffers"][i]["uri"].asString();
std::vector<uint8_t> data;
@@ -630,25 +759,43 @@ bool readGltf(const std::string& path, bool split, std::vector<MeshObject>& out,
}
data = base64Decode(uri.substr(comma + 1));
} else if (!uri.empty()) {
- if (uri.find("..") != std::string::npos || std::filesystem::path(uri).is_absolute()) {
+ const std::filesystem::path rel(std::u8string(uri.begin(), uri.end()));
+ if (uri.find("..") != std::string::npos || rel.is_absolute() || rel.has_root_name() || rel.has_root_directory()) {
error = "Refusing buffer path outside the model's folder: " + uri;
return false;
}
- if (!readFile(fsPath.parent_path() / std::filesystem::path(uri), data)) {
+ const std::filesystem::path full = fsPath.parent_path() / rel;
+ std::error_code ec;
+ if (!std::filesystem::is_regular_file(full, ec)) {
+ error = "Missing buffer file: " + uri;
+ return false;
+ }
+ const uintmax_t size = std::filesystem::file_size(full, ec);
+ if (ec || size > kMaxBufferBytes - bufferBytes) {
+ error = "Buffers are too large: " + uri;
+ return false;
+ }
+ if (!readFile(full, data)) {
error = "Missing buffer file: " + uri;
return false;
}
}
+ if (data.size() > kMaxBufferBytes - bufferBytes) {
+ error = "Buffers are too large";
+ return false;
+ }
+ bufferBytes += data.size();
r.buffers.push_back(std::move(data));
}
std::vector<GltfObject> objects(1);
+ size_t totalVertices = 0, totalTriangles = 0, totalDeltas = 0;
SplatCloud splats;
auto readSplats = [&](const Json& prim, const glm::mat4& world) -> bool {
const Json& at = prim["attributes"];
const char* prefix = "KHR_gaussian_splatting:";
- auto attr = [&](const std::string& n) { return at[n].isNumber() ? int(at[n].asNumber()) : -1; };
+ auto attr = [&](const std::string& n) { return jsonIndex(at[n]); };
const int pos = attr("POSITION"), rot = attr(std::string(prefix) + "ROTATION"),
scl = attr(std::string(prefix) + "SCALE"), opa = attr(std::string(prefix) + "OPACITY"),
dc = attr(std::string(prefix) + "SH_DEGREE_0_COEF_0");
@@ -692,13 +839,20 @@ bool readGltf(const std::string& path, bool split, std::vector<MeshObject>& out,
return true;
};
+ // glTF nodes form trees, so each node is visited once: shared children or cycles can't multiply the work.
+ std::vector<char> visited(r.doc["nodes"].size(), 0);
std::function<bool(int, const glm::mat4&, int)> visit = [&](int nodeIndex, const glm::mat4& parent, int depth) {
if (depth > 64) return r.fail("Node hierarchy too deep");
+ if (nodeIndex < 0 || size_t(nodeIndex) >= visited.size()) return r.fail("Node index out of range");
+ if (visited[size_t(nodeIndex)]) return true;
+ visited[size_t(nodeIndex)] = 1;
const Json& node = r.doc["nodes"][size_t(nodeIndex)];
const glm::mat4 world = parent * nodeMatrix(node);
const glm::mat3 linear(world);
- if (node["mesh"].isNumber()) {
- const Json& mesh = r.doc["meshes"][size_t(node["mesh"].asNumber())];
+ if (!node["mesh"].isNull()) {
+ const int meshIndex = jsonIndex(node["mesh"]);
+ if (meshIndex < 0 || size_t(meshIndex) >= r.doc["meshes"].size()) return r.fail("Mesh index out of range");
+ const Json& mesh = r.doc["meshes"][size_t(meshIndex)];
// Splitting: every node with a mesh is its own object (its primitives are material slots).
if (split && (objects.size() > 1 || !objects[0].m.triangles.empty() || !objects[0].name.empty()))
objects.emplace_back();
@@ -718,24 +872,28 @@ bool readGltf(const std::string& path, bool split, std::vector<MeshObject>& out,
if (splatsOut && splats.empty() && !readSplats(prim, world)) return false;
continue;
}
- if (prim["mode"].isNumber() && int(prim["mode"].asNumber()) != 4) continue; // triangles only
- if (!prim["attributes"]["POSITION"].isNumber()) continue;
+ if (!prim["mode"].isNull() && jsonEnum(prim["mode"]) != 4) continue; // triangles only
+ if (prim["attributes"]["POSITION"].isNull()) continue;
std::vector<glm::vec3> pos;
- if (!r.readVec3(int(prim["attributes"]["POSITION"].asNumber()), pos)) return false;
+ if (!r.readVec3(jsonIndex(prim["attributes"]["POSITION"]), pos)) return false;
std::vector<uint32_t> idx;
- if (prim["indices"].isNumber()) {
- if (!r.readIndices(int(prim["indices"].asNumber()), idx)) return false;
+ if (!prim["indices"].isNull()) {
+ if (!r.readIndices(jsonIndex(prim["indices"]), idx)) return false;
} else {
idx.resize(pos.size());
for (uint32_t i = 0; i < idx.size(); ++i) idx[i] = i;
}
+ if (pos.size() > kMaxImportVertices - totalVertices || idx.size() / 3 > kMaxImportTriangles - totalTriangles)
+ return r.fail("Model is too large to import");
+ totalVertices += pos.size();
+ totalTriangles += idx.size() / 3;
const uint32_t baseIndex = uint32_t(m.positions.size());
for (const auto& p : pos) m.positions.push_back(glm::vec3(world * glm::vec4(p, 1.0f)));
// Vertex colours (COLOR_0 is linear RGB or RGBA); primitives without them are white.
const Json& colorAcc = prim["attributes"]["COLOR_0"];
- if (colorAcc.isNumber()) {
- const int ci = int(colorAcc.asNumber());
- const int comps = r.doc["accessors"][size_t(ci)]["type"].asString() == "VEC4" ? 4 : 3;
+ if (!colorAcc.isNull()) {
+ const int ci = jsonIndex(colorAcc);
+ const int comps = r.doc["accessors"][size_t(std::max(ci, 0))]["type"].asString() == "VEC4" ? 4 : 3;
std::vector<float> c;
if (!r.readFloats(ci, comps, c)) return false;
m.colors.resize(baseIndex, glm::vec3(1.0f));
@@ -749,8 +907,8 @@ bool readGltf(const std::string& path, bool split, std::vector<MeshObject>& out,
// TEXCOORD_0 (glTF V runs down); Mesh::uvs holds one per corner either way until the end.
std::vector<float> uv;
const Json& uvAcc = prim["attributes"]["TEXCOORD_0"];
- if (uvAcc.isNumber()) {
- if (!r.readFloats(int(uvAcc.asNumber()), 2, uv)) return false;
+ if (!uvAcc.isNull()) {
+ if (!r.readFloats(jsonIndex(uvAcc), 2, uv)) return false;
o.uvs = true;
}
for (size_t t = 0; t + 2 < idx.size(); t += 3) {
@@ -766,19 +924,25 @@ bool readGltf(const std::string& path, bool split, std::vector<MeshObject>& out,
// Morph targets -> sculpt layers (only when every primitive has the same set).
const Json& targets = prim["targets"];
if (targetDeltas.empty() && baseIndex == 0) {
+ if (targets.size() > kMaxMorphTargets) return r.fail("Too many morph targets");
targetDeltas.resize(targets.size());
for (size_t k = 0; k < targets.size(); ++k) {
const Json& names = mesh["extras"]["targetNames"];
targetNames.push_back(names[k].isString() ? names[k].asString() : "Shape " + std::to_string(k + 1));
- targetWeights.push_back(float(mesh["weights"][k].asNumber(0.0)));
+ targetWeights.push_back(toFloat(mesh["weights"][k].asNumber(0.0)));
}
} else if (targets.size() != targetDeltas.size()) {
targetsConsistent = false;
}
+ if (!targetDeltas.empty() &&
+ (pos.size() > kMaxMorphDeltas / targetDeltas.size() ||
+ pos.size() * targetDeltas.size() > kMaxMorphDeltas - totalDeltas))
+ return r.fail("Morph targets are too large to import");
+ totalDeltas += pos.size() * targetDeltas.size();
for (size_t k = 0; k < targetDeltas.size(); ++k) {
std::vector<glm::vec3> d(pos.size(), glm::vec3(0.0f));
- if (k < targets.size() && targets[k]["POSITION"].isNumber() &&
- !r.readVec3(int(targets[k]["POSITION"].asNumber()), d))
+ if (k < targets.size() && !targets[k]["POSITION"].isNull() &&
+ !r.readVec3(jsonIndex(targets[k]["POSITION"]), d))
return false;
d.resize(pos.size(), glm::vec3(0.0f));
for (const auto& v : d) targetDeltas[k].push_back(linear * v);
@@ -786,21 +950,33 @@ bool readGltf(const std::string& path, bool split, std::vector<MeshObject>& out,
}
}
for (const Json& child : node["children"].items())
- if (!visit(int(child.asNumber()), world, depth + 1)) return false;
+ if (!visit(jsonIndex(child), world, depth + 1)) return false;
return true;
};
const Json& scenes = r.doc["scenes"];
if (scenes.size() > 0) {
- const Json& scene = scenes[size_t(r.doc["scene"].asNumber(0))];
+ size_t sceneIndex = 0;
+ if (!optionalWhole(r.doc["scene"], kMaxJsonInteger, 0, sceneIndex) || sceneIndex >= scenes.size()) {
+ error = "Scene index out of range";
+ return false;
+ }
+ const Json& scene = scenes[sceneIndex];
for (const Json& n : scene["nodes"].items())
- if (!visit(int(n.asNumber()), glm::mat4(1.0f), 0)) {
+ if (!visit(jsonIndex(n), glm::mat4(1.0f), 0)) {
error = r.error;
return false;
}
} else {
+ // No scene: every root node (one that is nobody's child), so children keep their parents' transforms.
+ std::vector<char> isChild(r.doc["nodes"].size(), 0);
+ for (const Json& node : r.doc["nodes"].items())
+ for (const Json& child : node["children"].items()) {
+ const int c = jsonIndex(child);
+ if (c >= 0 && size_t(c) < isChild.size()) isChild[size_t(c)] = 1;
+ }
for (size_t i = 0; i < r.doc["nodes"].size(); ++i)
- if (!visit(int(i), glm::mat4(1.0f), 0)) {
+ if (!isChild[i] && !visit(int(i), glm::mat4(1.0f), 0)) {
error = r.error;
return false;
}
diff --git a/tests/test_malformed_files.cpp b/tests/test_malformed_files.cpp
index dcf89d37..a9d9fd96 100644
--- a/tests/test_malformed_files.cpp
+++ b/tests/test_malformed_files.cpp
@@ -7,6 +7,7 @@
#include "core/Mesh.h"
#include "core/Splats.h"
+#include "io/GltfIO.h"
#include "io/ObjIO.h"
#include "io/PlyIO.h"
#include "core/LayerStackIO.h"
@@ -15,7 +16,9 @@
#include "core/Texture.h"
#include "io/Zip.h"
+#include <chrono>
#include <cmath>
+#include <cstring>
#include <filesystem>
#include <fstream>
#include <functional>
@@ -219,3 +222,294 @@ TEST(malformed_material_channels_in_a_project_fail_cleanly) {
CHECK(!err.empty());
std::filesystem::remove(path);
}
+
+// --- glTF / GLB (io/GltfIO.cpp): accessor and buffer sizes from the file are validated before use ---
+
+namespace {
+
+std::string base64(const std::vector<uint8_t>& in) {
+ static const char* chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+ std::string out;
+ size_t i = 0;
+ for (; i + 2 < in.size(); i += 3) {
+ const uint32_t v = uint32_t(in[i]) << 16 | uint32_t(in[i + 1]) << 8 | in[i + 2];
+ for (int s = 18; s >= 0; s -= 6) out += chars[(v >> s) & 63];
+ }
+ if (i < in.size()) {
+ const uint32_t v = uint32_t(in[i]) << 16 | (i + 1 < in.size() ? uint32_t(in[i + 1]) << 8 : 0);
+ out += chars[(v >> 18) & 63];
+ out += chars[(v >> 12) & 63];
+ out += i + 1 < in.size() ? chars[(v >> 6) & 63] : '=';
+ out += '=';
+ }
+ return out;
+}
+
+// One triangle's positions (36 bytes) followed by its uint16 indices (6 bytes, padded to 8).
+std::vector<uint8_t> triangleBytes() {
+ const float p[9] = {0, 0, 0, 1, 0, 0, 0, 1, 0};
+ const uint16_t idx[4] = {0, 1, 2, 0};
+ std::vector<uint8_t> b(44);
+ std::memcpy(b.data(), p, 36);
+ std::memcpy(b.data() + 36, idx, 8);
+ return b;
+}
+
+std::string dataUri(const std::vector<uint8_t>& bytes) { return "data:application/octet-stream;base64," + base64(bytes); }
+
+// A glTF with one buffer (`bytes`, or none when `uri` is false), the given views and accessors, one mesh and node.
+std::string gltfText(const std::string& views, const std::string& accessors, const std::string& prim,
+ const std::vector<uint8_t>& bytes = triangleBytes(), bool uri = true) {
+ return "{\"asset\":{\"version\":\"2.0\"},\"buffers\":[{\"byteLength\":" + std::to_string(bytes.size()) +
+ (uri ? ",\"uri\":\"" + dataUri(bytes) + "\"" : std::string()) + "}],\"bufferViews\":[" + views +
+ "],\"accessors\":[" + accessors + "],\"meshes\":[{\"primitives\":[" + prim +
+ "]}],\"nodes\":[{\"mesh\":0}],\"scenes\":[{\"nodes\":[0]}],\"scene\":0}";
+}
+
+const char* kViews = R"({"buffer":0,"byteOffset":0,"byteLength":36},{"buffer":0,"byteOffset":36,"byteLength":6})";
+const char* kPositions = R"({"bufferView":0,"componentType":5126,"count":3,"type":"VEC3"})";
+const char* kIndices = R"({"bufferView":1,"componentType":5123,"count":3,"type":"SCALAR"})";
+const char* kPrim = R"({"attributes":{"POSITION":0},"indices":1})";
+
+bool gltfBytesLoad(const std::string& bytes, std::string& err, Mesh* mesh = nullptr,
+ const char* name = "sculptforge_malformed.gltf") {
+ const std::string path = writeFile(name, bytes);
+ Mesh m;
+ err.clear();
+ const bool ok = loadGltf(path, m, err);
+ std::filesystem::remove(path);
+ if (mesh) *mesh = std::move(m);
+ return ok;
+}
+
+bool gltfRejected(const std::string& text) {
+ std::string err;
+ const bool ok = gltfBytesLoad(text, err);
+ return !ok && !err.empty();
+}
+
+std::string glb(const std::string& json, const std::vector<uint8_t>& bin) {
+ std::string j = json;
+ while (j.size() % 4) j += ' ';
+ std::string out;
+ auto u32 = [&](uint32_t v) { out.append(reinterpret_cast<const char*>(&v), 4); };
+ u32(0x46546C67);
+ u32(2);
+ u32(uint32_t(12 + 8 + j.size() + 8 + bin.size()));
+ u32(uint32_t(j.size()));
+ u32(0x4E4F534A);
+ out += j;
+ u32(uint32_t(bin.size()));
+ u32(0x004E4942);
+ out.append(reinterpret_cast<const char*>(bin.data()), bin.size());
+ return out;
+}
+
+std::string replaced(std::string text, const std::string& from, const std::string& to) {
+ const size_t at = text.find(from);
+ if (at != std::string::npos) text.replace(at, from.size(), to);
+ return text;
+}
+
+} // namespace
+
+TEST(gltf_well_formed_triangle_still_loads) {
+ std::string err;
+ Mesh m;
+ CHECK(gltfBytesLoad(gltfText(kViews, std::string(kPositions) + "," + kIndices, kPrim), err, &m));
+ CHECK(m.triangleCount() == 1);
+ CHECK(m.positions.size() == 3);
+ // The same file as a GLB with its data in the BIN chunk.
+ const std::string json = gltfText(kViews, std::string(kPositions) + "," + kIndices, kPrim, triangleBytes(), false);
+ CHECK(gltfBytesLoad(glb(json, triangleBytes()), err, &m, "sculptforge_malformed.glb"));
+ CHECK(m.triangleCount() == 1);
+}
+
+TEST(gltf_buffer_view_offset_that_wraps_around_is_rejected) {
+ // byteOffset + byteLength past 2^64 used to wrap to a small number and pass the range check.
+ const std::string acc = std::string(kPositions) + "," + kIndices;
+ CHECK(gltfRejected(gltfText(R"({"buffer":0,"byteOffset":18446744073709551600,"byteLength":36},)"
+ R"({"buffer":0,"byteOffset":36,"byteLength":6})",
+ acc, kPrim)));
+ CHECK(gltfRejected(gltfText(R"({"buffer":0,"byteOffset":9007199254740990,"byteLength":36},)"
+ R"({"buffer":0,"byteOffset":36,"byteLength":6})",
+ acc, kPrim)));
+ // A view longer than its buffer, and an accessor offset past its view.
+ CHECK(gltfRejected(gltfText(R"({"buffer":0,"byteLength":4000},{"buffer":0,"byteOffset":36,"byteLength":6})", acc, kPrim)));
+ CHECK(gltfRejected(gltfText(kViews, R"({"bufferView":0,"byteOffset":40,"componentType":5126,"count":3,"type":"VEC3"},)" +
+ std::string(kIndices),
+ kPrim)));
+}
+
+TEST(gltf_huge_accessor_count_is_rejected_without_allocating) {
+ // 4e12 positions would be a 48 TB allocation before the range check.
+ std::string err;
+ CHECK(!gltfBytesLoad(gltfText(kViews, R"({"bufferView":0,"componentType":5126,"count":4e12,"type":"VEC3"},)" +
+ std::string(kIndices),
+ kPrim),
+ err));
+ CHECK(err.find("out of range") != std::string::npos);
+ CHECK(gltfRejected(gltfText(
+ kViews, std::string(kPositions) + R"(,{"bufferView":1,"componentType":5123,"count":4e12,"type":"SCALAR"})", kPrim)));
+ CHECK(gltfRejected(gltfText(kViews,
+ std::string(kPositions) + "," + kIndices +
+ R"(,{"bufferView":0,"componentType":5126,"count":4e12,"type":"VEC2"})",
+ R"({"attributes":{"POSITION":0,"TEXCOORD_0":2},"indices":1})")));
+}
+
+TEST(gltf_stride_that_wraps_around_is_rejected) {
+ // (count - 1) * stride: 4 * 2^62 wraps to 0 in 64 bits.
+ const std::string views = R"({"buffer":0,"byteLength":36,"byteStride":4611686018427387904},)"
+ R"({"buffer":0,"byteOffset":36,"byteLength":6})";
+ CHECK(gltfRejected(gltfText(views, R"({"bufferView":0,"componentType":5126,"count":5,"type":"VEC3"},)" +
+ std::string(kIndices),
+ kPrim)));
+ // Strides beyond glTF's 252 bytes, smaller than an element, or not whole numbers.
+ for (const char* stride : {"256", "8", "12.5", "-12"})
+ CHECK(gltfRejected(gltfText(std::string(R"({"buffer":0,"byteLength":36,"byteStride":)") + stride +
+ R"(},{"buffer":0,"byteOffset":36,"byteLength":6})",
+ std::string(kPositions) + "," + kIndices, kPrim)));
+ // A valid stride that just doesn't fit: three elements 16 bytes apart need 44 bytes.
+ CHECK(gltfRejected(gltfText(R"({"buffer":0,"byteLength":36,"byteStride":16},{"buffer":0,"byteOffset":36,"byteLength":6})",
+ std::string(kPositions) + "," + kIndices, kPrim)));
+}
+
+TEST(gltf_negative_fractional_and_huge_numbers_are_rejected) {
+ const std::string idx = std::string(",") + kIndices;
+ for (const char* count : {"-1", "2.5", "1e300", "-1e300"})
+ CHECK(gltfRejected(gltfText(kViews,
+ std::string(R"({"bufferView":0,"componentType":5126,"count":)") + count +
+ R"(,"type":"VEC3"})" + idx,
+ kPrim)));
+ for (const char* bv : {"-1", "0.5", "1e30", "2"})
+ CHECK(gltfRejected(gltfText(kViews,
+ std::string(R"({"bufferView":)") + bv +
+ R"(,"componentType":5126,"count":3,"type":"VEC3"})" + idx,
+ kPrim)));
+ for (const char* off : {"-4", "0.5", "1e300"})
+ CHECK(gltfRejected(gltfText(std::string(R"({"buffer":0,"byteOffset":)") + off +
+ R"(,"byteLength":36},{"buffer":0,"byteOffset":36,"byteLength":6})",
+ std::string(kPositions) + idx, kPrim)));
+ for (const char* buf : {"-1", "1e20", "0.25", "1"})
+ CHECK(gltfRejected(gltfText(std::string(R"({"buffer":)") + buf +
+ R"(,"byteLength":36},{"buffer":0,"byteOffset":36,"byteLength":6})",
+ std::string(kPositions) + idx, kPrim)));
+ CHECK(gltfRejected(gltfText(kViews, R"({"bufferView":0,"componentType":1e30,"count":3,"type":"VEC3"})" + idx, kPrim)));
+ for (const char* a : {"-1", "1e20", "0.5", "7"})
+ CHECK(gltfRejected(gltfText(kViews, std::string(kPositions) + idx,
+ std::string(R"({"attributes":{"POSITION":)") + a + R"(},"indices":1})")));
+ CHECK(gltfRejected(gltfText(kViews, std::string(kPositions) + idx, R"({"attributes":{"POSITION":0},"indices":-2})")));
+ CHECK(gltfRejected(
+ gltfText(kViews, std::string(kPositions) + idx, R"({"attributes":{"POSITION":0,"COLOR_0":-1e20},"indices":1})")));
+ CHECK(gltfRejected(
+ gltfText(kViews, std::string(kPositions) + idx, R"({"attributes":{"POSITION":0},"indices":1,"mode":1e30})")));
+ // Scene, node and mesh indices.
+ const std::string base = gltfText(kViews, std::string(kPositions) + idx, kPrim);
+ CHECK(gltfRejected(replaced(base, "\"scene\":0", "\"scene\":-3")));
+ CHECK(gltfRejected(replaced(base, "\"scene\":0", "\"scene\":1e300")));
+ CHECK(gltfRejected(replaced(base, "\"scenes\":[{\"nodes\":[0]}]", "\"scenes\":[{\"nodes\":[-1]}]")));
+ CHECK(gltfRejected(replaced(base, "\"scenes\":[{\"nodes\":[0]}]", "\"scenes\":[{\"nodes\":[1e20]}]")));
+ CHECK(gltfRejected(replaced(base, "{\"mesh\":0}", "{\"mesh\":1.5}")));
+ CHECK(gltfRejected(replaced(base, "{\"mesh\":0}", "{\"mesh\":-1}")));
+ CHECK(gltfRejected(replaced(base, "{\"mesh\":0}", "{\"mesh\":0,\"children\":[1e20]}")));
+ // Out-of-float-range transforms and weights are clamped, not cast blindly.
+ std::string err;
+ CHECK(gltfBytesLoad(replaced(base, "{\"mesh\":0}", "{\"mesh\":0,\"translation\":[1e300,0,0],\"scale\":[1,-1e300,1]}"), err));
+}
+
+TEST(gltf_index_accessor_without_buffer_view_reads_zeros) {
+ // glTF 2.0: no bufferView means all zeros. It used to read buffer view 0 instead (here: float positions, which
+ // as indices are far out of range, so the old reading failed the whole file).
+ const std::string accessors = std::string(kPositions) + R"(,{"componentType":5125,"count":3,"type":"SCALAR"})";
+ const std::string prims = R"({"attributes":{"POSITION":0},"indices":1},{"attributes":{"POSITION":0}})";
+ std::string err;
+ Mesh m;
+ CHECK(gltfBytesLoad(gltfText(kViews, accessors, prims), err, &m));
+ CHECK(m.triangleCount() >= 1); // the second primitive's triangle; the all-zero one is degenerate
+ // Zero-filled accessors are capped, so a tiny file can't ask for terabytes of zeros.
+ CHECK(gltfRejected(gltfText(kViews, std::string(kPositions) + R"(,{"componentType":5125,"count":4e12,"type":"SCALAR"})",
+ R"({"attributes":{"POSITION":0},"indices":1})")));
+ CHECK(gltfRejected(gltfText(kViews, R"({"componentType":5126,"count":4e12,"type":"VEC3"})", R"({"attributes":{"POSITION":0}})")));
+ CHECK(gltfRejected(
+ gltfText(kViews, R"({"componentType":5126,"count":20000000,"type":"VEC3"})", R"({"attributes":{"POSITION":0}})")));
+}
+
+TEST(gltf_long_data_uri_decodes_exactly) {
+ // A 1 MB base64 buffer: the decoder's accumulator used to shift left without bound (signed overflow).
+ std::vector<uint8_t> bytes = triangleBytes();
+ const size_t pad = (size_t(1) << 20) + 1;
+ std::vector<uint8_t> big(pad);
+ for (size_t i = 0; i < pad; ++i) big[i] = uint8_t(i * 131 + 7);
+ bytes.insert(bytes.begin(), big.begin(), big.end());
+ const std::string off = std::to_string(pad), off2 = std::to_string(pad + 36);
+ std::string err;
+ Mesh m;
+ CHECK(gltfBytesLoad(gltfText(R"({"buffer":0,"byteOffset":)" + off + R"(,"byteLength":36},{"buffer":0,"byteOffset":)" +
+ off2 + R"(,"byteLength":6})",
+ std::string(kPositions) + "," + kIndices, kPrim, bytes),
+ err, &m));
+ CHECK(m.triangleCount() == 1);
+ float maxX = 0, maxY = 0;
+ for (const auto& p : m.positions) maxX = std::max(maxX, p.x), maxY = std::max(maxY, p.y);
+ CHECK(maxX == 1.0f && maxY == 1.0f);
+}
+
+TEST(gltf_node_graph_cannot_multiply_work) {
+ // 60 levels of nodes that each list the next one twice: 2^60 visits if shared children were walked again.
+ std::string nodes = "{\"mesh\":0,\"children\":[1,1]}";
+ for (int i = 1; i < 60; ++i)
+ nodes += ",{\"mesh\":0,\"children\":[" + std::to_string(i + 1) + "," + std::to_string(i + 1) + "]}";
+ nodes += ",{\"mesh\":0,\"children\":[0]}"; // and a cycle back to the root
+ std::string text = replaced(gltfText(kViews, std::string(kPositions) + "," + kIndices, kPrim), "\"nodes\":[{\"mesh\":0}]",
+ "\"nodes\":[" + nodes + "]");
+ const auto start = std::chrono::steady_clock::now();
+ std::string err;
+ CHECK(gltfBytesLoad(text, err));
+ CHECK(std::chrono::steady_clock::now() - start < std::chrono::seconds(20));
+ // Without a scene, only root nodes are walked (children once, under their parents); here every node is a child.
+ text = replaced(text, ",\"scenes\":[{\"nodes\":[0]}],\"scene\":0", "");
+ CHECK(gltfRejected(text)); // no roots: nothing to load, reported as an error rather than looping
+}
+
+TEST(gltf_too_many_morph_targets_are_rejected) {
+ std::string targets;
+ for (int i = 0; i < 5000; ++i) targets += std::string(i ? "," : "") + "{}";
+ CHECK(gltfRejected(gltfText(kViews, std::string(kPositions) + "," + kIndices,
+ R"({"attributes":{"POSITION":0},"indices":1,"targets":[)" + targets + "]}")));
+ // A few targets with zero-filled or real deltas still load.
+ std::string err;
+ CHECK(gltfBytesLoad(gltfText(kViews, std::string(kPositions) + "," + kIndices,
+ R"({"attributes":{"POSITION":0},"indices":1,"targets":[{},{"POSITION":0}]})"),
+ err));
+}
+
+TEST(gltf_external_buffer_paths_are_confined) {
+ for (const char* uri : {"../secret.bin", "/etc/passwd", "sub/../../x.bin", "."})
+ CHECK(gltfRejected("{\"asset\":{\"version\":\"2.0\"},\"buffers\":[{\"byteLength\":4,\"uri\":\"" + std::string(uri) +
+ "\"}],\"meshes\":[],\"nodes\":[]}"));
+}
+
+TEST(malformed_glb_containers_are_rejected) {
+ const std::string json = gltfText(kViews, std::string(kPositions) + "," + kIndices, kPrim, triangleBytes(), false);
+ const std::string good = glb(json, triangleBytes());
+ std::string err;
+ CHECK(gltfBytesLoad(good, err, nullptr, "sculptforge_malformed.glb"));
+ auto rejects = [&](const std::string& bytes) {
+ std::string why;
+ return !gltfBytesLoad(bytes, why, nullptr, "sculptforge_malformed.glb") && !why.empty();
+ };
+ auto setU32 = [](std::string s, size_t at, uint32_t v) {
+ std::memcpy(&s[at], &v, 4);
+ return s;
+ };
+ CHECK(rejects(setU32(good, 12, 0xFFFFFFFFu))); // JSON chunk claims 4 GB
+ CHECK(rejects(setU32(good, 12, 0xFFFFFFFDu))); // ... a length that wraps when padded
+ const size_t binHeader = 20 + ((json.size() + 3) & ~size_t(3));
+ CHECK(rejects(setU32(good, binHeader, 0xFFFFFFFFu))); // BIN chunk past the end
+ CHECK(rejects(setU32(good, 8, uint32_t(good.size() + 100)))); // header length past the end
+ CHECK(rejects(setU32(good, 8, 4))); // header length shorter than the header
+ CHECK(rejects(setU32(good, 4, 1))); // glTF 1.0 container
+ CHECK(rejects(good.substr(0, good.size() - 10))); // truncated
+ CHECK(rejects(setU32(good, 16, 0x12345678u))); // no JSON chunk
+ CHECK(rejects(glb(json, std::vector<uint8_t>(20, 0)))); // BIN shorter than the buffer views need
+}