Skip to content

fix: reject invalid n_dims in tensor header to prevent stack-buffer-overflow - #57

Open
shafiuzzaman-md wants to merge 1 commit into
PABannier:mainfrom
shafiuzzaman-md:patch-1
Open

fix: reject invalid n_dims in tensor header to prevent stack-buffer-overflow#57
shafiuzzaman-md wants to merge 1 commit into
PABannier:mainfrom
shafiuzzaman-md:patch-1

Conversation

@shafiuzzaman-md

Copy link
Copy Markdown

Problem

encodec_load_model_weights() (encodec.cpp:447) reads a tensor header's n_dims field as a raw int32_t directly from the model file and uses it, unbounded, as the loop count writing into a fixed-size 3-element stack array int32_t ne[3] = {1, 1, 1}:

int32_t nelements = 1;
int32_t ne[3] = {1, 1, 1};
for (int i = 0; i < n_dims; i++) {
    read_safe(infile, ne[i]);   // n_dims is fully attacker-controlled, no upper bound
    nelements *= ne[i];
}

A model file with n_dims > 3 writes past the ne[3] array on the stack. Reproduced with a crafted 132-byte model file (n_dims = 20) through the real public encodec_load_model() API, under an AddressSanitizer build:

==...==ERROR: AddressSanitizer: stack-buffer-overflow
WRITE of size 4 at ... thread T0
    #0 memcpy
    #1 read_safe<int>                       utils.h:12
    #2 encodec_load_model_weights           encodec.cpp:447
    #3 encodec_load_model                   encodec.cpp:949
    #4 main

Fix

Add an explicit n_dims range check immediately after it is read, before the loop that populates ne[]:

if (n_dims < 1 || n_dims > 3) {
    fprintf(stderr, "%s: invalid n_dims %d in model file (expected 1 <= n_dims <= 3)\n", __func__, n_dims);
    return false;
}

For normal, well-formed model files this is a no-op; a malformed file is now rejected with a clear error message instead of corrupting the stack.

Testing

  • Before: the crafted model file (n_dims=20) crashes with an ASan stack-buffer-overflow WRITE at encodec_load_model_weights (encodec.cpp:447).
  • After: the same file is rejected cleanly ("invalid n_dims 20 in model file"), no crash.
  • Regression check: a file with a valid n_dims (3) passes the new check unaffected (fails later
    only because the synthetic test file has no real tensor data, unrelated to this fix).
  • Both the library and a standalone harness calling only the public encodec_load_model() API
    build and run cleanly with the change.

Add validation for n_dims to ensure it is between 1 and 3.
@shafiuzzaman-md shafiuzzaman-md changed the title fix-load-model-weights-ndims-bounds fix: reject invalid n_dims in tensor header to prevent stack-buffer-overflow Aug 17, 2026
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.

1 participant