Skip to content

validate aiString length to prevent out-of-bounds read/write#6599

Open
jmestwa-coder wants to merge 3 commits into
assimp:masterfrom
jmestwa-coder:assbin-aistring-length-validation
Open

validate aiString length to prevent out-of-bounds read/write#6599
jmestwa-coder wants to merge 3 commits into
assimp:masterfrom
jmestwa-coder:assbin-aistring-length-validation

Conversation

@jmestwa-coder
Copy link
Copy Markdown

@jmestwa-coder jmestwa-coder commented Apr 15, 2026

Summary

Validate aiString length during Assbin import to prevent out-of-bounds memory access from malformed input.


Problem

aiString::length is read from input and used to fill a fixed-size buffer (AI_MAXLEN) without bounds checking.

This allows malformed .assbin data to trigger out-of-bounds writes and undefined behaviour.


Fix

  • Reject aiString::length >= AI_MAXLEN
  • Validate read size (bytesRead == length)
  • Fail early with DeadlyImportError

Key Points

  • Centralized fix in Read<aiString>() (covers all Assbin string reads)
  • No behavior change for valid files
  • Prevents memory corruption from untrusted input

Test

  • Export valid .assbin
  • Locate node chunk via structure markers (no fixed offsets)
  • Corrupt aiString length
  • Verify import fails with expected error

Summary by CodeRabbit

  • Bug Fixes

    • Improved ASSBIN import validation and error reporting: oversized node name lengths and truncated string data are now reliably detected and rejected, reducing silent failures and improving stability.
  • Tests

    • Added a unit test to confirm ASSBIN imports fail when node name lengths are invalid.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Apr 15, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 8770fa29-4179-48e0-8025-9c0d0f7241e1

📥 Commits

Reviewing files that changed from the base of the PR and between 3534712 and 5c9aa5e.

📒 Files selected for processing (1)
  • code/AssetLib/Assbin/AssbinLoader.cpp
🚧 Files skipped from review as they are similar to previous changes (1)
  • code/AssetLib/Assbin/AssbinLoader.cpp

📝 Walkthrough

Walkthrough

Read now reads the length via Read<ai_uint32>, rejects oversized lengths, verifies the exact number of bytes read for string data and null-terminates. AssbinImporter::InternReadFile wraps opened IOStream in a std::unique_ptr with a deleter that calls IOSystem::Close, removing manual Close calls. A unit test was added that tampers an aiString length in an assbin blob and asserts import failure.

Changes

Assbin loader + test

Layer / File(s) Summary
aiString deserialization & validation
code/AssetLib/Assbin/AssbinLoader.cpp
Read<aiString> reads s.length via Read<ai_uint32>(stream), throws on s.length >= AI_MAXLEN, reads exactly s.length bytes and throws on short read, then null-terminates s.data. Error messages changed to indicate oversized length / unexpected EOF.
IOStream ownership in importer
code/AssetLib/Assbin/AssbinLoader.cpp
AssbinImporter::InternReadFile replaces raw IOStream* with std::unique_ptr<IOStream, ...> using a custom deleter that calls IOSystem::Close, switches stream uses to stream.get(), and removes explicit pIOHandler->Close(...) calls on normal and exceptional paths.
Unit test: oversized aiString rejection
test/unit/utAssbinImportExport.cpp
Added TEST_F(utAssbinImportExport, rejectOversizedNodeNameLengthInAssbin) which exports a scene to an in-memory assbin blob, mutates an AINODE chunk's aiString length to AI_MAXLEN, re-imports and asserts import failure and that the importer error contains the invalid-length message. Also added includes for assbin constants and standard types.

Sequence Diagram(s)

sequenceDiagram
    participant Importer
    participant IOHandler
    participant IOSystem
    participant Stream
    participant Reader
    Importer->>IOHandler: Open(file)
    IOHandler-->>Importer: IOStream*
    Note right of Importer: wrap IOStream* in std::unique_ptr with deleter calling IOSystem::Close
    Importer->>Stream: use stream.get() for seeks/reads
    Importer->>Reader: Read<ai_uint32> (s.length)
    Reader->>Stream: read 4 bytes (length)
    alt s.length >= AI_MAXLEN
        Reader-->>Importer: throw DeadlyImportError("ASSBIN: String length too large, potential buffer overflow attempt")
    else s.length valid
        Reader->>Stream: read s.length bytes into s.data
        alt bytesRead != s.length
            Reader-->>Importer: throw DeadlyImportError("ASSBIN: Unexpected EOF reading string data")
        else
            Reader-->>Importer: null-terminate and continue parsing
        end
    end
    Note left of Importer: unique_ptr deleter calls IOSystem::Close on stream destruction
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • assimp/assimp#6606: Similar changes to aiString deserialization in AssetLib/Assbin/AssbinLoader.cpp (length validation, EOF checks, null-termination).

Suggested labels

Bug, Security Risk

Suggested reviewers

  • kimkulling

Poem

🐰 I munched a length that grew too long,
Found bytes miscounted, something wrong.
I wrapped the stream, I checked each read,
Tossed oversized names where they mislead,
Now files sleep safe — hop, code's strong! 🥕

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main security-focused change: validating aiString length to prevent out-of-bounds memory access, which is the core objective of this PR.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Tip

💬 Introducing Slack Agent: The best way for teams to turn conversations into code.

Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Member

@kimkulling kimkulling left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good. I love the way you are testing the out-of-bounds access while reading an aiString. Thanks for your great work!

@kimkulling
Copy link
Copy Markdown
Member

The sanitizer is not happy. Could you please take a look?

@turol
Copy link
Copy Markdown
Member

turol commented Apr 21, 2026

Needs some RAII here:

IOStream *stream = pIOHandler->Open(pFile, "rb");

This bug is not caused by this PR but merely exposed.

@jmestwa-coder jmestwa-coder force-pushed the assbin-aistring-length-validation branch from 44b9638 to 3534712 Compare April 22, 2026 19:16
@jmestwa-coder
Copy link
Copy Markdown
Author

Thanks for the feedback.

I’ve updated the code to use RAII for IOStream so it is properly closed on all paths, including exceptions. This resolves the sanitizer issue without changing existing logic.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
code/AssetLib/Assbin/AssbinLoader.cpp (1)

728-747: ⚠️ Potential issue | 🟠 Major

Use std::vector for exception-safe buffer management in compressed data decompression.

The current code has a memory leak: ReadBinaryScene(&io, pScene) at line 747 can throw from Read<aiString>() validation, bypassing the cleanup code at lines 749-750. Replace raw pointer allocations with std::vector<unsigned char> for automatic cleanup. Also replace the ai_assert at line 735 with a proper exception throw since read failures are recoverable errors, not programming bugs.

♻️ Proposed RAII fix
 `#include` <assimp/scene.h>
 `#include` <memory>
+#include <vector>
@@
-        unsigned char *compressedData = new unsigned char[compressedSize];
-        size_t len = stream->Read(compressedData, 1, compressedSize);
-        ai_assert(len == compressedSize);
+        std::vector<unsigned char> compressedData(compressedSize);
+        const size_t len = stream->Read(compressedData.data(), 1, compressedSize);
+        if (len != compressedSize) {
+            throw DeadlyImportError("ASSBIN: Unexpected EOF while reading compressed data");
+        }
 
-        unsigned char *uncompressedData = new unsigned char[uncompressedSize];
+        std::vector<unsigned char> uncompressedData(uncompressedSize);
 
-        int res = uncompress(uncompressedData, &uncompressedSize, compressedData, (uLong)len);
+        int res = uncompress(uncompressedData.data(), &uncompressedSize, compressedData.data(), static_cast<uLong>(len));
         if (res != Z_OK) {
-            delete[] uncompressedData;
-            delete[] compressedData;
             throw DeadlyImportError("Zlib decompression failed.");
         }
 
-        MemoryIOStream io(uncompressedData, uncompressedSize);
+        MemoryIOStream io(uncompressedData.data(), uncompressedSize);
 
         ReadBinaryScene(&io, pScene);
-
-        delete[] uncompressedData;
-        delete[] compressedData;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@code/AssetLib/Assbin/AssbinLoader.cpp` around lines 728 - 747, Replace the
raw new[] buffers and ai_assert with exception-safe RAII: allocate compressed
and uncompressed buffers as std::vector<unsigned char> (use
compressedData.data() and uncompressedData.data() when calling stream->Read and
uncompress) so they automatically free on exceptions, and replace the
ai_assert(len == compressedSize) with a proper throw (e.g., throw
DeadlyImportError) when the read returns a different size; keep the rest of the
flow (Read<uint32_t>(stream.get()), MemoryIOStream(io uses
uncompressedData.data(), uncompressedSize), and ReadBinaryScene(&io, pScene))
unchanged so Read<aiString>() exceptions propagate safely without leaking
memory.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@code/AssetLib/Assbin/AssbinLoader.cpp`:
- Around line 728-747: Replace the raw new[] buffers and ai_assert with
exception-safe RAII: allocate compressed and uncompressed buffers as
std::vector<unsigned char> (use compressedData.data() and
uncompressedData.data() when calling stream->Read and uncompress) so they
automatically free on exceptions, and replace the ai_assert(len ==
compressedSize) with a proper throw (e.g., throw DeadlyImportError) when the
read returns a different size; keep the rest of the flow
(Read<uint32_t>(stream.get()), MemoryIOStream(io uses uncompressedData.data(),
uncompressedSize), and ReadBinaryScene(&io, pScene)) unchanged so
Read<aiString>() exceptions propagate safely without leaking memory.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 5f9c5743-26f5-4ff9-89f5-1f050060d142

📥 Commits

Reviewing files that changed from the base of the PR and between 44b9638 and 3534712.

📒 Files selected for processing (2)
  • code/AssetLib/Assbin/AssbinLoader.cpp
  • test/unit/utAssbinImportExport.cpp

@sonarqubecloud
Copy link
Copy Markdown

@jmestwa-coder
Copy link
Copy Markdown
Author

@kimkulling , I resolved the merge conflicts and updated the branch.

@sonarqubecloud
Copy link
Copy Markdown

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants