Skip to content

eBPF-based security platform

upatch: run a decoder only from the payload loaded and within its budget

Daniel Borkmann36d0ddb110c1
diff --git a/Documentation/concepts/background/luajit.rst b/Documentation/concepts/background/luajit.rst
index d32afd3c..5c2110e0 100644
--- a/Documentation/concepts/background/luajit.rst
+++ b/Documentation/concepts/background/luajit.rst
@@ -100,16 +100,22 @@ 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.
+zeroed and scrubbed before release. The empty owner state and allocator
+bookkeeping are outside the limit.
The state opens the standard libraries and then removes these globals:
``io``, ``os``, ``package``, ``require``, ``debug``, ``jit``, ``ffi``,
-``dofile``, ``loadfile``, ``load``, ``loadstring``, ``module`` and
-``collectgarbage``. What remains is the language itself with ``string``,
+``dofile``, ``loadfile``, ``load``, ``loadstring``, ``module``,
+``collectgarbage``, ``newproxy``, ``xpcall`` and ``print``, and the
+pattern functions ``find``, ``match``, ``gmatch`` and ``gsub`` from
+``string``. What remains is the language itself with ``string``,
``table``, ``math``, ``bit``, ``coroutine``, ``pcall`` and the other base
-functions, ``print`` among them.
+functions. LuaJIT runs finalizers with hooks off, and the handler
+``xpcall`` calls for an error the hook raised runs while the hook is
+still active, so either would run code the budget never counts:
+``newproxy`` is the one way to a value with a finalizer that the state
+leaves, and the metatable of the slot values shirudo hands the decoder
+is locked.
shirudo turns off the JIT compiler for the state, so every instruction
runs in the interpreter where the instruction hook sees it. It loads the
@@ -120,7 +126,10 @@ A count hook runs every 10,000 interpreter instructions and draws from a
budget of one million instructions. The budget covers both running the
chunk at the top of the source and the call to the entry point. When the
budget is spent, the hook raises the error ``decoder instruction limit
-exceeded``.
+exceeded`` and from then on runs at every instruction, raising it again:
+``pcall`` or ``coroutine.resume`` catch the error, but the next
+instruction of their caller raises it anew, so the decoder unwinds to
+shirudo.
The entry point receives one table: the upatch and map names, the start
and current time as decimal nanosecond strings, the map's type and sizes,
@@ -153,28 +162,22 @@ the records afterwards, and :doc:`/operate/run/telemetry` sets up the export.
Limits
------
-- The instruction budget is a Lua error like any other. ``pcall``,
- ``xpcall`` and ``coroutine.resume`` catch it. Once the budget is spent,
- the hook raises again every 10,000 instructions, but a loop around
- ``pcall`` catches each error and runs without end.
-- Time spent inside a C function, such as ``string.rep``, a pattern match
- in ``string.find`` or one of the ``shirudo`` helpers, does not count
- against the budget.
-- There is no wall-clock deadline. A decoder that does not finish stalls
- every export after it in the same run, until the systemd unit's start
- timeout stops the service. A command run by hand has no such timeout.
+- Time spent inside a C function, such as ``string.rep``, the sorting
+ of ``table.sort`` or one of the ``shirudo`` helpers, does not count
+ against the budget. Each is bounded by the size of its arguments, which
+ the memory limit bounds in turn.
+- There is no wall-clock deadline. The instruction budget and the memory
+ limit are what bound a decoder.
- The global list is a denylist. Every function of the standard library
- that the list does not name stays available. ``print`` writes to the
- command's standard output, the stream that ``--json`` without a path
- also writes to.
+ that the list does not name stays available.
- A decoder runs inside a process with runtime authority, not in a
separate process. The LuaJIT interpreter is therefore part of the
target's trusted computing base, and a flaw in it that a signed decoder
can reach runs with shirudo's authority.
-- At export, shirudo reads the decoder from the archived artifact again.
- The seal protects that file, but shirudo does not verify its signature
- a second time or compare it with the payload digest of the programs it
- loaded.
+- At export, shirudo reads the decoder from the archived artifact again
+ and compares its bytes with the payload digest on the pin directory,
+ but does not verify its signature a second time: the kernel did at
+ load, and the seal has protected the archive since.
These limits bound a mistake or misbehavior in a decoder that carries a
valid signature. A decoder without one never runs. The threat model
diff --git a/Documentation/security/threat-model.rst b/Documentation/security/threat-model.rst
index 5263db9f..883dc958 100644
--- a/Documentation/security/threat-model.rst
+++ b/Documentation/security/threat-model.rst
@@ -925,6 +925,12 @@ payload digest recorded on the upatch's pin directory, in the xattr
A directive therefore removes the upatch its signer made it for and no
other.
+The Lua decoders that map export runs with runtime authority ride in a
+signed section too. Export reads them from the archived artifact only
+when its bytes hash to the payload digest on the pin directory, so a
+decoder runs only beside the maps of the payload it was signed with. No
+test makes the two differ, which takes runtime authority.
+
.. rst-class:: facts
:Adversary: ADV-B, root on the target without the signing key
diff --git a/Documentation/upatches/write/decoders.rst b/Documentation/upatches/write/decoders.rst
index 9e6a1b6f..6c6b7674 100644
--- a/Documentation/upatches/write/decoders.rst
+++ b/Documentation/upatches/write/decoders.rst
@@ -190,19 +190,25 @@ The decoder runs in a restricted LuaJIT state:
- The JIT compiler is off, so that the instruction count sees every
instruction. One snapshot may take 1,000,000 virtual machine
instructions, loading the chunk included, and 32 MiB of memory, and the
- result may nest 32 levels deep.
- The memory limit also applies to finalizers during state cleanup.
+ result may nest 32 levels deep. ``pcall`` catches the error the limit
+ raises, but from then on every instruction raises it again.
- ``io``, ``os``, ``package``, ``require``, ``debug``, ``jit``, ``ffi``,
- ``dofile``, ``loadfile``, ``load``, ``loadstring``, ``module`` and
- ``collectgarbage`` are removed. The rest of the base library and the
- ``string``, ``table``, ``math`` and ``bit`` libraries remain.
+ ``dofile``, ``loadfile``, ``load``, ``loadstring``, ``module``,
+ ``collectgarbage``, ``newproxy``, ``xpcall`` and ``print`` are
+ removed, and so are the pattern functions ``string.find``,
+ ``string.match``, ``string.gmatch`` and ``string.gsub``, whose
+ backtracking on a recorded string the instruction count never sees.
+ The rest of the base library and the ``string``, ``table``, ``math``
+ and ``bit`` libraries remain.
- shirudo reads the decoder from the archived copy of the upatch,
- ``/var/lib/shirudo/upatches/<name>.upatch``, and opens it as sealed
- state. A decoder that did not arrive inside the signed artifact never
- runs.
+ ``/var/lib/shirudo/upatches/<name>.upatch``, opens it as sealed state
+ and runs it only when its bytes are the payload loaded, as the digest
+ on the pin directory records. A decoder that did not arrive inside the
+ signed artifact of the loaded upatch never runs.
An error raised in the decoder drops that snapshot with a message on
-standard error. It never produces a partial record.
+standard error, its control characters replaced. It never produces a
+partial record.
Build and check it
------------------
diff --git a/Makefile.shirudo b/Makefile.shirudo
index 27e11883..576862e6 100644
--- a/Makefile.shirudo
+++ b/Makefile.shirudo
@@ -978,7 +978,8 @@ testing/helper/test-upatch-rodata: testing/helper/test-upatch-rodata.c \
testing/helper/test-upatch-decode: testing/helper/test-upatch-decode.c \
util/upatch_decode.o util/upatch.o util/malloc.o util/hex.o \
- util/string.o util/seal.o util/io.o util/log.o util/json.o
+ util/string.o util/seal.o util/io.o util/log.o util/json.o \
+ util/crypto_openssl.o
@printf ' CC $@\n'
$(Q)$(CC) $(CFLAGS) -o $@ $^ $(DYNAMIC_LIBS)
@@ -1197,7 +1198,7 @@ testing/fuzz/fuzz-cms: testing/fuzz/fuzz-cms.c $(FUZZ_BASE) util/keys.c \
util/crypto_openssl.c util/io.c $(FUZZ_SEAL)
testing/fuzz/fuzz-decoder: testing/fuzz/fuzz-decoder.c $(FUZZ_BASE) \
util/upatch_decode.c util/upatch.c util/io.c \
- $(FUZZ_SEAL)
+ util/crypto_openssl.c $(FUZZ_SEAL)
testing/fuzz/fuzz-decoder: FUZZ_CFLAGS += $(LUAJIT_CFLAGS) -DHAVE_LUAJIT
testing/fuzz/fuzz-decoder: FUZZ_LIBS += $(LUAJIT_LIBS)
testing/fuzz/fuzz-otel: testing/fuzz/fuzz-otel.c $(FUZZ_BASE) \
diff --git a/testing/unit/upatch_decode.c b/testing/unit/upatch_decode.c
index ccfe8f3a..e68aa07f 100644
--- a/testing/unit/upatch_decode.c
+++ b/testing/unit/upatch_decode.c
@@ -116,30 +116,51 @@ static void decoder_memory_limit_is_enforced(void)
-EINVAL, NULL);
}
-static void decoder_memory_limit_applies_to_finalizers(void)
+static void decoder_protected_loops_hit_the_limit(void)
{
- char output[128] = {};
+ decode("function decode(input) while true do "
+ "pcall(function() while true do end end) end end",
+ -EINVAL, NULL);
+ decode("function decode(input) local co = coroutine.wrap(function() "
+ "while true do pcall(function() while true do end end) "
+ "coroutine.yield() end end) "
+ "while true do pcall(co) end end",
+ -EINVAL, NULL);
+}
+
+static void decoder_cannot_reach_unbudgeted_code(void)
+{
+ decode("function decode(input) return {reach = tostring(newproxy) .. "
+ "tostring(xpcall) .. tostring(print) .. tostring(string.find) .. "
+ "tostring(string.match) .. tostring(string.gmatch) .. "
+ "tostring(string.gsub)} end",
+ 0, "{\"reach\":\"nilnilnilnilnilnilnil\"}");
+ decode("function decode(input) local s = shirudo.page_slots("
+ "{chunks = '1', data_hex = string.rep('00', 64)}, 8) "
+ "return {mt = getmetatable(s[1])} end",
+ 0, "{\"mt\":\"shirudo.slot\"}");
+}
+
+static void decoder_error_is_sanitized(void)
+{
+ char output[256] = {};
int capture, saved;
ssize_t len;
- capture = memfd_create("decoder-finalizer", MFD_CLOEXEC);
+ capture = memfd_create("decoder-error", MFD_CLOEXEC);
ASSERT_TRUE(capture >= 0);
- saved = dup(STDOUT_FILENO);
+ saved = dup(STDERR_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);
+ ASSERT_EQ(dup2(capture, STDERR_FILENO), STDERR_FILENO);
+ decode("function decode(input) error('\\27]0;title\\7', 0) end",
+ -EINVAL, NULL);
+ ASSERT_EQ(dup2(saved, STDERR_FILENO), STDERR_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");
+ ASSERT_TRUE(len > 0);
+ EXPECT_TRUE(strstr(output, "decoder failed: ?]0;title?\n"));
+ EXPECT_FALSE(memchr(output, '\033', len));
EXPECT_EQ(close(capture), 0);
}
@@ -147,7 +168,9 @@ 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_CASE(decoder_protected_loops_hit_the_limit),
+ UNIT_CASE(decoder_cannot_reach_unbudgeted_code),
+ UNIT_CASE(decoder_error_is_sanitized),
{}
};
diff --git a/util/upatch_decode.c b/util/upatch_decode.c
index e4a1300f..2f03abab 100644
--- a/util/upatch_decode.c
+++ b/util/upatch_decode.c
@@ -79,8 +79,10 @@ int upatch_decode_map_file_otel(const char *path,
#include <shirudo/overflow.h>
#include <shirudo/string.h>
+#include "crypto.h"
#include "json.h"
#include "hex.h"
+#include "log.h"
#include "malloc.h"
#include "paths.h"
#include "seal.h"
@@ -842,6 +844,9 @@ static void lua_register_slot(lua_State *L)
lua_pushcfunction(L, lua_slot_cstring);
lua_setfield(L, -2, "cstring");
lua_setfield(L, -2, "__index");
+ /* A __gc a decoder added to it would run with hooks off. */
+ lua_pushliteral(L, LUA_SLOT_MT);
+ lua_setfield(L, -2, "__metatable");
lua_pop(L, 1);
}
@@ -862,12 +867,23 @@ static void lua_install_host_api(lua_State *L)
lua_setglobal(L, "shirudo");
}
+/*
+ * LuaJIT runs a finalizer with hooks off, so newproxy(), which makes a
+ * userdata that takes one, would run code past the budget, and so does
+ * the handler xpcall() calls for the error the budget hook raises, from
+ * inside the hook. A pattern match is one C call the count hook never
+ * interrupts, and backtracks for as long as the subject, a string a map
+ * recorded, makes it.
+ */
static void lua_disable_globals(lua_State *L)
{
static const char *const deny[] = {
"io", "os", "package", "require", "debug", "jit", "ffi",
"dofile", "loadfile", "load", "loadstring", "module",
- "collectgarbage",
+ "collectgarbage", "newproxy", "xpcall", "print",
+ };
+ static const char *const patterns[] = {
+ "find", "match", "gmatch", "gsub",
};
size_t i;
@@ -875,8 +891,18 @@ static void lua_disable_globals(lua_State *L)
lua_pushnil(L);
lua_setglobal(L, deny[i]);
}
+ lua_getglobal(L, "string");
+ for (i = 0; i < ARRAY_SIZE(patterns); i++) {
+ lua_pushnil(L);
+ lua_setfield(L, -2, patterns[i]);
+ }
+ lua_pop(L, 1);
}
+/*
+ * pcall() catches the error, so once the budget is spent every
+ * instruction raises it again: no protected call runs past it.
+ */
static void lua_budget_hook(lua_State *L, lua_Debug *ar)
{
struct lua_budget *budget;
@@ -884,6 +910,7 @@ static void lua_budget_hook(lua_State *L, lua_Debug *ar)
budget = current_lua_budget;
if (!budget || --budget->remaining > 0)
return;
+ lua_sethook(L, lua_budget_hook, LUA_MASKCOUNT, 1);
luaL_error(L, "decoder instruction limit exceeded");
}
@@ -1034,24 +1061,38 @@ static int lua_get_decoder_entrypoint(lua_State *L, const char *entrypoint)
struct lua_decoder_call {
const struct map_view *view;
+ struct json_emit *jo;
+ bool otel;
+ int ret;
};
+/* The result is encoded under the same pcall, as it may run out of memory. */
static int lua_call_decoder(lua_State *L)
{
- const struct lua_decoder_call *call =
- lua_touserdata(L, lua_upvalueindex(1));
+ struct lua_decoder_call *call = lua_touserdata(L, lua_upvalueindex(1));
lua_pushvalue(L, lua_upvalueindex(2));
lua_push_map_input(L, call->view);
lua_call(L, 1, 1);
- return 1;
+ call->ret = call->otel ? lua_otel_emit_value(L, -1, call->jo, 0) :
+ lua_json_emit_value(L, -1, call->jo, 0);
+ return 0;
}
-static const char *lua_error_message(lua_State *L)
+/* The message is the decoder's, and may carry what a map recorded. */
+static void lua_report(lua_State *L, const char *what)
{
- const char *message = lua_tostring(L, -1);
-
- return message ? message : "unknown Lua error";
+ const char *message = "unknown Lua error";
+ char shown[256];
+ ssize_t len;
+
+ if (lua_type(L, -1) == LUA_TSTRING)
+ message = lua_tostring(L, -1);
+ len = strscpy(shown, message, sizeof(shown));
+ if (len < 0)
+ len = sizeof(shown) - 1;
+ text_sanitize(shown, len, false);
+ pr_err("upatch map: %s: %s", what, shown);
}
/*
@@ -1064,8 +1105,11 @@ static int run_lua_decoder(const struct upatch_decoder_view *d,
bool otel, size_t max_bytes,
char **out, size_t *out_len)
{
+ struct json_emit jo = {};
struct lua_decoder_call call = {
.view = v,
+ .jo = &jo,
+ .otel = otel,
};
struct lua_budget budget = {
.remaining = LUA_INSN_LIMIT / LUA_HOOK_COUNT,
@@ -1074,7 +1118,6 @@ static int run_lua_decoder(const struct upatch_decoder_view *d,
.limit = LUA_MEMORY_LIMIT,
};
lua_State *allocator, *L;
- struct json_emit jo = {};
int ret = 0;
allocator = luaL_newstate();
@@ -1102,32 +1145,28 @@ static int run_lua_decoder(const struct upatch_decoder_view *d,
if (luaL_loadbufferx(L, d->source, d->source_len, d->source_name,
"t") ||
lua_pcall(L, 0, 1, 0)) {
- fprintf(stderr, "upatch map: decoder load failed: %s\n",
- lua_error_message(L));
+ lua_report(L, "decoder load failed");
ret = -EINVAL;
goto out_close;
}
ret = lua_get_decoder_entrypoint(L, d->entrypoint);
if (ret) {
- fprintf(stderr, "upatch map: decoder entrypoint '%s' not found\n",
- d->entrypoint);
+ pr_err("upatch map: decoder entrypoint %s not found",
+ d->entrypoint);
goto out_close;
}
lua_pushlightuserdata(L, &call);
lua_pushvalue(L, -2);
lua_pushcclosure(L, lua_call_decoder, 2);
lua_remove(L, -2);
- if (lua_pcall(L, 0, 1, 0)) {
- fprintf(stderr, "upatch map: decoder failed: %s\n",
- lua_error_message(L));
+ if (lua_pcall(L, 0, 0, 0)) {
+ lua_report(L, "decoder failed");
ret = -EINVAL;
goto out_close;
}
- ret = otel ? lua_otel_emit_value(L, -1, &jo, 0) :
- lua_json_emit_value(L, -1, &jo, 0);
+ ret = call.ret;
if (ret) {
- fprintf(stderr, "upatch map: decoder encode failed: %s\n",
- strerror(-ret));
+ pr_err("upatch map: decoder encode failed: %s", strerror(-ret));
goto out_close;
}
if (jo.err) {
@@ -1164,15 +1203,35 @@ static int decoder_matches(const struct upatch_decoder_view *d,
return 1;
}
+static int payload_digest(const struct upatch *u,
+ __u8 out[UPATCH_PAYLOAD_HASH_LEN])
+{
+ struct sha256_ctx ctx;
+ int ret;
+
+ ret = sha256_init(&ctx);
+ if (ret)
+ return ret;
+ ret = sha256_update(&ctx, upatch_loader(u), u->hdr.loader_insns_len);
+ if (!ret)
+ ret = sha256_update(&ctx, upatch_data(u), u->hdr.data_len);
+ if (!ret)
+ ret = sha256_final(&ctx, out);
+ sha256_free(&ctx);
+ return ret;
+}
+
/*
* The archived artifact the decoders come from, opened as sealed state
* when archived: an entry under the archive that is not shirudo's own,
* brought in while the directory's mark was gone, is refused rather
- * than run, signed or not.
+ * than run, signed or not, and so is an archive whose bytes are not the
+ * payload the pin directory says was loaded.
*/
static int archive_open(const char *path, bool archived,
- struct upatch *u)
+ const struct map_view *v, struct upatch *u)
{
+ __u8 digest[UPATCH_PAYLOAD_HASH_LEN];
int fd, ret;
if (!archived)
@@ -1182,6 +1241,19 @@ static int archive_open(const char *path, bool archived,
return fd;
ret = upatch_open_fd(fd, u);
close(fd);
+ if (ret)
+ return ret;
+ ret = payload_digest(u, digest);
+ if (!ret && (!v->has_payload ||
+ memneq_explicit(digest, v->payload, sizeof(digest)) ||
+ memneq_explicit(u->hdr.payload_sha256, v->payload,
+ sizeof(digest)))) {
+ pr_err("upatch map: the archive of %s is not the upatch loaded; its decoders do not run",
+ v->upatch);
+ ret = -ESTALE;
+ }
+ if (ret)
+ upatch_close(u);
return ret;
}
@@ -1200,7 +1272,7 @@ static int decode_map_open(const char *path, bool archived,
*out_len = 0;
if (!upatch_name_valid(v->upatch))
return -EINVAL;
- ret = archive_open(path, archived, &u);
+ ret = archive_open(path, archived, v, &u);
if (ret)
return ret == -ENOENT ? -ENOENT : ret;
ret = -ENODATA;
@@ -1238,7 +1310,7 @@ int upatch_decode_map_signal(const struct map_view *v,
if (strsprintf(path, sizeof(path), "%s/%s.upatch", UPATCHES_DIR,
v->upatch) < 0)
return -ENAMETOOLONG;
- ret = archive_open(path, true, &u);
+ ret = archive_open(path, true, v, &u);
if (ret)
return ret == -ENOENT ? -ENOENT : ret;
ret = -ENODATA;
diff --git a/util/upatch_maps.c b/util/upatch_maps.c
index 02d8b23e..271b9668 100644
--- a/util/upatch_maps.c
+++ b/util/upatch_maps.c
@@ -34,6 +34,7 @@
#include "serializer.h"
#include "upatch_map_types.h"
#include "upatch_maps.h"
+#include "upatch_pins.h"
#include "upatch_resolve.h"
#include "bpf/lib/serializer.h"
@@ -1257,6 +1258,7 @@ int upatch_maps_read(const char *upatch, const char *map,
out->lifetime_start_ns =
(__u64)upatch_st.st_ctim.tv_sec * 1000000000ULL +
(__u64)upatch_st.st_ctim.tv_nsec;
+ out->has_payload = !upatch_pin_payload(upatch, out->payload);
ret = try_read_serialized(upatch, map, flags, out);
if (ret < 0) {
diff --git a/util/upatch_maps.h b/util/upatch_maps.h
index fb4c771e..182cb4a8 100644
--- a/util/upatch_maps.h
+++ b/util/upatch_maps.h
@@ -64,6 +64,8 @@ struct map_view {
__u32 n_entries; /* live entries iterated */
__u32 n_cpus; /* 1 for non-percpu types */
__u64 lifetime_start_ns; /* pin-dir ctime; metric reset boundary */
+ bool has_payload; /* the pin directory's payload digest */
+ __u8 payload[UPATCH_PAYLOAD_HASH_LEN];
bool truncated;
__u32 n_truncated_at;
bool serialized;