eBPF-based security platform
upatch: sign the name, the attach metadata and the unload target
Daniel Borkmann79fc2ef4beed
diff --git a/Documentation/architecture.rst b/Documentation/architecture.rstindex 4c61fe51..aafd8b3f 100644--- a/Documentation/architecture.rst+++ b/Documentation/architecture.rst@@ -151,8 +151,10 @@ Build. ``shirudo build fix.bpf.c -o fix.upatch`` compiles the sourcewith ``clang -target bpf -O2 -g``, opens the object with libbpf, calls``bpf_object__gen_loader()`` with ``gen_hash`` set and``bpf_object__load()`` to produce the loader instructions and data,-CMS-signs ``loader_insns || data``, and writes the ``.upatch``-container with the name, the payload SHA-256 and the attach metadata.+appends the name, the attach metadata and the decoders to the data as+signed sections, CMS-signs ``loader_insns || data``, and writes the+``.upatch`` container with the name and the payload SHA-256 in its+header.A pre-compiled ``.bpf.o`` is accepted as input too. ``shirudo build --unload<name>`` emits an unload directive instead: the same container withflag bit 0 set, carrying the compiled ``bpf/unload.c`` template@@ -201,8 +203,10 @@ the persisted ``.upatch``: a process stopped between the two leaves aregister that says more than happened, never a detach it does notknow. A missing pin is ``already_unloaded`` and extends nothing. The kernel's``bpf_sys_bpf()`` allowlist has no detach or unlink command, which is-why the detach is not inside the signed BPF; what that costs the trust-model is residual risk 1 in the threat model.+why the detach is not inside the signed BPF; the target name and the+expected payload are signed sections of the directive, so what that+costs the trust model is the moment of the detach alone, residual risk+1 in the threat model.Attach kinds. The attach metadata selects a raw tracepoint attach(``tp_btf``, ``fentry``/``fexit``, ``lsm``), kprobe and kretprobe,diff --git a/Documentation/threat-model.rst b/Documentation/threat-model.rstindex c1d35ab7..9398c43d 100644--- a/Documentation/threat-model.rst+++ b/Documentation/threat-model.rst@@ -180,12 +180,18 @@ T3 Tampering with shirudo's files and processT4 Substituting artifactsThe signature covers the loader instructions and data, so the kernel- refuses a modified loader. An unload directive is itself a signed+ refuses a modified loader. The name an artifact loads under, the+ sites its programs attach at and the target an unload directive+ names and the payload it expects there ride in signed sections of+ the data, so the kernel refuses an edited one and the target+ refuses a header that disagrees with them; a load takes its attach+ sites from nowhere else. An unload directive is itself a signedloader and goes through the same ``BPF_PROG_LOAD``. Beforedetaching, shirudo compares the live pin's payload xattr, which only- shirudo can write, against the directive's expected payload, and- refuses ``payload_mismatch`` on disagreement or when the xattr is- unreadable.+ shirudo can write, against the directive's signed expected payload,+ and refuses ``payload_mismatch`` on disagreement or when the xattr+ is unreadable, so a directive detaches the upatch its signer made+ it for and no other.T5 Silent state changeEvery init, load, unload and tree operation extends this boot's@@ -355,13 +361,13 @@ T12 Interrupted image activationEach of these is known, documented and bounded; none is silent.-1. The unload directive's target name and expected payload live in- unsigned metadata. The kernel's ``bpf_sys_bpf()`` cannot detach or- unlink, so the detach runs in userspace, and root can repoint a- signed directive at another upatch loaded under the same key, or- edit the expected payload to match it. ``payload_mismatch`` catches- honest substitution; closing this fully needs an in-kernel detach so- the compare runs against signed ``.rodata``.+1. The detach runs in userspace: the kernel's ``bpf_sys_bpf()`` cannot+ detach or unlink. The directive's target name and expected payload+ are signed, so root cannot repoint a directive at another upatch;+ what root keeps is the moment, since every directive the operator+ published, in a package beside its load, is root's to apply at any+ time, and the register records each application. An in-kernel+ detach would make the whole lifecycle signed BPF.2. ``CAP_SYS_RESOURCE`` can rewrite ``mm->exe_file``. The task mark isindependent of that field, and ``task_prctl`` denies those operations to@@ -496,8 +502,8 @@ values of each boot and systemd-aware verifiers find it in PCR 9 beforethe separator, and measuring the anchor through ``systemd-pcrextend`` sosystemd's measurement log explains it (residual risk 11); signed PCRpolicies for the kernel and initrd PCRs so a verifier needs no golden-values; an in-kernel detach so the unload compare runs against-signed ``.rodata`` (residual risk 1); and refusing creation, rename+values; an in-kernel detach so the pin removal is signed BPF rather+than userspace (residual risk 1); and refusing creation, renameand link into a labelled directory from any process but shirudo, whichwould keep foreign entries out of the tree altogether, and a``d_instantiate`` hook the BPF LSM can sleep in, which would mark adiff --git a/Documentation/upatch-spec.rst b/Documentation/upatch-spec.rstindex 29e448fc..cfaa7249 100644--- a/Documentation/upatch-spec.rst+++ b/Documentation/upatch-spec.rst@@ -47,16 +47,18 @@ Artifacts are small in practice.+-------------------------------------------+| signature (CMS/PKCS#7, detached) |+-------------------------------------------+- | data (signature-covered) | optional+ | data (signature-covered) |+ | loader data |+ | signed sections, directory, trailer |+-------------------------------------------+| metadata | optional+-------------------------------------------+The writer emits the sections in this order, but a reader must relyonly on the header offsets, never on adjacency. ``loader_insns``-begins at offset 360, immediately after the header. ``data`` and-``metadata`` are optional; an absent section-has its ``*_off`` set to 0.+begins at offset 360, immediately after the header. ``metadata`` is+optional and the writer no longer emits it; an absent section has its+``*_off`` set to 0. ``data`` always ends with the signed sections.3) Header---------@@ -130,7 +132,8 @@ with ``data``.For an UNLOAD directive (``flags & DIRECTIVE_UNLOAD``) the loader is nota gen_loader output but the compiled bytes of the small hand-written``bpf/unload.c`` template, parameterised through its ``.rodata`` with-the target name and the expected ``payload_sha256``.+the target name and the expected ``payload_sha256``; the target reads+both from the signed ``NAME`` and ``UNLD`` sections instead.signature~~~~~~~~~@@ -158,27 +161,50 @@ dataThe bytes of ``gen_loader_opts.data``: the blob the loader instructionsreference (the program BTF, ``.rodata`` and map initial values,-relocation inputs, ...). The loader is parameterised by this data, so-it must travel with the instructions. Absent (``data_off == 0``) only-for artifacts with no such data. Writers may append a decoder blob and-trailer; generated loaders ignore the trailing bytes because all their-offsets refer to the original prefix.--Signed decoder trailer. A BPF source declares-``struct shirudo_decoder_manifest`` in ``.rodata``. At build time-shirudo resolves and embeds each referenced decoder source before-signing ``loader_insns || data``, so the decoders are signature-covered.-The final 16 bytes of ``data`` are:+relocation inputs, ...), followed by the signed sections. The loader+is parameterised by its data, so it must travel with the instructions;+it ignores the bytes behind it because all its offsets refer to the+original prefix, and the kernel signs the whole section, so what the+target needs beyond the loader rides there, covered.++Signed sections. Each section is placed at an 8-byte boundary after+the loader data, then a directory of 16-byte entries, then a 16-byte+trailer that ends ``data``:========== ==== ===================== ====================================offset size field meaning========== ==== ===================== ====================================-+0 4 magic ``0x52544344`` (``"DCTR"`` LE)++0 4 magic ``0x52544753`` (``"SGTR"`` LE)+4 4 version ``1``-+8 4 decoder_off offset from the start of ``data``-+12 4 decoder_len decoder blob length++8 4 dir_off directory offset from the start of ``data``++12 4 nr_sections directory entries, 1 to 8+========== ==== ===================== ====================================++Each directory entry:++========== ==== ===================== ====================================+offset size field meaning+========== ==== ===================== ====================================++0 4 tag ``"NAME"``, ``"UPGM"``, ``"UNLD"`` or+ ``"DCDB"`` as little-endian u32++4 4 reserved zero++8 4 off section offset from the start of ``data``++12 4 len section length========== ==== ===================== ====================================+Every section lies before the directory, and every tag appears at most+once. ``NAME`` (256 bytes, NUL-padded) is the upatch name of a LOAD+and the target name of an UNLOAD directive; the header's ``name`` must+equal it. ``UPGM`` is the attach metadata of a LOAD, described below.+``UNLD`` (32 bytes) is the ``payload_sha256`` an UNLOAD directive+expects the loaded upatch to carry. ``DCDB`` is the decoder blob. A+reader takes a directory that breaks any of this for none, and a load+or unload then refuses for what it lacks.++Decoders. A BPF source declares ``struct shirudo_decoder_manifest`` in+``.rodata``. At build time shirudo resolves and embeds each referenced+decoder source in the ``DCDB`` section before signing+``loader_insns || data``, so the decoders are signature-covered.The blob starts with magic ``0x42444344`` (``"DCDB"`` LE), a version, adecoder count and a reserved word. Each 200-byte entry holds thelanguage, API version, input format, fixed-size upatch, map, source@@ -300,7 +326,7 @@ For LOAD artifacts and UNLOAD directives alike this is the SHA-256 ofcovers. At load, shirudo recomputes it. For a loaded upatch it is alsorecorded as the ``security.bpf.shirudo.payload`` xattr on the pindirectory. An UNLOAD directive's expected target digest is carried-separately in its loader ``.rodata`` and in its metadata.+separately in its ``UNLD`` section, and in its loader ``.rodata``.It also lets ``shirudo upatch list`` and ``status`` identify an artifactwithout parsing the instruction stream.@@ -308,22 +334,27 @@ without parsing the instruction stream.7) What is signed------------------The CMS signature covers ``loader_insns || data``. ``metadata`` is not-signed. The integrity model is therefore:+The CMS signature covers ``loader_insns || data``, the signed sections+included. The header and ``metadata`` are not signed. The integrity+model is therefore:- the loader instructions and loader data are signature-verified bythe kernel before anything runs;- the payload program is separately hash-locked by the loader's``excl_prog_hash`` and checked by the kernel at ``BPF_PROG_LOAD``;-- decoder sources are signature-covered because they are appended- inside ``data`` before signing;-- ``metadata`` is advisory. Tampering with a LOAD artifact's attach- metadata changes where the hash-verified program is attached, not- what it contains, and the target validates the blob before creating- links. Tampering with an UNLOAD directive's metadata can only- produce a chain value the operator's expectation rejects, or a- ``payload_mismatch``; the residual that remains is risk 1 in- `threat-model <threat-model.rst>`__.+- the name, the attach metadata, the unload target and the decoder+ sources are signature-covered because they are appended inside+ ``data`` before signing. A load takes the attach sites from the+ signed ``UPGM`` section and refuses an artifact without one; an+ unload takes the target name and expected payload from the signed+ ``NAME`` and ``UNLD`` sections, so a directive detaches the upatch+ its signer made it for and no other. Both refuse a header whose+ ``name`` differs from the signed one, since the pin directory, the+ archive copy, ``status`` and the package tooling read the header;+- the rest of the header is advisory. Its ``payload_sha256`` must+ equal the digest of the signed bytes, which the target recomputes;+ ``nr_maps`` and ``nr_progs`` must agree with the attach metadata, and+ a loader whose descriptors disagree fails at attach.8) Versioning and compatibility-------------------------------@@ -338,9 +369,14 @@ authoritative for symbol offsets and sizes.- a signed decoder blob may be appended inside ``data`` and located bythe trailer at its end. Loaders ignore the additional bytes;readers treat them as opaque loader data;+- the signed sections are appended inside ``data`` and located by the+ trailer at its end. Loaders ignore the additional bytes; a new tag+ is a new section, and a reader refuses a tag it does not know;- the 360-byte header includes ``rodata_data_off``, ``type`` and- ``reserved1``;-- ``reserved1`` is zero in every file a writer emits.+ ``reserved1`` after ``reserved0``;+- ``reserved0`` and ``reserved1`` are zero in every file a writer+ emits; a reader rejects a file in which ``reserved0`` is not, so the+ slot can be given a meaning later without a flag day.A reader must reject a file whose ``magic`` or ``version`` does notmatch, before trusting any offset.@@ -356,10 +392,13 @@ match, before trusting any offset.section starts at or after the 360-byte header;4. ``loader_insns_len`` and ``signature_len`` are non-zero,``rodata_data_off`` is within ``data``, and ``reserved1`` is zero;-5. decoders are parsed only if ``data`` ends with a matching trailer,- all blob and entry bounds fit, fixed strings are NUL-terminated, and- every source range stays inside the blob. Malformed decoder- metadata is treated as absent by offline inspection.+5. the signed sections are parsed only if ``data`` ends with a matching+ trailer, the directory and every section lie within ``data`` in that+ order, every tag is known and appears once, ``NAME`` is 256 bytes+ and ``UNLD`` 32, and the decoder blob's entry bounds fit, its fixed+ strings are NUL-terminated and every source range stays inside it.+ A directory that fails any of this is treated as absent by offline+ inspection, and a load or unload refuses the artifact.10) Production and consumption------------------------------diff --git a/builtin-upatch.c b/builtin-upatch.cindex e79da864..367d9e68 100644--- a/builtin-upatch.c+++ b/builtin-upatch.c@@ -279,10 +279,12 @@ static const struct shirudo_help upatch_get_help = {static int cmd_upatch_info(int argc, const char **argv){char name[SHIRUDO_UPATCH_NAME_MAX + 1]; /* not NUL-term on disk */+ const __u8 *unload_payload;struct shirudo_upatch u;const char *path = NULL;bool json = false;int i, rc, ret = 1;+ __u32 attach_len;for (i = 1; i < argc; i++) {if (strcmp(argv[i], "--json") == 0) {@@ -315,6 +317,8 @@ static int cmd_upatch_info(int argc, const char **argv)memcpy(name, u.hdr.name, sizeof(u.hdr.name));name[SHIRUDO_UPATCH_NAME_MAX] = '\0';+ upatch_signed_attach(&u, &attach_len);+ unload_payload = upatch_signed_unload_payload(&u);if (json) {size_t cap = 8192 + (size_t)u.nr_decoders * 768;@@ -345,6 +349,19 @@ static int cmd_upatch_info(int argc, const char **argv)json_kv_int(&e, "data_len", u.hdr.data_len);json_kv_int(&e, "log_buf_sz", u.hdr.log_buf_sz);json_kv_int(&e, "file_size", (__s64)u.map_size);+ if (upatch_signed_name(&u)) {+ memcpy(name, upatch_signed_name(&u), sizeof(u.hdr.name));+ json_kv_string(&e, "signed_name", name);+ } else {+ json_kv_null(&e, "signed_name");+ }+ json_kv_int(&e, "attach_metadata_len", attach_len);+ if (unload_payload) {+ hex_encode(unload_payload, 32, payload_hex);+ json_kv_string(&e, "unload_payload_sha256", payload_hex);+ } else {+ json_kv_null(&e, "unload_payload_sha256");+ }json_arr_open(&e, "decoders");for (__u32 j = 0; j < u.nr_decoders; j++) {struct upatch_decoder_view d;@@ -407,6 +424,25 @@ static int cmd_upatch_info(int argc, const char **argv)printf(" %-22s %u\n", "Offset:", u.hdr.signature_off);printf(" %-22s %u bytes\n", "Length:", u.hdr.signature_len);+ printf("\nSigned sections:\n");+ if (upatch_signed_name(&u)) {+ memcpy(name, upatch_signed_name(&u), sizeof(u.hdr.name));+ printf(" %-22s %s\n", "Name:", name);+ } else {+ printf(" %-22s (none)\n", "Name:");+ }+ if (attach_len)+ printf(" %-22s %u bytes\n", "Attach metadata:", attach_len);+ else+ printf(" %-22s (none)\n", "Attach metadata:");+ if (unload_payload) {+ printf(" %-22s ", "Unload payload:");+ print_sha256_hex(unload_payload);+ printf("\n");+ } else {+ printf(" %-22s (none)\n", "Unload payload:");+ }+printf("\nDecoders:\n");if (!upatch_has_decoders(&u)) {printf(" (none)\n");@@ -1714,6 +1750,18 @@ static int upatch_apply(const char *path, bool verify_only,rc = 1;goto out;}+ /* The header's copy of the name is what everything else reads. */+ if (!upatch_signed_name(&u) ||+ memcmp(upatch_signed_name(&u), u.hdr.name,+ SHIRUDO_UPATCH_NAME_MAX)) {+ pr_err("upatch: the name of '%s' is not signature-covered or "+ "differs from the signed one; rebuild the artifact",+ upatch_name);+ rep_fail(rep, "parse", "parser_rejected", 0,+ "name not signed");+ rc = 1;+ goto out;+ }/** The signature authorises the load, but payload_sha256 is what the pin@@ -1737,15 +1785,30 @@ static int upatch_apply(const char *path, bool verify_only,}/*- * Program metadata is intentionally outside the loader signature, so- * parse it strictly and bind every uprobe target to its recorded GNU- * build ID before loading any BPF program. Open target fds stay live- * through link creation to prevent pathname replacement races.+ * The attach metadata is signed with the data, which the kernel has+ * not verified yet at this point: parsing it strictly here keeps a+ * malformed artifact from the keyring, the load that follows keeps+ * a forged one from the sites it names. Every uprobe target is bound+ * to its recorded GNU build ID before any BPF program loads, and the+ * open target fds stay live through link creation to prevent+ * pathname replacement races.*/if (!verify_only) {- rc = prog_specs_parse(upatch_metadata(&u),- u.hdr.metadata_len,- u.hdr.nr_progs, &prog_specs);+ const void *attach;+ __u32 attach_len;++ attach = upatch_signed_attach(&u, &attach_len);+ if (!attach) {+ pr_err("upatch: the attach metadata of '%s' is not "+ "signature-covered; rebuild the artifact",+ upatch_name);+ rep_fail(rep, "parse", "parser_rejected", 0,+ "attach metadata not signed");+ rc = 1;+ goto out;+ }+ rc = prog_specs_parse(attach, attach_len, u.hdr.nr_progs,+ &prog_specs);if (rc) {pr_err("upatch program metadata rejected: %s",strerror(-rc));@@ -2634,6 +2697,7 @@ static int cmd_upatch_unload(int argc, const char **argv){const char *file, *expect_chain, *expect_version_id, *report;char name[SHIRUDO_UPATCH_NAME_MAX + 1] = {};+ char staged[PATH_MAX] = {};char persisted[PATH_MAX];__u8 payload[SHIRUDO_UPATCH_PAYLOAD_HASH_LEN] = {};struct shirudo_upatch u;@@ -2657,6 +2721,20 @@ static int cmd_upatch_unload(int argc, const char **argv)if (version_gate(expect_version_id, no_version_check, &rep, "unload") != 0)goto done;+ /*+ * Read once, as a load is: the target and the payload the kernel's+ * signature check covers must be the bytes read back after it, and+ * a file of root's is root's to rewrite between the two.+ */+ rc = stage_upatch(file, staged, sizeof(staged));+ if (rc) {+ pr_err("upatch unload: read %s: %s", file, strerror(-rc));+ rep_fail(&rep, "parse", "parser_rejected", -rc,+ "cannot read .upatch");+ goto done;+ }+ file = staged;+rc = upatch_open(file, &u);if (rc) {pr_err("open %s: %s", file, strerror(-rc));@@ -2672,13 +2750,25 @@ static int cmd_upatch_unload(int argc, const char **argv)upatch_close(&u);goto done;}+ /*+ * The target's name and the payload it is expected to carry are the+ * directive's signed sections; the header's name must be the same,+ * since status and the package tooling read it.+ */+ if (!upatch_signed_name(&u) || !upatch_signed_unload_payload(&u) ||+ memcmp(upatch_signed_name(&u), u.hdr.name,+ SHIRUDO_UPATCH_NAME_MAX)) {+ pr_err("upatch unload: the target of %s is not "+ "signature-covered or differs from the header; rebuild "+ "the directive", rep.path);+ rep_fail(&rep, "parse", "parser_rejected", 0,+ "directive target not signed");+ upatch_close(&u);+ goto done;+ }memcpy(name, u.hdr.name, SHIRUDO_UPATCH_NAME_MAX);name[SHIRUDO_UPATCH_NAME_MAX] = '\0';- if (u.hdr.metadata_len == sizeof(payload))- memcpy(payload, upatch_metadata(&u), sizeof(payload));- else- pr_warn("upatch unload: directive carries no payload metadata; "- "chain event uses zeros");+ memcpy(payload, upatch_signed_unload_payload(&u), sizeof(payload));upatch_close(&u);rep.name = name;hex_encode(payload, sizeof(payload), rep.payload_hex);@@ -2713,40 +2803,33 @@ static int cmd_upatch_unload(int argc, const char **argv)}/*- * The live value is the xattr bpf2 guards; the expected one is the- * directive's unsigned metadata, so this catches an honest- * substitution, not an attacker editing both. A pin whose value- * cannot be read is refused; no pin at all is the already-unloaded- * case below.+ * The live value is the xattr bpf2 guards; the expected one is+ * signed, so a directive detaches the upatch its signer made it+ * for and nothing else. A pin whose value cannot be read is refused;+ * no pin at all is the already-unloaded case below.*/{- __u8 zero[SHIRUDO_UPATCH_PAYLOAD_HASH_LEN] = {};__u8 live[SHIRUDO_UPATCH_PAYLOAD_HASH_LEN];int xrc;- if (memcmp(payload, zero, sizeof(payload)) == 0) {- pr_warn("upatch unload: directive carries no expected "- "payload; skipping payload_mismatch check");- } else {- xrc = get_pin_payload(name, live);- if (xrc == 0) {- if (!ct_eq(live, payload, sizeof(payload))) {- pr_err("upatch unload: payload_mismatch -- the "- "upatch loaded under '%s' is not what the "- "directive expects; refusing", name);- rep_fail(&rep, "pin", "payload_mismatch", EPERM,- "loaded payload does not match directive");- goto done;- }- pr_info("upatch unload: payload matches for '%s'", name);- } else if (xrc != -ENOENT) {- pr_err("upatch unload: cannot read the payload "- "recorded for '%s': %s; refusing", name,- strerror(-xrc));- rep_fail(&rep, "pin", "payload_mismatch", -xrc,- "payload xattr unreadable");+ xrc = get_pin_payload(name, live);+ if (xrc == 0) {+ if (!ct_eq(live, payload, sizeof(payload))) {+ pr_err("upatch unload: payload_mismatch -- the "+ "upatch loaded under '%s' is not what the "+ "directive expects; refusing", name);+ rep_fail(&rep, "pin", "payload_mismatch", EPERM,+ "loaded payload does not match directive");goto done;}+ pr_info("upatch unload: payload matches for '%s'", name);+ } else if (xrc != -ENOENT) {+ pr_err("upatch unload: cannot read the payload "+ "recorded for '%s': %s; refusing", name,+ strerror(-xrc));+ rep_fail(&rep, "pin", "payload_mismatch", -xrc,+ "payload xattr unreadable");+ goto done;}}@@ -2806,6 +2889,8 @@ done:rep.err,rep.err ? strerror(rep.err) : "none",rep.message[0] ? rep.message : "(none)");+ if (staged[0])+ unlink(staged);if (report)report_emit(report, &rep);report_free(&rep);diff --git a/include/shirudo/upatch.h b/include/shirudo/upatch.hindex 3b12f2e7..f7917ba4 100644--- a/include/shirudo/upatch.h+++ b/include/shirudo/upatch.h@@ -65,13 +65,46 @@ _Static_assert(sizeof(struct shirudo_upatch_header) ==SHIRUDO_UPATCH_HEADER_SIZE, "unexpected upatch header padding");/*- * Optional decoder metadata embedded inside the signature-covered data- * section. BPF programs declare a shirudo_decoder_manifest in .rodata;- * shirudo-build resolves and embeds the decoder source before signing.+ * The signed sections: what the target needs beyond the loader and its+ * data, appended to the data section before signing so the kernel's+ * signature check covers them, and located through a trailer in the+ * data's last 16 bytes. The loader ignores the bytes behind its own.+ * A LOAD carries its name and its attach metadata, an UNLOAD directive+ * the name of its target and the payload digest it expects, and a LOAD+ * carries decoders when its programs declare any.+ */+#define SHIRUDO_UPATCH_SIGNED_TRAILER_MAGIC 0x52544753u /* "SGTR" le */+#define SHIRUDO_UPATCH_SIGNED_VERSION 1u+#define SHIRUDO_UPATCH_SIGNED_SECTIONS_MAX 8u++enum shirudo_upatch_section_tag {+ SHIRUDO_UPATCH_SECTION_NAME = 0x454d414eu, /* "NAME" le */+ SHIRUDO_UPATCH_SECTION_ATTACH = 0x4d475055u, /* "UPGM" le */+ SHIRUDO_UPATCH_SECTION_UNLOAD = 0x444c4e55u, /* "UNLD" le */+ SHIRUDO_UPATCH_SECTION_DECODERS = 0x42444344u, /* "DCDB" le */+};++struct shirudo_upatch_signed_section {+ __u32 tag; /* enum shirudo_upatch_section_tag */+ __u32 reserved; /* zero */+ __u32 off; /* from the start of data */+ __u32 len;+};++struct shirudo_upatch_signed_trailer {+ __u32 magic; /* SHIRUDO_UPATCH_SIGNED_TRAILER_MAGIC */+ __u32 version; /* SHIRUDO_UPATCH_SIGNED_VERSION */+ __u32 dir_off; /* the section directory, from the start of data */+ __u32 nr_sections;+};++/*+ * Decoders embedded inside the signature-covered data section. BPF+ * programs declare a shirudo_decoder_manifest in .rodata; shirudo-build+ * resolves and embeds the decoder source before signing.*/#define SHIRUDO_DECODER_MANIFEST_MAGIC 0x44434544u /* "DECD" le */#define SHIRUDO_UPATCH_DECODER_MAGIC 0x42444344u /* "DCDB" le */-#define SHIRUDO_UPATCH_DECODER_TRAILER_MAGIC 0x52544344u /* "DCTR" le */#define SHIRUDO_UPATCH_DECODER_VERSION 1u#define SHIRUDO_UPATCH_DECODER_LANG_LUA 1u#define SHIRUDO_UPATCH_DECODER_INPUT_MAP_V1 1u@@ -116,22 +149,13 @@ struct shirudo_upatch_decoder_blob {struct shirudo_upatch_decoder_entry decoders[];};-struct shirudo_upatch_decoder_trailer {- __u32 magic;- __u32 version;- __u32 decoder_off;- __u32 decoder_len;-};-/*- * Optional metadata format for LOAD upatches. This tells the target how- * each program should be attached after the signed loader has created it.+ * The attach metadata of a LOAD upatch, its ATTACH section: how the+ * target attaches each program after the signed loader has created it.* Programs without a special attach kind use RAW_TRACEPOINT, preserving- * the original attach_btf_id behavior.- *- * Metadata is not signature-covered in the v1 container format. The program- * bytes are still hash-locked by the signed loader; this blob is attach- * policy for the target to validate before creating links.+ * the original attach_btf_id behavior. The program bytes are hash-locked+ * by the signed loader; the site a kprobe, uprobe, cgroup or netfilter+ * program attaches at comes from here, which is why it is signed.*/#define SHIRUDO_UPATCH_ATTACH_TARGET_MAX 128u#define SHIRUDO_UPATCH_PROG_MAGIC 0x4d475055u /* "UPGM" le */diff --git a/testing/fuzz/fuzz-upatch.c b/testing/fuzz/fuzz-upatch.cindex 526617a6..a6de7f16 100644--- a/testing/fuzz/fuzz-upatch.c+++ b/testing/fuzz/fuzz-upatch.c@@ -12,6 +12,8 @@ int LLVMFuzzerTestOneInput(const __u8 *data, size_t size){struct shirudo_prog_spec *specs;struct shirudo_upatch u;+ const void *attach;+ __u32 attach_len;char path[64];int fd;@@ -19,10 +21,13 @@ int LLVMFuzzerTestOneInput(const __u8 *data, size_t size)if (fd < 0)return 0;if (!upatch_open(path, &u)) {- if (!prog_specs_parse(upatch_metadata(&u),- u.hdr.metadata_len,- u.hdr.nr_progs, &specs))+ attach = upatch_signed_attach(&u, &attach_len);+ if (attach &&+ !prog_specs_parse(attach, attach_len, u.hdr.nr_progs,+ &specs))prog_specs_free(specs, u.hdr.nr_progs);+ upatch_signed_name(&u);+ upatch_signed_unload_payload(&u);upatch_is_unload(&u);if (upatch_has_decoders(&u)) {struct upatch_decoder_view d;diff --git a/testing/helper/test-otel-map.c b/testing/helper/test-otel-map.cindex 298902e1..2fd3c50a 100644--- a/testing/helper/test-otel-map.c+++ b/testing/helper/test-otel-map.c@@ -72,13 +72,16 @@ static int make_decoder(bool metric, bool counter, bool snapshot,size_t entries_end = sizeof(struct shirudo_upatch_decoder_blob) +sizeof(struct shirudo_upatch_decoder_entry);size_t decoder_len = entries_end + source_len;- size_t data_len = decoder_len +- sizeof(struct shirudo_upatch_decoder_trailer);+ size_t dir_off = (decoder_len + 7) & ~(size_t)7;+ size_t data_len = dir_off ++ sizeof(struct shirudo_upatch_signed_section) ++ sizeof(struct shirudo_upatch_signed_trailer);size_t loader_off = sizeof(struct shirudo_upatch_header);size_t sig_off = loader_off + sizeof(struct bpf_insn);size_t data_off = sig_off + 1;size_t file_len = data_off + data_len;- struct shirudo_upatch_decoder_trailer trailer = {};+ struct shirudo_upatch_signed_section section = {};+ struct shirudo_upatch_signed_trailer trailer = {};struct shirudo_upatch_decoder_entry entry = {};struct shirudo_upatch_decoder_blob blob = {};struct shirudo_upatch_header header = {};@@ -132,11 +135,16 @@ static int make_decoder(bool metric, bool counter, bool snapshot,entry.source_len = htole32(source_len);memcpy(file + data_off + sizeof(blob), &entry, sizeof(entry));memcpy(file + data_off + entries_end, source, source_len);- trailer.magic = htole32(SHIRUDO_UPATCH_DECODER_TRAILER_MAGIC);- trailer.version = htole32(SHIRUDO_UPATCH_DECODER_VERSION);- trailer.decoder_off = htole32(0);- trailer.decoder_len = htole32(decoder_len);- memcpy(file + data_off + decoder_len, &trailer, sizeof(trailer));+ section.tag = htole32(SHIRUDO_UPATCH_SECTION_DECODERS);+ section.off = htole32(0);+ section.len = htole32(decoder_len);+ memcpy(file + data_off + dir_off, §ion, sizeof(section));+ trailer.magic = htole32(SHIRUDO_UPATCH_SIGNED_TRAILER_MAGIC);+ trailer.version = htole32(SHIRUDO_UPATCH_SIGNED_VERSION);+ trailer.dir_off = htole32(dir_off);+ trailer.nr_sections = htole32(1);+ memcpy(file + data_off + dir_off + sizeof(section), &trailer,+ sizeof(trailer));rc = write_complete(fd, file, file_len);if (close(fd) != 0 && rc == 0)diff --git a/testing/helper/test-upatch-prog-metadata.c b/testing/helper/test-upatch-prog-metadata.cindex 6b96fa4f..ff7c44ac 100644--- a/testing/helper/test-upatch-prog-metadata.c+++ b/testing/helper/test-upatch-prog-metadata.c@@ -27,14 +27,15 @@ static int expect_attach(const struct shirudo_upatch *u, __u32 kind,struct shirudo_upatch_prog_metadata md;struct shirudo_upatch_prog_entry prog;const __u8 *raw;+ __u32 len;if (u->hdr.nr_progs != 1)return fail("unexpected metadata prog count");- if (u->hdr.metadata_len != sizeof(md) + sizeof(prog))- return fail("unexpected metadata length");- raw = upatch_metadata(u);+ raw = upatch_signed_attach(u, &len);if (!raw)- return fail("missing metadata");+ return fail("missing signed metadata");+ if (len != sizeof(md) + sizeof(prog))+ return fail("unexpected metadata length");memcpy(&md, raw, sizeof(md));memcpy(&prog, raw + sizeof(md), sizeof(prog));if (le32toh(md.magic) != SHIRUDO_UPATCH_PROG_MAGIC ||@@ -68,14 +69,15 @@ static int expect_serializer(const struct shirudo_upatch *u)bool arena = false, error = false;const __u8 *raw;size_t i;+ __u32 len;if (u->hdr.nr_maps != 4 || u->hdr.nr_progs != 2)return fail("unexpected map/prog counts");- if (u->hdr.metadata_len != sizeof(md) + sizeof(progs))- return fail("unexpected metadata length");- raw = upatch_metadata(u);+ raw = upatch_signed_attach(u, &len);if (!raw)- return fail("missing metadata");+ return fail("missing signed metadata");+ if (len != sizeof(md) + sizeof(progs))+ return fail("unexpected metadata length");memcpy(&md, raw, sizeof(md));memcpy(progs, raw + sizeof(md), sizeof(progs));if (le32toh(md.magic) != SHIRUDO_UPATCH_PROG_MAGIC ||@@ -105,13 +107,13 @@ static int expect_uprobe_multi(const struct shirudo_upatch *u,struct shirudo_upatch_prog_metadata md;struct shirudo_upatch_prog_entry prog;const __u8 *raw, *cursor, *end;- __u32 path_len, build_id_len, nr_offsets, i;+ __u32 path_len, build_id_len, nr_offsets, len, i;__u64 previous = 0;if (u->hdr.nr_progs != 1)return fail("unexpected metadata prog count");- raw = upatch_metadata(u);- if (!raw || u->hdr.metadata_len < sizeof(md) + sizeof(prog) ++ raw = upatch_signed_attach(u, &len);+ if (!raw || len < sizeof(md) + sizeof(prog) +sizeof(targets) + sizeof(record))return fail("missing uprobe metadata");memcpy(&md, raw, sizeof(md));@@ -127,7 +129,7 @@ static int expect_uprobe_multi(const struct shirudo_upatch *u,strcmp(prog.target, pattern) != 0)return fail("uprobe program entry mismatch");cursor = raw + sizeof(md) + sizeof(prog);- end = raw + u->hdr.metadata_len;+ end = raw + len;memcpy(&targets, cursor, sizeof(targets));if (le32toh(targets.magic) != SHIRUDO_UPATCH_UPROBE_TARGET_MAGIC ||le32toh(targets.version) != SHIRUDO_UPATCH_UPROBE_TARGET_VERSION ||diff --git a/testing/run-target-tests.sh b/testing/run-target-tests.shindex 97b103ca..0964ff2e 100755--- a/testing/run-target-tests.sh+++ b/testing/run-target-tests.sh@@ -69,6 +69,7 @@ for t in \tamperproof/t1125-key-permission.sh \tamperproof/t1140-verity-authority.sh \tamperproof/t1143-attach-scope.sh \+ tamperproof/t1144-signed-metadata.sh \tamperproof/t1150-verity-devices.sh \tamperproof/t1151-verity-process.sh \tamperproof/t1153-verity-hidden.sh \diff --git a/testing/t0005-upatch-decoders.sh b/testing/t0005-upatch-decoders.shindex 42d333d9..e8ce7bbb 100755--- a/testing/t0005-upatch-decoders.sh+++ b/testing/t0005-upatch-decoders.sh@@ -159,7 +159,12 @@ src, root = pathlib.Path(sys.argv[1]), pathlib.Path(sys.argv[2])original = bytearray(src.read_bytes())data_off, data_len = struct.unpack_from("<II", original, 328)trailer = data_off + data_len - 16-decoder_off, decoder_len = struct.unpack_from("<II", original, trailer + 8)+dir_off, nr = struct.unpack_from("<II", original, trailer + 8)+for i in range(nr):+ tag, _, off, length = struct.unpack_from("<IIII", original,+ data_off + dir_off + 16 * i)+ if tag == 0x42444344:+ section, decoder_off, decoder_len = data_off + dir_off + 16 * i, off, lengthblob, entry = data_off + decoder_off, data_off + decoder_off + 16def write(name, changes):data = bytearray(original)@@ -167,7 +172,7 @@ def write(name, changes):struct.pack_into(fmt, data, off, value)(root / name).write_bytes(data)write("bad-decoder-trailer", [(trailer, "<I", 0)])-write("bad-decoder-offset", [(trailer + 8, "<I", 0xffffffff)])+write("bad-decoder-offset", [(section + 8, "<I", 0xffffffff)])write("bad-decoder-count", [(blob + 8, "<I", 0xffffffff)])write("bad-decoder-source-range",[(entry + 192, "<I", decoder_len), (entry + 196, "<I", 1)])diff --git a/testing/tamperproof/t1144-signed-metadata.sh b/testing/tamperproof/t1144-signed-metadata.shnew file mode 100755index 00000000..2570dba5--- /dev/null+++ b/testing/tamperproof/t1144-signed-metadata.sh@@ -0,0 +1,95 @@+#!/bin/sh+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo+#+# t1144 -- the attach metadata, the name and the unload target are+# signed. Root used to edit the symbol a signed kprobe attached at, or+# the name and expected payload of a signed unload directive, and load+# the result as the trusted task: the kernel verified the loader, the+# edited bytes were outside the signature. Now the kernel refuses an+# artifact whose signed sections were touched, and the target refuses+# one whose header disagrees with them. Non-destructive: nothing loads+# and the basic fixture stays pinned.++cd "$(dirname "$0")/.."+. ./integration-lib.sh+target_guard+command -v python3 >/dev/null 2>&1 || test_skip_all "no python3"++FIXTURES=${SHIRUDO_TEST_FIXTURES_DIR:?target fixture directory is not set}+KP="$FIXTURES/shirudo-test-scope-kprobe.upatch"+KP_UNLOAD="$FIXTURES/shirudo-test-scope-kprobe.unload.upatch"+BASIC_PIN=/run/shirudo/bpffs/upatches/shirudo-test-basic/link+B=/run/shirudo/bpffs/upatches+WORK=$(mktemp -d)+trap 'rm -rf "$WORK"' EXIT+[ -s "$KP" ] && [ -s "$KP_UNLOAD" ] || test_skip_all "missing scope kprobe fixture"+[ -e "$BASIC_PIN" ] || test_skip_all "basic fixture is not loaded"+[ ! -e "$B/shirudo-test-scope-kprobe" ] || test_skip_all "scope kprobe fixture is loaded"++# Rewrite the header name, or a string inside one signed section named+# by its tag, keeping payload_sha256 consistent so only the signature or+# the signed name can refuse the result.+mutate() {+ python3 - "$@" <<'PY'+import hashlib, pathlib, struct, sys+src, dst, what = sys.argv[1:4]+data = bytearray(pathlib.Path(src).read_bytes())+loader_off, loader_len = struct.unpack_from("<II", data, 304)+data_off, data_len = struct.unpack_from("<II", data, 328)+if what == "header-name":+ name = sys.argv[4].encode()+ data[16:272] = name + bytes(256 - len(name))+elif what == "section":+ tag, (old, new) = sys.argv[4].encode(), sys.argv[5].split("=")+ magic, version, dir_off, nr = struct.unpack_from(+ "<4sIII", data, data_off + data_len - 16)+ assert magic == b"SGTR" and version == 1+ for i in range(nr):+ t, _, off, length = struct.unpack_from(+ "<4sIII", data, data_off + dir_off + 16 * i)+ if t == tag:+ break+ else:+ raise SystemExit("no section " + tag.decode())+ start = data_off + off+ i = bytes(data[start:start + length]).find(old.encode())+ assert i >= 0, "pattern not in the section"+ data[start + i:start + i + len(old)] = new.encode().ljust(len(old), b"\0")+ payload = bytes(data[loader_off:loader_off + loader_len]) + bytes(data[data_off:data_off + data_len])+ data[272:304] = hashlib.sha256(payload).digest()+pathlib.Path(dst).write_bytes(data)+PY+}++category() {+ "$SHIRUDO_BIN" "$@" --no-precheck --report=- 2>/dev/null | report_field category+}++test_expect_success 'the kernel refuses a load whose kprobe symbol was edited' '+ mutate "$KP" "$WORK/resited.upatch" section UPGM do_nanosleep=do_exit &&+ [ "$(category upatch load "$WORK/resited.upatch")" = signature_rejected ] &&+ [ ! -e "$B/shirudo-test-scope-kprobe" ]+'++test_expect_success 'a load whose header name differs from the signed name is refused' '+ mutate "$KP" "$WORK/renamed.upatch" header-name shirudo-test-renamed &&+ [ "$(category upatch load "$WORK/renamed.upatch")" = parser_rejected ] &&+ [ ! -e "$B/shirudo-test-renamed" ] &&+ [ ! -e "$B/shirudo-test-scope-kprobe" ]+'++test_expect_success 'an unload directive cannot be pointed at another upatch' '+ mutate "$KP_UNLOAD" "$WORK/repointed.unload.upatch" header-name shirudo-test-basic &&+ [ "$(category upatch unload "$WORK/repointed.unload.upatch")" = parser_rejected ] &&+ [ -e "$BASIC_PIN" ]+'++test_expect_success 'the kernel refuses an unload directive whose signed target was edited' '+ mutate "$KP_UNLOAD" "$WORK/retargeted.unload.upatch" section NAME shirudo-test-scope-kprobe=shirudo-test-basic &&+ mutate "$WORK/retargeted.unload.upatch" "$WORK/retargeted.unload.upatch" header-name shirudo-test-basic &&+ [ "$(category upatch unload "$WORK/retargeted.unload.upatch")" = signature_rejected ] &&+ [ -e "$BASIC_PIN" ]+'++test_donediff --git a/tools/shirudo-build/package.c b/tools/shirudo-build/package.cindex 407b4c4e..c6ccec3c 100644--- a/tools/shirudo-build/package.c+++ b/tools/shirudo-build/package.c@@ -1068,43 +1068,69 @@ static int build_decoder_blob(const struct decoder_set *set,return 0;}+struct signed_section {+ __u32 tag;+ const void *data;+ __u32 len;+};++/*+ * data || sections, each at an 8-byte boundary || directory || trailer.+ * The loader addresses nothing past its own data, so the sections are+ * invisible to it and the kernel signs them with the rest.+ */static int compose_signed_data(const void *data, __u32 data_len,- const void *decoder_blob,- __u32 decoder_blob_len,- void **out, __u32 *out_len)+ const struct signed_section *sections,+ __u32 nr_sections, void **out, __u32 *out_len){- struct shirudo_upatch_decoder_trailer trailer = {};- __u64 payload_len, total;- __u32 pad_len;- char *buf;+ struct shirudo_upatch_signed_trailer trailer = {};+ __u64 total = data_len, dir_off;+ __u8 *buf;+ __u32 i;*out = NULL;- *out_len = data_len;- if (!decoder_blob_len)- return 0;- payload_len = (__u64)data_len + decoder_blob_len;- pad_len = (__u32)((8 - (payload_len & 7)) & 7);- total = payload_len + pad_len;- total += sizeof(trailer);+ *out_len = 0;+ if (nr_sections == 0 ||+ nr_sections > SHIRUDO_UPATCH_SIGNED_SECTIONS_MAX)+ return -EINVAL;+ for (i = 0; i < nr_sections; i++) {+ total = (total + 7) & ~7ULL;+ total += sections[i].len;+ }+ dir_off = (total + 7) & ~7ULL;+ total = dir_off ++ (__u64)nr_sections *+ sizeof(struct shirudo_upatch_signed_section) ++ sizeof(trailer);if (total > UINT32_MAX)return -EOVERFLOW;- buf = xmalloc((size_t)total);+ buf = xcalloc(1, (size_t)total);if (!buf)return -ENOMEM;if (data_len)memcpy(buf, data, data_len);- memcpy(buf + data_len, decoder_blob, decoder_blob_len);- memset(buf + data_len + decoder_blob_len, 0, pad_len);-- trailer.magic = htole32(SHIRUDO_UPATCH_DECODER_TRAILER_MAGIC);- trailer.version = htole32(SHIRUDO_UPATCH_DECODER_VERSION);- trailer.decoder_off = htole32(data_len);- trailer.decoder_len = htole32(decoder_blob_len);- memcpy(buf + data_len + decoder_blob_len + pad_len, &trailer,- sizeof(trailer));+ total = data_len;+ for (i = 0; i < nr_sections; i++) {+ struct shirudo_upatch_signed_section s = {};++ total = (total + 7) & ~7ULL;+ memcpy(buf + total, sections[i].data, sections[i].len);+ s.tag = htole32(sections[i].tag);+ s.off = htole32((__u32)total);+ s.len = htole32(sections[i].len);+ memcpy(buf + dir_off + i * sizeof(s), &s, sizeof(s));+ total += sections[i].len;+ }+ trailer.magic = htole32(SHIRUDO_UPATCH_SIGNED_TRAILER_MAGIC);+ trailer.version = htole32(SHIRUDO_UPATCH_SIGNED_VERSION);+ trailer.dir_off = htole32((__u32)dir_off);+ trailer.nr_sections = htole32(nr_sections);+ total = dir_off ++ (__u64)nr_sections * sizeof(struct shirudo_upatch_signed_section);+ memcpy(buf + total, &trailer, sizeof(trailer));*out = buf;- *out_len = (__u32)total;+ *out_len = (__u32)(total + sizeof(trailer));return 0;}@@ -1525,24 +1551,22 @@ static void unregister_target_attach_types(int handler_ids[2])*/static int finalize_object(struct bpf_object *obj, const char *out_path,const char *upatch_name, __u32 flags,- const void *meta, __u32 meta_len,- const char *src_path,+ const __u8 *unload_payload, const char *src_path,const char *pkey_path, const char *cert_path){LIBBPF_OPTS(gen_loader_opts, opts);- __u32 loader_off, sig_off, data_off, data_len, meta_off;- __u32 write_meta_len = meta_len, attach_meta_len = 0;- __u32 decoder_blob_len = 0, signed_data_len = 0;+ struct signed_section sections[SHIRUDO_UPATCH_SIGNED_SECTIONS_MAX];+ __u32 loader_off, sig_off, data_off, data_len, attach_meta_len = 0;+ __u32 decoder_blob_len = 0, signed_data_len = 0, nr_sections = 0;+ char signed_name[SHIRUDO_UPATCH_NAME_MAX] = {};__u32 nr_maps = 0, nr_progs = 0;__u32 rodata_data_off = 0;struct shirudo_upatch_header hdr;struct shirudo_upatch rodata_upatch = {};struct decoder_set decoders = {};struct shirudo_sign_io sio = {};- const void *signed_data = NULL;- const void *write_meta = meta;+ void *signed_data = NULL;size_t loader_data_len;- void *signed_data_buf = NULL;void *loader_data_buf = NULL;void *decoder_blob = NULL;__u32 nr_decoders = 0;@@ -1577,8 +1601,6 @@ static int finalize_object(struct bpf_object *obj, const char *out_path,&attach_meta, &attach_meta_len);if (err)goto out;- write_meta = attach_meta;- write_meta_len = attach_meta_len;err = collect_decoder_manifests(obj, src_path, upatch_name,&decoders);@@ -1607,12 +1629,35 @@ static int finalize_object(struct bpf_object *obj, const char *out_path,err = -EOVERFLOW;goto out;}- err = compose_signed_data(opts.data, (__u32)opts.data_sz,- decoder_blob, decoder_blob_len,- &signed_data_buf, &signed_data_len);+ /*+ * The name the pin, the archive and the register event carry, the+ * attach sites, the unload target: signed with the data, since the+ * header is not.+ */+ strscpy(signed_name, upatch_name, sizeof(signed_name));+ sections[nr_sections++] = (struct signed_section){+ SHIRUDO_UPATCH_SECTION_NAME, signed_name, sizeof(signed_name),+ };+ if (flags & SHIRUDO_DIRECTIVE_UNLOAD) {+ sections[nr_sections++] = (struct signed_section){+ SHIRUDO_UPATCH_SECTION_UNLOAD, unload_payload,+ SHIRUDO_UPATCH_PAYLOAD_HASH_LEN,+ };+ } else {+ sections[nr_sections++] = (struct signed_section){+ SHIRUDO_UPATCH_SECTION_ATTACH, attach_meta,+ attach_meta_len,+ };+ if (decoder_blob_len)+ sections[nr_sections++] = (struct signed_section){+ SHIRUDO_UPATCH_SECTION_DECODERS, decoder_blob,+ decoder_blob_len,+ };+ }+ err = compose_signed_data(opts.data, (__u32)opts.data_sz, sections,+ nr_sections, &signed_data, &signed_data_len);if (err)goto out;- signed_data = signed_data_buf ? signed_data_buf : opts.data;if (__builtin_add_overflow(opts.insns_sz, (size_t)signed_data_len,&loader_data_len)) {err = -EOVERFLOW;@@ -1658,14 +1703,13 @@ static int finalize_object(struct bpf_object *obj, const char *out_path,sig_off = loader_off + opts.insns_sz;data_off = sig_off + (__u32)sio.signature_sz;data_len = signed_data_len;- meta_off = data_off + data_len;pack_header(&hdr, upatch_name, SHIRUDO_UPATCH_TYPE_BPF, flags,sio.payload_sha256,loader_off, opts.insns_sz,sig_off, (__u32)sio.signature_sz,- write_meta_len ? meta_off : 0, write_meta_len,- data_len ? data_off : 0, data_len,+ 0, 0,+ data_off, data_len,1u * 1024u * 1024u,rodata_data_off, nr_maps, nr_progs);@@ -1680,10 +1724,8 @@ static int finalize_object(struct bpf_object *obj, const char *out_path,err = write_complete(fd, opts.insns, opts.insns_sz);if (!err)err = write_complete(fd, sig_buf, sio.signature_sz);- if (!err && data_len)+ if (!err)err = write_complete(fd, signed_data, data_len);- if (!err && write_meta_len)- err = write_complete(fd, write_meta, write_meta_len);if (!err && fsync(fd) != 0)err = -errno;close(fd);@@ -1693,10 +1735,10 @@ static int finalize_object(struct bpf_object *obj, const char *out_path,goto out;}- pr_info("wrote %s (insns=%u sig=%zu data=%u meta=%u maps=%u "+ pr_info("wrote %s (insns=%u sig=%zu data=%u sections=%u maps=%u ""progs=%u decoders=%u name=%s%s)",out_path, opts.insns_sz, sio.signature_sz, data_len,- write_meta_len, nr_maps, nr_progs, nr_decoders,+ nr_sections, nr_maps, nr_progs, nr_decoders,upatch_name,(flags & SHIRUDO_DIRECTIVE_UNLOAD) ? " UNLOAD" : "");out:@@ -1705,7 +1747,7 @@ out:if (loader_data_buf)xfree(loader_data_buf, loader_data_len);free_decoder_set(&decoders);- xfree(signed_data_buf, signed_data_len);+ xfree(signed_data, signed_data_len);xfree(decoder_blob, decoder_blob_len);xfree(sig_buf, SHIRUDO_MAX_SIG_SIZE);bpf_object__close(obj);@@ -1735,8 +1777,8 @@ int shirudo_build_package_load(const char *bpf_o, const char *src_path,unregister_target_attach_types(handler_ids);return err;}- err = finalize_object(obj, out_path, upatch_name, 0,- NULL, 0, src_path, pkey_path, cert_path);+ err = finalize_object(obj, out_path, upatch_name, 0, NULL, src_path,+ pkey_path, cert_path);unregister_target_attach_types(handler_ids);return err;}@@ -1798,14 +1840,11 @@ int shirudo_build_package_unload(const char *upatch_name,}/*- * Carry the target's expected payload_sha256 as metadata so the- * target can compute the unload chain event (and a future- * payload_mismatch check) without parsing the loader data blob.- * The metadata is not signature-covered; tampering only produces- * a chain value the operator's expectation rejects.+ * The target reads the name and the expected payload from the+ * signed sections, not from the loader's .rodata, which it has no+ * portable way to locate in the data blob.*/return finalize_object(obj, out_upatch, upatch_name,- SHIRUDO_DIRECTIVE_UNLOAD,- payload_sha256, 32,+ SHIRUDO_DIRECTIVE_UNLOAD, payload_sha256,NULL, pkey_path, cert_path);}diff --git a/util/upatch.c b/util/upatch.cindex 786ff555..ea8ab285 100644--- a/util/upatch.c+++ b/util/upatch.c@@ -116,53 +116,28 @@ static bool has_nul(const char *s, size_t n)return memchr(s, '\0', n);}-/*- * Parse the optional signed decoder blob. Advisory for now: malformed- * decoder metadata is treated as absent so old upatches and ordinary- * gen_loader data remain readable by `upatch info`.- */-static void parse_decoders(struct shirudo_upatch *u)+/* The DECODERS section: entries and sources within the blob. */+static bool parse_decoders(struct shirudo_upatch *u, const __u8 *bp,+ __u32 decoder_len){- const __u8 *data, *trp, *bp;- __u32 magic, version, decoder_off, decoder_len, nr_decoders;+ __u32 nr_decoders;__u64 entries_end;size_t i;- if (u->hdr.data_len < sizeof(struct shirudo_upatch_decoder_trailer))- return;-- data = u->map + u->hdr.data_off;- trp = data + u->hdr.data_len -- sizeof(struct shirudo_upatch_decoder_trailer);- magic = rd_le32(trp);- if (magic != SHIRUDO_UPATCH_DECODER_TRAILER_MAGIC)- return;- version = rd_le32(trp + 4);- if (version != SHIRUDO_UPATCH_DECODER_VERSION)- return;-- decoder_off = rd_le32(trp + 8);- decoder_len = rd_le32(trp + 12);if (decoder_len < sizeof(struct shirudo_upatch_decoder_blob))- return;- if ((__u64)decoder_off + decoder_len >- (__u64)u->hdr.data_len -- sizeof(struct shirudo_upatch_decoder_trailer))- return;-- bp = data + decoder_off;+ return false;if (rd_le32(bp) != SHIRUDO_UPATCH_DECODER_MAGIC ||rd_le32(bp + 4) != SHIRUDO_UPATCH_DECODER_VERSION)- return;+ return false;nr_decoders = rd_le32(bp + 8);if (nr_decoders == 0)- return;+ return false;entries_end = sizeof(struct shirudo_upatch_decoder_blob) +(__u64)nr_decoders *sizeof(struct shirudo_upatch_decoder_entry);if (entries_end > decoder_len)- return;+ return false;/* The blob sits behind the signature, so entries are unaligned. */for (i = 0; i < nr_decoders; i++) {@@ -175,24 +150,113 @@ static void parse_decoders(struct shirudo_upatch *u)!has_nul(d.map, sizeof(d.map)) ||!has_nul(d.source, sizeof(d.source)) ||!has_nul(d.entrypoint, sizeof(d.entrypoint)))- return;+ return false;if (le32toh(d.language) == 0 ||le32toh(d.api_version) == 0 ||le32toh(d.input_format) == 0 ||le32toh(d.export_signal) == 0)- return;+ return false;source_off = le32toh(d.source_off);source_len = le32toh(d.source_len);if (source_len == 0 || source_off < entries_end ||source_off > decoder_len ||source_len > decoder_len - source_off)- return;+ return false;}u->decoder_blob = (const void *)bp;u->decoder_blob_len = decoder_len;u->nr_decoders = nr_decoders;+ return true;+}++static void forget_signed_sections(struct shirudo_upatch *u)+{+ u->decoder_blob = NULL;+ u->decoder_blob_len = 0;+ u->nr_decoders = 0;+ u->signed_name = NULL;+ u->signed_attach = NULL;+ u->signed_attach_len = 0;+ u->signed_unload_payload = NULL;+}++/*+ * The signed sections behind the loader data. Each lies below the+ * directory, the directory below the trailer, and each tag appears+ * once; a directory that breaks any of that is taken for none, so a+ * load or unload refuses for what it then lacks.+ */+static void parse_signed_sections(struct shirudo_upatch *u)+{+ struct shirudo_upatch_signed_trailer tr;+ __u32 i, nr, dir_off, seen = 0;+ const __u8 *data, *dir;+ __u64 end;++ if (u->hdr.data_len < sizeof(tr))+ return;+ data = u->map + u->hdr.data_off;+ memcpy(&tr, data + u->hdr.data_len - sizeof(tr), sizeof(tr));+ if (le32toh(tr.magic) != SHIRUDO_UPATCH_SIGNED_TRAILER_MAGIC ||+ le32toh(tr.version) != SHIRUDO_UPATCH_SIGNED_VERSION)+ return;+ nr = le32toh(tr.nr_sections);+ dir_off = le32toh(tr.dir_off);+ end = u->hdr.data_len - sizeof(tr);+ if (nr == 0 || nr > SHIRUDO_UPATCH_SIGNED_SECTIONS_MAX ||+ dir_off > end ||+ (__u64)nr * sizeof(struct shirudo_upatch_signed_section) >+ end - dir_off)+ return;+ dir = data + dir_off;+ for (i = 0; i < nr; i++) {+ struct shirudo_upatch_signed_section s;+ __u32 tag, off, len, bit;++ memcpy(&s, dir + i * sizeof(s), sizeof(s));+ tag = le32toh(s.tag);+ off = le32toh(s.off);+ len = le32toh(s.len);+ if (le32toh(s.reserved) || off > dir_off ||+ len > dir_off - off)+ goto reject;+ switch (tag) {+ case SHIRUDO_UPATCH_SECTION_NAME:+ bit = 1;+ if (len != SHIRUDO_UPATCH_NAME_MAX)+ goto reject;+ u->signed_name = (const char *)data + off;+ break;+ case SHIRUDO_UPATCH_SECTION_ATTACH:+ bit = 2;+ if (len == 0)+ goto reject;+ u->signed_attach = data + off;+ u->signed_attach_len = len;+ break;+ case SHIRUDO_UPATCH_SECTION_UNLOAD:+ bit = 4;+ if (len != SHIRUDO_UPATCH_PAYLOAD_HASH_LEN)+ goto reject;+ u->signed_unload_payload = data + off;+ break;+ case SHIRUDO_UPATCH_SECTION_DECODERS:+ bit = 8;+ if (!parse_decoders(u, data + off, len))+ goto reject;+ break;+ default:+ goto reject;+ }+ if (seen & bit)+ goto reject;+ seen |= bit;+ }+ return;+reject:+ forget_signed_sections(u);}static int upatch_parse(const void *data, size_t size,@@ -212,7 +276,7 @@ static int upatch_parse(const void *data, size_t size,rc = validate_bounds(&out->hdr, out->map_size);if (rc)goto err;- parse_decoders(out);+ parse_signed_sections(out);return 0;err:memset(out, 0, sizeof(*out));@@ -274,12 +338,26 @@ void upatch_close(struct shirudo_upatch *u)u->map = NULL;u->map_size = 0;u->mapped = false;- u->decoder_blob = NULL;- u->decoder_blob_len = 0;- u->nr_decoders = 0;+ forget_signed_sections(u);}}+const char *upatch_signed_name(const struct shirudo_upatch *u)+{+ return u->map ? u->signed_name : NULL;+}++const void *upatch_signed_attach(const struct shirudo_upatch *u, __u32 *len)+{+ *len = u->map ? u->signed_attach_len : 0;+ return u->map ? u->signed_attach : NULL;+}++const __u8 *upatch_signed_unload_payload(const struct shirudo_upatch *u)+{+ return u->map ? u->signed_unload_payload : NULL;+}+const void *upatch_loader(const struct shirudo_upatch *u){if (!u->map)diff --git a/util/upatch.h b/util/upatch.hindex be96b1d8..15b7b74d 100644--- a/util/upatch.h+++ b/util/upatch.h@@ -27,6 +27,10 @@ struct shirudo_upatch {const struct shirudo_upatch_decoder_blob *decoder_blob;__u32 decoder_blob_len;__u32 nr_decoders;+ const char *signed_name; /* SHIRUDO_UPATCH_NAME_MAX */+ const __u8 *signed_attach;+ __u32 signed_attach_len;+ const __u8 *signed_unload_payload; /* 32 bytes */};struct upatch_decoder_view {@@ -67,6 +71,18 @@ bool upatch_has_decoders(const struct shirudo_upatch *u);int upatch_decoder_view(const struct shirudo_upatch *u, __u32 idx,struct upatch_decoder_view *out);+/*+ * The signed sections, NULL where the data carries none: the name,+ * NUL-padded to SHIRUDO_UPATCH_NAME_MAX like the header's; the attach+ * metadata of a load; the payload digest an unload directive expects.+ * A load or unload refuses what it needs and does not find; inspection+ * shows what there is.+ */+const char *upatch_signed_name(const struct shirudo_upatch *u);+const void *upatch_signed_attach(const struct shirudo_upatch *u,+ __u32 *len);+const __u8 *upatch_signed_unload_payload(const struct shirudo_upatch *u);+/** Validate an externally-provided upatch name: non-empty, doesn't* start with '.', and matches [A-Za-z0-9._-]+. Rejects anything that@@ -94,9 +110,8 @@ struct shirudo_prog_spec {};/*- * The program metadata of a load upatch, which the loader signature does- * not cover: parsed strictly into one spec per program, target_fd -1.- * 0 or -errno; free with prog_specs_free().+ * The attach metadata of a load upatch, parsed strictly into one spec+ * per program, target_fd -1. 0 or -errno; free with prog_specs_free().*/int prog_specs_parse(const void *metadata, __u32 metadata_len,__u32 nr_progs, struct shirudo_prog_spec **out);