eBPF-based security platform
decode: enforce decoder memory limits during cleanup
Andrea Lattuada8d57ada14f7c
diff --git a/Documentation/concepts/background/luajit.rst b/Documentation/concepts/background/luajit.rstindex b560abe1..d32afd3c 100644--- a/Documentation/concepts/background/luajit.rst+++ b/Documentation/concepts/background/luajit.rst@@ -96,6 +96,14 @@ than 32 MiB in total. The limit covers everything the state allocates,the input table included, and a decoder that reaches it fails with amemory error.+The allocator function uses LuaJIT's allocator for addresses its garbage+collector can represent, including on arm64 where the libc heap can sit+above its 47-bit limit. A separate empty state owns the allocator arena+and releases it after the decoder state closes. Decoder allocations are+zeroed and scrubbed before release. The memory limit also covers finalizers+run at close. The empty owner state and allocator bookkeeping are outside+that limit.+The state opens the standard libraries and then removes these globals:``io``, ``os``, ``package``, ``require``, ``debug``, ``jit``, ``ffi``,``dofile``, ``loadfile``, ``load``, ``loadstring``, ``module`` anddiff --git a/Documentation/contribute/testing/test-coverage.rst b/Documentation/contribute/testing/test-coverage.rstindex 6e557053..51278191 100644--- a/Documentation/contribute/testing/test-coverage.rst+++ b/Documentation/contribute/testing/test-coverage.rst@@ -491,10 +491,11 @@ signed config image.Unit suites and fuzz targets~~~~~~~~~~~~~~~~~~~~~~~~~~~~-The unit suites in :src:`testing/unit/` cover eight of the modules in+The unit suites in :src:`testing/unit/` cover nine of the modules in:src:`util/`: ``chain``, ``hex``, ``json``, ``kernel_abi``,-``kernel_build_id``, ``kernel_release``, ``string`` and ``upatch``, and-``overflow`` the arithmetic of :src:`include/shirudo/overflow.h`. The+``kernel_build_id``, ``kernel_release``, ``string``, ``upatch`` and+``upatch_decode``, and ``overflow`` the arithmetic of+:src:`include/shirudo/overflow.h`. Theother modules are reached through the test helpers, the fuzz targets andthe binaries the functional tests run.diff --git a/Documentation/operate/plan/system-requirements.rst b/Documentation/operate/plan/system-requirements.rstindex 3576b05f..a87628b4 100644--- a/Documentation/operate/plan/system-requirements.rst+++ b/Documentation/operate/plan/system-requirements.rst@@ -427,9 +427,10 @@ keyrings. Any Linux kernel on which the tools below run serves.- ML-DSA-87 signing and hybrid ML-KEM TLS. The build refuses olderversions.* - ``libcurl`` 7.75 or newer, ``tss2-esys`` 4.0 or newer,- ``tss2-tctildr``, ``libelf``, ``zlib``, LuaJIT+ ``tss2-tctildr``, ``libelf``, ``zlib``, LuaJIT with GC64- Linked by the ``shirudo`` binary, which is the same program on- both roles.+ both roles. LuaJIT GC64 is required on the supported 64-bit+ architectures.* - ``clang`` and LLVM 23 with the BPF target- ``shirudo build`` runs ``/usr/bin/clang``, and the helper of theDebian package ``/usr/lib/llvm-23/bin/clang``. It does not search@@ -482,7 +483,7 @@ target-deps`` first.* - autoconf, automake, libtool and autoconf-archive- tpm2-tss's ``bootstrap`` script.* - Static ``libelf.a``, ``libz.a``, ``libzstd.a`` and- ``libluajit-5.1.a``+ ``libluajit-5.1.a`` with GC64- Taken from the first of ``/usr/lib/<multiarch>``, ``/usr/lib64``and ``/usr/lib`` that holds ``libelf.a``.``TARGET_SYSTEM_LIBDIR=`` names another directory.diff --git a/Documentation/upatches/write/decoders.rst b/Documentation/upatches/write/decoders.rstindex 454f3e20..379de59b 100644--- a/Documentation/upatches/write/decoders.rst+++ b/Documentation/upatches/write/decoders.rst@@ -191,6 +191,7 @@ The decoder runs in a restricted LuaJIT state:instruction. One snapshot may take 1,000,000 virtual machineinstructions, loading the chunk included, and 32 MiB of memory, and theresult may nest 32 levels deep.+ The memory limit also applies to finalizers during state cleanup.- ``io``, ``os``, ``package``, ``require``, ``debug``, ``jit``, ``ffi``,``dofile``, ``loadfile``, ``load``, ``loadstring``, ``module`` and``collectgarbage`` are removed. The rest of the base library and thediff --git a/testing/unit/upatch_decode.c b/testing/unit/upatch_decode.cnew file mode 100644index 00000000..ccfe8f3a--- /dev/null+++ b/testing/unit/upatch_decode.c@@ -0,0 +1,154 @@+// SPDX-License-Identifier: BSD-2-Clause+/* Copyright (c) 2026 Authors of shirudo */++#include <errno.h>+#include <stddef.h>+#include <stdio.h>+#include <stdlib.h>+#include <unistd.h>+#include <sys/mman.h>++#include <linux/bpf.h>++#include <shirudo/string.h>+#include <shirudo/upatch.h>++#include "upatch_decode.h"+#include "upatch_maps.h"+#include "malloc.h"+#include "unit.h"+#include "io.h"++struct decoder_fixture {+ struct upatch_header header;+ struct bpf_insn loader;+ __u8 signature[8];+ __u8 blob[sizeof(struct upatch_decoder_blob)];+ struct upatch_decoder_entry decoder;+ char source[256];+ struct upatch_signed_section section;+ struct upatch_signed_trailer trailer;+};++static void decode(const char *source, int expected, const char *json)+{+ const size_t data_off = offsetof(struct decoder_fixture, blob);+ char path[] = "/tmp/shirudo-unit-decoder-XXXXXX";+ struct upatch_decoder_blob blob = {};+ size_t source_len = strlen(source);+ struct decoder_fixture f = {};+ struct map_view view = {+ .upatch = "unit-decoder",+ .name = "records",+ .serialized = true,+ .max_entries = 1,+ .type_name = "array",+ };+ size_t out_len = 0;+ char *out = NULL;+ int fd, ret;++ f.header.magic = cpu_to_le64(UPATCH_MAGIC);+ f.header.version = cpu_to_le32(UPATCH_VERSION);+ f.header.type = cpu_to_le32(UPATCH_TYPE_BPF);+ ASSERT_TRUE(strscpy(f.header.name, view.upatch,+ sizeof(f.header.name)) >= 0);+ f.header.loader_insns_off = cpu_to_le32(offsetof(struct decoder_fixture, loader));+ f.header.loader_insns_len = cpu_to_le32(sizeof(f.loader));+ f.header.signature_off = cpu_to_le32(offsetof(struct decoder_fixture, signature));+ f.header.signature_len = cpu_to_le32(sizeof(f.signature));+ f.header.data_off = cpu_to_le32(data_off);+ f.header.data_len = cpu_to_le32(sizeof(f) - data_off);+ f.loader.code = BPF_JMP | BPF_EXIT;+ blob.magic = cpu_to_le32(UPATCH_DECODER_MAGIC);+ blob.version = cpu_to_le32(UPATCH_DECODER_VERSION);+ blob.nr_decoders = cpu_to_le32(1);+ memcpy(f.blob, &blob, sizeof(blob));+ f.decoder.language = cpu_to_le32(UPATCH_DECODER_LANG_LUA);+ f.decoder.api_version = cpu_to_le32(1);+ f.decoder.input_format = cpu_to_le32(UPATCH_DECODER_INPUT_MAP_V1);+ f.decoder.export_signal = cpu_to_le32(UPATCH_DECODER_EXPORT_LOG);+ ASSERT_TRUE(strscpy(f.decoder.upatch, view.upatch,+ sizeof(f.decoder.upatch)) >= 0);+ ASSERT_TRUE(strscpy(f.decoder.map, view.name, sizeof(f.decoder.map)) >= 0);+ ASSERT_TRUE(strscpy(f.decoder.source, "unit.lua", sizeof(f.decoder.source)) >= 0);+ ASSERT_TRUE(strscpy(f.decoder.entrypoint, "decode",+ sizeof(f.decoder.entrypoint)) >= 0);+ ASSERT_TRUE(strscpy(f.source, source, sizeof(f.source)) >= 0);+ f.decoder.source_off = cpu_to_le32(offsetof(struct decoder_fixture, source) - data_off);+ f.decoder.source_len = cpu_to_le32(source_len);+ f.section.tag = cpu_to_le32(UPATCH_SECTION_DECODERS);+ f.section.len = cpu_to_le32(sizeof(f.blob) + sizeof(f.decoder) + source_len);+ f.trailer.magic = cpu_to_le32(UPATCH_SIGNED_TRAILER_MAGIC);+ f.trailer.version = cpu_to_le32(UPATCH_SIGNED_VERSION);+ f.trailer.dir_off = cpu_to_le32(offsetof(struct decoder_fixture, section) - data_off);+ f.trailer.nr_sections = cpu_to_le32(1);+ fd = mkstemp(path);+ ASSERT_TRUE(fd >= 0);+ ASSERT_EQ(write_complete(fd, &f, sizeof(f)), 0);+ ASSERT_EQ(close(fd), 0);+ ret = upatch_decode_map_file_json(path, &view, &out, &out_len);+ EXPECT_EQ(unlink(path), 0);+ EXPECT_EQ(ret, expected);+ if (!ret) {+ EXPECT_STREQ(out, json);+ } else {+ EXPECT_FALSE(out);+ EXPECT_UEQ(out_len, 0);+ }+ xfree(out, out_len + 1);+}++static void decoder_initializes_and_returns_json(void)+{+ decode("function decode(input) return {value = 42} end",+ 0, "{\"value\":42}");+}++static void decoder_instruction_limit_is_enforced(void)+{+ decode("function decode(input) while true do end end", -EINVAL, NULL);+}++static void decoder_memory_limit_is_enforced(void)+{+ decode("function decode(input) return string.rep('x', 64 * 1024 * 1024) end",+ -EINVAL, NULL);+}++static void decoder_memory_limit_applies_to_finalizers(void)+{+ char output[128] = {};+ int capture, saved;+ ssize_t len;++ capture = memfd_create("decoder-finalizer", MFD_CLOEXEC);+ ASSERT_TRUE(capture >= 0);+ saved = dup(STDOUT_FILENO);+ ASSERT_TRUE(saved >= 0);+ ASSERT_EQ(fflush(stdout), 0);+ ASSERT_EQ(dup2(capture, STDOUT_FILENO), STDOUT_FILENO);+ decode("proxy = newproxy(true) "+ "getmetatable(proxy).__gc = function() "+ "local ok, s = pcall(string.rep, 'x', 64 * 1024 * 1024) "+ "print(ok, ok and #s or s) end "+ "function decode(input) return {value = 42} end", 0, "{\"value\":42}");+ ASSERT_EQ(fflush(stdout), 0);+ ASSERT_EQ(dup2(saved, STDOUT_FILENO), STDOUT_FILENO);+ EXPECT_EQ(close(saved), 0);+ ASSERT_EQ(lseek(capture, 0, SEEK_SET), 0);+ len = read(capture, output, sizeof(output) - 1);+ ASSERT_TRUE(len >= 0);+ EXPECT_STREQ(output, "false\tnot enough memory\n");+ EXPECT_EQ(close(capture), 0);+}++static const struct unit_case cases[] = {+ UNIT_CASE(decoder_initializes_and_returns_json),+ UNIT_CASE(decoder_instruction_limit_is_enforced),+ UNIT_CASE(decoder_memory_limit_is_enforced),+ UNIT_CASE(decoder_memory_limit_applies_to_finalizers),+ {}+};++UNIT_SUITE(upatch_decode, cases);diff --git a/util/upatch_decode.c b/util/upatch_decode.cindex 2baca0fe..7059d862 100644--- a/util/upatch_decode.c+++ b/util/upatch_decode.c@@ -159,6 +159,7 @@ static void *lua_limited_alloc(void *ud, void *ptr, size_t old_size,next = memory->inner(memory->inner_ud, NULL, 0, new_size);if (!next)return NULL;+ memset(next, 0, new_size);if (ptr) {memcpy(next, ptr, min(old_size, new_size));memzero_explicit(ptr, old_size);@@ -168,16 +169,6 @@ static void *lua_limited_alloc(void *ud, void *ptr, size_t old_size,return next;}-/*- * lua_close() releases LuaJIT's arenas only while its own allocator is- * the state's, so hand it back first.- */-static void lua_close_limited(lua_State *L, struct lua_memory *memory)-{- lua_setallocf(L, memory->inner, memory->inner_ud);- lua_close(L);-}-static int json_out_reserve(struct json_out *out, size_t need){char *buf;@@ -1211,37 +1202,45 @@ static const char *lua_error_message(lua_State *L)return message ? message : "unknown Lua error";}+/*+ * Restoring the native allocator before close would let finalizers bypass+ * the memory limit and skip scrubbing. A separate state owns the arena so+ * the decoder keeps its wrapper until close has freed all its objects.+ */static int run_lua_decoder(const struct upatch_decoder_view *d,const struct map_view *v,bool otel, size_t max_bytes,char **out, size_t *out_len){+ struct lua_decoder_call call = {+ .view = v,+ };struct lua_budget budget = {.remaining = LUA_INSN_LIMIT / LUA_HOOK_COUNT,};struct lua_memory memory = {.limit = LUA_MEMORY_LIMIT,};- struct lua_decoder_call call = {- .view = v,- };+ lua_State *allocator, *L;struct json_out jo = {};- lua_State *L;int ret = 0;- L = luaL_newstate();- if (!L)+ allocator = luaL_newstate();+ if (!allocator)+ return -ENOMEM;+ memory.inner = lua_getallocf(allocator, &memory.inner_ud);+ L = lua_newstate(lua_limited_alloc, &memory);+ if (!L) {+ lua_close(allocator);return -ENOMEM;- memory.inner = lua_getallocf(L, &memory.inner_ud);- memory.used = (size_t)lua_gc(L, LUA_GCCOUNT, 0) * 1024 +- (size_t)lua_gc(L, LUA_GCCOUNTB, 0);- lua_setallocf(L, lua_limited_alloc, &memory);+ }jo.max_bytes = max_bytes;luaL_openlibs(L);lua_disable_globals(L);/* Instruction hooks must observe every instruction; do not run traces. */if (!luaJIT_setmode(L, 0, LUAJIT_MODE_ENGINE | LUAJIT_MODE_OFF)) {- lua_close_limited(L, &memory);+ lua_close(L);+ lua_close(allocator);return -EINVAL;}lua_install_host_api(L);@@ -1293,7 +1292,8 @@ out_close:xfree(jo.buf, jo.cap);lua_sethook(L, NULL, 0, 0);current_lua_budget = NULL;- lua_close_limited(L, &memory);+ lua_close(L);+ lua_close(allocator);return ret;}