Skip to content

luzer: fix use-after-free of FuzzedDataProvider input - #109

Open
Juanna470 wants to merge 1 commit into
ligurio:masterfrom
Juanna470:fdp-input-lifetime
Open

Juanna470 wants to merge 1 commit into
ligurio:masterfrom
Juanna470:fdp-input-lifetime

Conversation

@Juanna470

Copy link
Copy Markdown

Repro: luzer.FuzzedDataProvider(string.rep("A", 4096)), the form used in docs/api.md, then any consume call once the collector has run.
Cause: the provider holds a pointer to the Lua string bytes, but the string is anchored only while the constructor runs, so an input with no other reference is collected while the provider is still in use.
Fix: keep the bytes in the userdata, whose lifetime is the provider's.

ASAN, Lua 5.4:

==4142==ERROR: AddressSanitizer: heap-use-after-free on address 0x621000002918
READ of size 1 at 0x621000002918 thread T0
    #0 FuzzedDataProvider::ConsumeRandomLengthString(unsigned long) FuzzedDataProvider.h:165
    #1 luaL_consume_string(lua_State*) fuzzed_data_provider.cc:48
freed by thread T0 here:
    #1 l_alloc lauxlib.c:1029
    #2 luaM_free_ lmem.c:153
    #3 sweeplist lgc.c:835
    #9 luaC_fullgc lgc.c:1735

An explicit collectgarbage() is not needed, the incremental collector gets there on its own. Without a sanitizer the read is silent: the freed buffer is reused and the provider returns the new occupant's bytes instead of the input. The check added to test_unit.lua fails that way on master and passes with the patch.

luaL_fuzzed_data_provider() passes the pointer returned by
luaL_checklstring() straight to FuzzedDataProvider, which reads those
bytes on every consume call for the whole lifetime of the userdata. The
Lua string behind that pointer is anchored only while the constructor
runs: afterwards neither the stack nor the userdata references it, so an
input string with no other reference is collected and every later
consume call reads freed memory.

The form documented in docs/api.md is exactly that case:

    fdp = luzer.FuzzedDataProvider(string.rep("A", 10^9))
    fdp:consume_boolean()

Allocate the input bytes together with the userdata and point the
provider at that copy, so the data lives exactly as long as the provider
does. Anchoring the string instead would need a per-version uservalue
API (lua_setfenv(), lua_setuservalue(), lua_setiuservalue()), while the
copy works on every supported Lua.
@ligurio

ligurio commented Nov 26, 2026

Copy link
Copy Markdown
Owner

Thanks for the patch! I'll review.

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.

2 participants