Skip to content

fix: use-after-realloc in addManyNumbers (#517)#522

Open
BAder82t wants to merge 1 commit into
homenc:masterfrom
BAder82t:fix/bgv-keygen-heap-overflow-517
Open

fix: use-after-realloc in addManyNumbers (#517)#522
BAder82t wants to merge 1 commit into
homenc:masterfrom
BAder82t:fix/bgv-keygen-heap-overflow-517

Conversation

@BAder82t
Copy link
Copy Markdown

Summary

Fixes heap-buffer-overflow reported in #517.

In addManyNumbers (src/binaryArith.cpp), ct_ptr = numbers.ptr2nonNull() is captured before the 3-for-2 while-loop. Inside the loop, three4Two() calls NTL::Vec<Ctxt>::SetLength on the row ct_ptr points into. When the Vec grows past capacity, storage is reallocated and ct_ptr is left dangling. The next iteration reads freed memory on ct_ptr->getContext().BPL() (Ctxt.h:1374), which AddressSanitizer catches as a heap-buffer-overflow READ of size 8.

Fix

Cache 3 * BPL() before the loop (the Context object is stable, so BPL is constant for the duration) and null out ct_ptr so it cannot be dereferenced after that point. bootstrappable and ea were already captured as a value / stable reference and are unaffected.

Reproduction

Parameters from #517 (m=4095, mvec={7,5,9,13}, gens={2341,3277,911}, ords={6,4,6}, p=2, bits=500, c=2) plus a 16-bit multTwoNumbers, built with -fsanitize=address -fno-omit-frame-pointer -g:

  • Before: ASan heap-buffer-overflow READ of size 8 at Ctxt.h:1374 (Ctxt::getContext()), called from addManyNumbers (binaryArith.cpp:927) <- multTwoNumbers (binaryArith.cpp:1121).
  • After: clean ASan run, multTwoNumbers completes successfully.

Closes

#517

ct_ptr is captured before the loop, but three4Two() can resize the
NTL::Vec<Ctxt> it points into, invalidating the pointer. Later
iterations then read freed memory on ct_ptr->getContext().BPL().

Cache the threshold (3 * BPL()) before the loop and drop ct_ptr.

Closes homenc#517
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