Skip to content

eBPF-based security platform

bpm: generate and update rodata inputs

John Fastabend5a2d0837c4d9
diff --git a/Documentation/upatch-spec.rst b/Documentation/upatch-spec.rst
index 9b097c6d..29e448fc 100644
--- a/Documentation/upatch-spec.rst
+++ b/Documentation/upatch-spec.rst
@@ -83,7 +83,7 @@ offset size type field meaning
336 4 u32 log_buf_sz verifier-log buffer size to allocate at load
340 4 u32 nr_maps gen_loader bpf_map_desc count
344 4 u32 nr_progs gen_loader bpf_prog_desc count
-348 4 u32 reserved0 zero
+348 4 u32 rodata_data_off ``.rodata`` initial value offset in ``data``
352 4 u32 type ``1`` = BPF
356 4 u32 reserved1 zero
========== ==== ====== ===================== ===========================================
@@ -328,17 +328,19 @@ signed. The integrity model is therefore:
8) Versioning and compatibility
-------------------------------
-``version`` is ``1``. The format grows additively without a version
-bump:
+``version`` is ``1``. The header's ``rodata_data_off`` field gives the
+offset within ``data`` of the initial ``.rodata`` value. Writers derive
+it from the generated loader and readers check it against the BTF section
+size and data bounds. The field is outside the loader signature and
+serves as a location hint for offline rewriting; the signed BTF remains
+authoritative for symbol offsets and sizes.
- a signed decoder blob may be appended inside ``data`` and located by
- the trailer at its end. Older loaders ignore the additional bytes;
- older readers treat them as opaque loader data;
-- the 360-byte header includes ``type`` and ``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.
+ the trailer at its end. Loaders ignore the additional bytes;
+ readers treat them as opaque loader data;
+- the 360-byte header includes ``rodata_data_off``, ``type`` and
+ ``reserved1``;
+- ``reserved1`` is zero in every file a writer emits.
A reader must reject a file whose ``magic`` or ``version`` does not
match, before trusting any offset.
@@ -352,8 +354,8 @@ match, before trusting any offset.
2. ``magic`` and ``version`` match;
3. each section ``(off, len)`` lies within the file, and any non-empty
section starts at or after the 360-byte header;
-4. ``loader_insns_len`` and ``signature_len`` are non-zero, and
- ``reserved0`` and ``reserved1`` are zero;
+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
diff --git a/Documentation/upatch.rst b/Documentation/upatch.rst
index e1d80d40..ea77523d 100644
--- a/Documentation/upatch.rst
+++ b/Documentation/upatch.rst
@@ -326,7 +326,7 @@ Example ``example-shields.bee``::
``upatches/kernel-cve/kernel-cve.bee`` in the tree is a worked example
with one entry per CVE shield, and
-``upatches/kernel-obs/kernel-obs.bee`` one with
+``upatches/kernel-obs/Beefile`` one with
decoders and shared headers. Build and inspect::
shirudo bpm build ./example-shields --version 1.0.0 \
@@ -358,6 +358,54 @@ Without it, ``bpm build`` checks ``./vmlinux.h`` and
then checks those paths from the package directory and the installed
shared header path.
+Generated rodata
+~~~~~~~~~~~~~~~~
+
+An upatch may declare repeated ``[[upatches.rodata]]`` entries. Each
+entry names a BTF variable, a default input file, and a ``generator`` and
+``update`` command array. The generator runs during ``bpm build``; the
+updater runs during ``bpm config update``. Commands are executed without
+a shell from the Beefile's directory. Shirudo appends ``--input <path>
+--symbol <name> --output <path>``. The program writes the raw bytes for
+that BTF variable to the output file, and the builder rejects a value
+whose length differs from the BTF variable size.
+
+The default input path is relative to the Beefile. Its override name is
+the input basename up to its first dot: ``watch.list`` is named
+``watch``. Multiple entries can share that input and one command-line
+override. An override path is resolved relative to the caller's working
+directory::
+
+ shirudo bpm build ./upatches/kernel-obs --version 0.1.1 \
+ --rodata-input watch=./customer/watch.list
+
+To change data without compiling BPF again, ``bpm config update`` takes
+a previously built package. By default, it reads the Beefile, updater
+programs, and declared input files from that package. This runs code
+from the package on the operator, so omitting ``-f`` explicitly trusts
+those packaged files. The upatch CMS signature does not authenticate the
+Beefile or updater files. Pass ``-f`` to use a locally selected Beefile
+and its updater files instead. It re-signs the changed upatches,
+regenerates their unload directives, and writes a new package version::
+
+ shirudo bpm config update \
+ --base-package oci://registry.example.com/shirudo/kernel-obs:0.1.0 \
+ --version 0.1.1 \
+ --rodata-input watch=./customer/watch.list
+
+To use a local Beefile instead of trusting the packaged updater, pass
+``-f`` explicitly::
+
+ shirudo bpm config update \
+ --base-package ./kernel-obs-0.1.0.bee \
+ --version 0.1.1 -f ./upatches/kernel-obs/Beefile \
+ --rodata-input watch=./customer/watch.list
+
+Generator and updater programs execute on the operator and must be
+trusted. Include their source and any default input needed later with
+``[[files]]`` entries in the Beefile. The target receives the signed
+upatch and never executes these programs.
+
6) Publishing
-------------
diff --git a/builtin-bpm.c b/builtin-bpm.c
index ea0a6f57..1afeab89 100644
--- a/builtin-bpm.c
+++ b/builtin-bpm.c
@@ -1373,7 +1373,11 @@ static int cmd_bpm_config(int argc, const char **argv)
const char *op = argc > 1 ? argv[1] : NULL;
if (!op || is_help(op)) {
- fprintf(stderr, "usage: shirudo bpm config register {add|list|remove} ...\n");
+ fprintf(stderr,
+ "usage: shirudo bpm config register {add|list|remove} ...\n"
+ " shirudo bpm config update --base-package "
+ "<package.bee|oci://host/repo:tag> --version <version> "
+ "[-f <name>.bee] [options]\n");
return op ? 0 : 2;
}
if (strcmp(op, "register"))
@@ -2238,7 +2242,7 @@ out:
}
static const struct shirudo_help_item bpm_subcmds[] = {
- { "config", "register and manage OCI repositories" },
+ { "config", "manage package inputs and OCI repositories" },
{ "repo", "refresh signed repository indexes" },
{ "tree", "synchronize or publish the signed upatch tree" },
{ "key", "add, fingerprint, and list package certificates" },
@@ -2444,6 +2448,9 @@ int cmd_bpm(int argc, const char **argv)
n_subcmds);
if (!sub)
return 2;
+ if (!strcmp(sub, "config") && argc >= 3 &&
+ !strcmp(argv[2], "update"))
+ return bpm_exec_operator("config", argc, argv);
if (!strcmp(sub, "config"))
return cmd_bpm_config(argc - 1, argv + 1);
if (!strcmp(sub, "info")) {
diff --git a/completion/shirudo.bash b/completion/shirudo.bash
index dbb65584..a2270a32 100644
--- a/completion/shirudo.bash
+++ b/completion/shirudo.bash
@@ -83,7 +83,18 @@ _shirudo()
subs=$("$bin" bpm --list-cmds 2>/dev/null)
COMPREPLY=( $(compgen -W "$subs" -- "$cur") )
elif [[ $sub == config && cword -eq 3 ]]; then
- COMPREPLY=( $(compgen -W "register" -- "$cur") )
+ COMPREPLY=( $(compgen -W "register update" -- "$cur") )
+ elif [[ $sub == config && ${COMP_WORDS[3]} == update && ${COMP_WORDS[COMP_CWORD-1]} == --base-package ]]; then
+ COMPREPLY=( $(compgen -f -X '!*.bee' -- "$cur") )
+ elif [[ $sub == config && ${COMP_WORDS[3]} == update && (${COMP_WORDS[COMP_CWORD-1]} == -f ||
+ ${COMP_WORDS[COMP_CWORD-1]} == --file) ]]; then
+ COMPREPLY=( $(compgen -f -X '!*.bee' -- "$cur") )
+ elif [[ $sub == config && ${COMP_WORDS[3]} == update && ${COMP_WORDS[COMP_CWORD-1]} == --rodata-input ]]; then
+ COMPREPLY=( $(compgen -f -- "$cur") $(compgen -d -- "$cur") )
+ elif [[ $sub == config && ${COMP_WORDS[3]} == update && $cur == -* ]]; then
+ COMPREPLY=( $(compgen -W "--base-package --version -f --file --keys-dir --rodata-input" -- "$cur") )
+ elif [[ $sub == config && ${COMP_WORDS[3]} == update ]]; then
+ COMPREPLY=( $(compgen -f -X '!*.bee' -- "$cur") $(compgen -d -- "$cur") )
elif [[ $sub == config && ${COMP_WORDS[3]} == register && cword -eq 4 ]]; then
COMPREPLY=( $(compgen -W "add list remove" -- "$cur") )
elif [[ $sub == config && ${COMP_WORDS[3]} == register && ${COMP_WORDS[4]} == add && $cur == -* ]]; then
@@ -110,15 +121,19 @@ _shirudo()
elif [[ $sub == info ]]; then
COMPREPLY=( $(compgen -f -X '!*.bee' -- "$cur") \
$(compgen -d -- "$cur") )
- elif [[ $sub == build && ${COMP_WORDS[COMP_CWORD-1]} == -f ]]; then
+ elif [[ $sub == build && (${COMP_WORDS[COMP_CWORD-1]} == -f ||
+ ${COMP_WORDS[COMP_CWORD-1]} == --file) ]]; then
COMPREPLY=( $(compgen -f -X '!*.bee' -- "$cur") \
$(compgen -d -- "$cur") )
elif [[ $sub == build && ${COMP_WORDS[COMP_CWORD-1]} == --keys-dir ]]; then
COMPREPLY=( $(compgen -d -- "$cur") )
elif [[ $sub == build && ${COMP_WORDS[COMP_CWORD-1]} == --vmlinux ]]; then
COMPREPLY=( $(compgen -f -- "$cur") )
+ elif [[ $sub == build && ${COMP_WORDS[COMP_CWORD-1]} == --rodata-input ]]; then
+ COMPREPLY=( $(compgen -f -- "$cur") $(compgen -d -- "$cur") )
elif [[ $sub == build && $cur == -* ]]; then
- COMPREPLY=( $(compgen -W "-f --version --keys-dir --vmlinux" -- "$cur") )
+ COMPREPLY=( $(compgen -W "-f --file --version --keys-dir \
+ --vmlinux --rodata-input" -- "$cur") )
elif [[ $sub == build ]]; then
COMPREPLY=( $(compgen -d -- "$cur") )
elif [[ $sub == tree && cword -eq 3 ]]; then
diff --git a/include/shirudo/upatch.h b/include/shirudo/upatch.h
index 4f44b300..3b12f2e7 100644
--- a/include/shirudo/upatch.h
+++ b/include/shirudo/upatch.h
@@ -56,9 +56,9 @@ struct shirudo_upatch_header {
__u32 log_buf_sz; /* verifier-log buf size */
__u32 nr_maps; /* loader ctx bpf_map_desc count */
__u32 nr_progs; /* loader ctx bpf_prog_desc count */
- __u32 reserved0; /* zero */
+ __u32 rodata_data_off; /* offset in gen_loader_opts.data */
__u32 type; /* enum shirudo_upatch_type */
- __u32 reserved1; /* zero; keeps the v1 header 8-byte aligned */
+ __u32 reserved1; /* zero; keeps the header 8-byte aligned */
};
_Static_assert(sizeof(struct shirudo_upatch_header) ==
diff --git a/testing/Makefile b/testing/Makefile
index 74542728..96bfb92b 100644
--- a/testing/Makefile
+++ b/testing/Makefile
@@ -128,7 +128,7 @@ TEST_VM_BUNDLE_SOURCES := $(sort $(wildcard \
$(ROOT)/testing/fixtures/decoders/* \
$(ROOT)/testing/signing/*.sh \
$(ROOT)/upatches/kernel-obs/*.c $(ROOT)/upatches/kernel-obs/*.h $(ROOT)/upatches/kernel-obs/*.list \
- $(ROOT)/upatches/kernel-obs/*.py $(ROOT)/upatches/kernel-obs/kernel-obs.bee \
+ $(ROOT)/upatches/kernel-obs/*.py $(ROOT)/upatches/kernel-obs/Beefile \
$(ROOT)/upatches/kernel-obs/decoders/*))
# The kernel build replaces versioned package files; depend on its stable stamp.
TEST_VM_BUNDLE_ARTIFACTS := $(VM_KERNEL_STAMP)
diff --git a/testing/t0004-upatch-parse.sh b/testing/t0004-upatch-parse.sh
index a49d4d0d..51f2de8b 100644
--- a/testing/t0004-upatch-parse.sh
+++ b/testing/t0004-upatch-parse.sh
@@ -68,7 +68,7 @@ def mutate(name, off, fmt, value):
struct.pack_into(fmt, data, off, value)
(root / name).write_bytes(data)
mutate("bad-version", 8, "<I", 2)
-mutate("reserved0", 348, "<I", 1)
+mutate("rodata-offset-oob", 348, "<I", 1)
mutate("reserved1", 356, "<I", 1)
mutate("zero-loader", 308, "<I", 0)
mutate("zero-signature", 316, "<I", 0)
@@ -86,7 +86,7 @@ test_expect_success 'structured valid container parses' '
"$S" upatch info "$WORK/valid-structured" >/dev/null 2>&1
'
test_expect_success 'structured header and section bounds fail cleanly' '
- for f in bad-version reserved0 reserved1 zero-loader zero-signature \
+ for f in bad-version rodata-offset-oob reserved1 zero-loader zero-signature \
loader-in-header signature-oob data-overflow metadata-in-header \
data-len-overflow; do reject "$WORK/$f" || exit 1; done
'
diff --git a/tools/shirudo-build/README.md b/tools/shirudo-build/README.md
index 152227d8..4647cea1 100644
--- a/tools/shirudo-build/README.md
+++ b/tools/shirudo-build/README.md
@@ -45,6 +45,7 @@ target boundary) and `AGENTS.md` (the no-subprocess invariant).
| `upatch rewrite-rodata <original> <modified> -o <output> --data-range <offset:length>...` | verify an existing signed upatch, permit changes only to its BTF watch arrays, then re-sign it |
| `keys vouch <cert.der>` | sign a vouch for another certificate |
| `bpm build [context] --version <v> [-f <name>.bee] [--vmlinux <file>]` | compile, sign and package every Beefile upatch into a `.bee` |
+| `bpm config update --base-package <package.bee|oci://host/repo:tag> --version <v> [-f <name>.bee]` | update existing signed upatches from packaged or local rodata configuration |
| `bpm push <pkg.bee> oci://...` | publish the package and certificate referrer; with signing material, also update the signed index |
| `bpm tree append <pkg.bee> oci://...` | publish the next generation of a signed upatch tree |
@@ -95,6 +96,28 @@ example-shield/
The local package definition uses the package name with a `.bee` suffix.
`bpm build` stores it inside the package archive as `Beefile`.
+An upatch may define repeated `[[upatches.rodata]]` entries with a BTF
+`symbol`, a default `input` file, and `generator` and `update` command
+arrays. Commands run in the Beefile's directory without a shell. Shirudo
+appends `--input <path> --symbol <name> --output <path>`; the program writes
+the symbol's raw value bytes to that output file. Its length must match the
+BTF variable. The input override name is the input file's basename through
+its first dot, so `watch.list` is selected with
+`--rodata-input watch=<path>`. Multiple entries can share that input name.
+The default input resolves relative to the Beefile; an override resolves
+relative to the command's working directory.
+
+`bpm config update --base-package <package.bee|oci://host/repo:tag> --version <v>`
+reuses the load upatches in the base package, invokes each configured `update`
+command, re-signs changed `.rodata`, regenerates unload directives, and
+writes a new package. It does not compile BPF. Without `-f`, the Beefile
+and files named by its `[[files]]` entries come from the base package, and
+the operator is choosing to trust and execute its updater programs; those
+files are not covered by the upatch CMS signature. Pass `-f <name>.bee` to
+select a local Beefile and its locally resolved updater files instead.
+List every updater dependency and default input in `[[files]]` when
+packaged updates should be self-contained.
+
Example `example-shield.bee`:
```toml
diff --git a/tools/shirudo-build/bpm-build.c b/tools/shirudo-build/bpm-build.c
index bc7fde91..e9ae7c5d 100644
--- a/tools/shirudo-build/bpm-build.c
+++ b/tools/shirudo-build/bpm-build.c
@@ -8,6 +8,7 @@
*/
#include <ctype.h>
+#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
@@ -17,6 +18,7 @@
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
+#include <sys/wait.h>
#include <sys/utsname.h>
#include <time.h>
#include <unistd.h>
@@ -26,8 +28,11 @@
#include <shirudo/string.h>
#include "bpm.h"
+#include "bpm_oci.h"
+#include "bpm_package.h"
#include "compile.h"
#include "crypto.h"
+#include "io.h"
#include "json.h"
#include "log.h"
#include "hex.h"
@@ -356,6 +361,7 @@ static int build_target_ok(const char *target);
static int build_parse_spec(struct bpm_build_spec *spec, char *body)
{
struct bpm_build_upatch *upatch = NULL, *tree_owner = NULL;
+ struct bpm_build_rodata *rodata = NULL;
struct shirudo_tree_selector *sel = NULL;
struct bpm_build_file *file = NULL;
bool tree_section = false;
@@ -387,6 +393,7 @@ static int build_parse_spec(struct bpm_build_spec *spec, char *body)
memmove(section, s, strlen(s) + 1);
file = NULL;
upatch = NULL;
+ rodata = NULL;
tree_section = !array &&
(!strcmp(section, "upatches.tree") ||
!strcmp(section, "upatches.tree.selector") ||
@@ -402,6 +409,17 @@ static int build_parse_spec(struct bpm_build_spec *spec, char *body)
return -E2BIG;
upatch = &spec->upatches[spec->n_upatches++];
tree_owner = upatch;
+ } else if (array && !strcmp(section, "upatches.rodata")) {
+ if (!tree_owner ||
+ tree_owner->n_rodata >= BPM_BUILD_MAX_RODATA)
+ return -E2BIG;
+ if (!tree_owner->rodata) {
+ tree_owner->rodata = xcalloc(BPM_BUILD_MAX_RODATA,
+ sizeof(*tree_owner->rodata));
+ if (!tree_owner->rodata)
+ return -ENOMEM;
+ }
+ rodata = &tree_owner->rodata[tree_owner->n_rodata++];
} else if (array) {
return -EINVAL;
} else if (tree_section) {
@@ -480,6 +498,30 @@ static int build_parse_spec(struct bpm_build_spec *spec, char *body)
}
if (build_parse_string(value, dst, cap))
return -EINVAL;
+ } else if (rodata) {
+ if (!strcmp(key, "symbol")) {
+ if (build_parse_string(value, rodata->symbol,
+ sizeof(rodata->symbol)))
+ return -EINVAL;
+ } else if (!strcmp(key, "input")) {
+ if (build_parse_string(value, rodata->input,
+ sizeof(rodata->input)))
+ return -EINVAL;
+ } else if (!strcmp(key, "generator")) {
+ if (rodata->n_generator ||
+ build_parse_string_array(value, rodata->generator,
+ BPM_BUILD_MAX_COMMAND_ARGS,
+ &rodata->n_generator))
+ return -EINVAL;
+ } else if (!strcmp(key, "update")) {
+ if (rodata->n_update ||
+ build_parse_string_array(value, rodata->update,
+ BPM_BUILD_MAX_COMMAND_ARGS,
+ &rodata->n_update))
+ return -EINVAL;
+ } else {
+ return -EINVAL;
+ }
} else if (tree_section && !strcmp(section, "upatches.tree")) {
struct bpm_build_tree *t = &tree_owner->tree;
char *dst = NULL;
@@ -552,6 +594,15 @@ static int build_parse_spec(struct bpm_build_spec *spec, char *body)
*p = (char)tolower((__u8)*p);
if (strcmp(u->type, "bpf") || build_default_targets(u))
return -EINVAL;
+ for (size_t j = 0; j < u->n_rodata; j++) {
+ struct bpm_build_rodata *r = &u->rodata[j];
+
+ if (!r->symbol[0] || !r->input[0] ||
+ !r->n_generator || !r->n_update ||
+ r->input[0] == '/' || strstr(r->input, "../") ||
+ !strcmp(r->input, ".."))
+ return -EINVAL;
+ }
if (!u->tree.present)
continue;
if (!u->tree.id[0] || !upatch_name_valid(u->tree.id))
@@ -605,6 +656,10 @@ void bpm_build_spec_free(struct bpm_build_spec *spec)
if (spec->upatches[i].tree.selector)
xfree(spec->upatches[i].tree.selector,
sizeof(*spec->upatches[i].tree.selector));
+ if (spec->upatches[i].rodata)
+ xfree(spec->upatches[i].rodata,
+ BPM_BUILD_MAX_RODATA *
+ sizeof(*spec->upatches[i].rodata));
}
if (spec->build_file)
xfree(spec->build_file, spec->build_file_len + 1);
@@ -640,6 +695,158 @@ static int build_resolve_source(const struct bpm_build_spec *spec,
return 0;
}
+static int build_rodata_input_name(const char *path, char *name, size_t cap)
+{
+ const char *base = strrchr(path, '/');
+ const char *dot;
+ size_t len;
+
+ base = base ? base + 1 : path;
+ dot = strchr(base, '.');
+ len = dot ? (size_t)(dot - base) : strlen(base);
+ if (!len || len >= cap)
+ return -EINVAL;
+ memcpy(name, base, len);
+ name[len] = '\0';
+ return 0;
+}
+
+static const char *build_rodata_input(const struct bpm_build_rodata *rodata,
+ const struct bpm_build_input_override *overrides,
+ size_t n_overrides)
+{
+ char name[128];
+
+ if (build_rodata_input_name(rodata->input, name, sizeof(name)))
+ return NULL;
+ for (size_t i = 0; i < n_overrides; i++)
+ if (!strcmp(overrides[i].name, name))
+ return overrides[i].path;
+ return rodata->input;
+}
+
+static int build_run_rodata_command(const struct bpm_build_spec *spec,
+ const struct bpm_build_rodata *rodata,
+ bool update, const char *input,
+ const char *output)
+{
+ const char *argv[BPM_BUILD_MAX_COMMAND_ARGS + 7] = {};
+ const char (*command)[SHIRUDO_TREE_STRING_MAX] = update ?
+ rodata->update : rodata->generator;
+ int n_command = update ? rodata->n_update : rodata->n_generator;
+ int status;
+ pid_t pid;
+
+ for (int i = 0; i < n_command; i++)
+ argv[i] = command[i];
+ argv[n_command++] = "--input";
+ argv[n_command++] = input;
+ argv[n_command++] = "--symbol";
+ argv[n_command++] = rodata->symbol;
+ argv[n_command++] = "--output";
+ argv[n_command++] = output;
+ pid = fork();
+ if (pid < 0)
+ return -errno;
+ if (!pid) {
+ if (chdir(spec->scope))
+ _exit(126);
+ execvp(argv[0], (char *const *)argv);
+ _exit(127);
+ }
+ if (waitpid(pid, &status, 0) < 0)
+ return -errno;
+ if (WIFEXITED(status) && WEXITSTATUS(status) == 0)
+ return 0;
+ return -EIO;
+}
+
+static int build_rodata_apply(const struct bpm_build_spec *spec,
+ const struct bpm_build_upatch *upatch,
+ const char *load, const char *pkey,
+ const char *cert,
+ const struct bpm_build_input_override *overrides,
+ size_t n_overrides, bool update)
+{
+ for (size_t i = 0; i < upatch->n_rodata; i++) {
+ const struct bpm_build_rodata *rodata = &upatch->rodata[i];
+ const char *selected = build_rodata_input(rodata, overrides,
+ n_overrides);
+ char input[PATH_MAX], generated[PATH_MAX], patched[PATH_MAX];
+ __u8 *value = NULL;
+ size_t value_len = 0;
+ int rc;
+
+ if (!selected)
+ return -EINVAL;
+ if (selected == rodata->input) {
+ rc = build_resolve_source(spec, selected, input,
+ sizeof(input), &(struct stat){});
+ if (rc)
+ return rc;
+ } else if (strscpy(input, selected, sizeof(input)) < 0) {
+ return -ENAMETOOLONG;
+ }
+ if (strsprintf(generated, sizeof(generated), "%s/rodata-%zu-%zu.bin",
+ spec->stage, (size_t)(upatch - spec->upatches), i) < 0 ||
+ strsprintf(patched, sizeof(patched), "%s/rodata-%zu-%zu.upatch",
+ spec->stage, (size_t)(upatch - spec->upatches), i) < 0)
+ return -ENAMETOOLONG;
+ unlink(generated);
+ unlink(patched);
+ rc = build_run_rodata_command(spec, rodata, update, input,
+ generated);
+ if (rc) {
+ pr_err("bpm %s: converter failed for .rodata symbol %s",
+ update ? "config update" : "build", rodata->symbol);
+ goto out;
+ }
+ rc = build_read_file(generated, &value, &value_len,
+ SHIRUDO_UPATCH_FILE_MAX);
+ if (rc)
+ goto out;
+ rc = shirudo_build_package_patch_rodata(load, patched,
+ rodata->symbol, value,
+ value_len, pkey, cert);
+ if (!rc && rename(patched, load))
+ rc = -errno;
+out:
+ if (value)
+ xfree(value, value_len + 1);
+ unlink(generated);
+ if (rc) {
+ unlink(patched);
+ return rc;
+ }
+ }
+ return 0;
+}
+
+static int build_rodata_overrides_known(const struct bpm_build_spec *spec,
+ const struct bpm_build_input_override *overrides,
+ size_t count)
+{
+ for (size_t i = 0; i < count; i++) {
+ bool found = false;
+
+ for (size_t j = 0; j < spec->n_upatches; j++) {
+ const struct bpm_build_upatch *upatch = &spec->upatches[j];
+
+ for (size_t k = 0; k < upatch->n_rodata; k++) {
+ char name[128];
+
+ if (!build_rodata_input_name(upatch->rodata[k].input,
+ name, sizeof(name)) &&
+ !strcmp(name, overrides[i].name))
+ found = true;
+ }
+ }
+ if (!found)
+ return -ENOENT;
+ }
+ return 0;
+}
+
static int build_target_ok(const char *target)
{
const char *p = target;
@@ -675,7 +882,22 @@ static int build_add_target(char seen[][PATH_MAX], size_t *n, const char *target
return 0;
}
-static int build_validate(struct bpm_build_spec *spec)
+static const char *
+build_rodata_command_source(const struct bpm_build_rodata *rodata, bool update)
+{
+ const char (*command)[SHIRUDO_TREE_STRING_MAX] = update ?
+ rodata->update : rodata->generator;
+ int n = update ? rodata->n_update : rodata->n_generator;
+
+ if (!n)
+ return NULL;
+ if (strchr(command[0], '/'))
+ return command[0];
+ return n > 1 ? command[1] : NULL;
+}
+
+static int build_validate(struct bpm_build_spec *spec,
+ bool allow_missing_upatch_source)
{
char seen[BPM_BUILD_MAX_ENTRIES * 3][PATH_MAX];
char resolved[PATH_MAX];
@@ -693,8 +915,53 @@ static int build_validate(struct bpm_build_spec *spec)
if (build_add_target(seen, &n, u->load_target) ||
build_add_target(seen, &n, u->unload_target) ||
- build_resolve_source(spec, u->source, resolved, sizeof(resolved), &st))
+ (allow_missing_upatch_source ? build_target_ok(u->source) :
+ build_resolve_source(spec, u->source, resolved, sizeof(resolved),
+ &st)))
return -EINVAL;
+ for (size_t j = 0; j < u->n_rodata; j++) {
+ struct bpm_build_rodata *r = &u->rodata[j];
+ char input_name[128], other_name[128];
+
+ if (build_resolve_source(spec, r->input, resolved,
+ sizeof(resolved), &st) ||
+ build_rodata_input_name(r->input, input_name,
+ sizeof(input_name)))
+ return -EINVAL;
+ for (size_t k = 0; k < i; k++) {
+ for (size_t m = 0; m < spec->upatches[k].n_rodata; m++) {
+ struct bpm_build_rodata *prev =
+ &spec->upatches[k].rodata[m];
+
+ if (build_rodata_input_name(prev->input,
+ other_name,
+ sizeof(other_name)))
+ return -EINVAL;
+ if (!strcmp(input_name, other_name) &&
+ strcmp(r->input, prev->input))
+ return -EEXIST;
+ }
+ }
+ for (size_t k = 0; k < j; k++) {
+ struct bpm_build_rodata *prev = &u->rodata[k];
+
+ if (build_rodata_input_name(prev->input, other_name,
+ sizeof(other_name)))
+ return -EINVAL;
+ if (!strcmp(input_name, other_name) &&
+ strcmp(r->input, prev->input))
+ return -EEXIST;
+ }
+ for (int k = 0; k < 2; k++) {
+ const char *cmd_source = build_rodata_command_source(r,
+ k != 0);
+
+ if (!cmd_source ||
+ build_resolve_source(spec, cmd_source, resolved,
+ sizeof(resolved), &st))
+ return -EINVAL;
+ }
+ }
}
return 0;
}
@@ -747,6 +1014,7 @@ static void build_upatch_name(const char *source, char *out, size_t cap)
static int build_stage_open(struct bpm_build_spec *spec)
{
const char *tmpdir = getenv("TMPDIR");
+ char resolved[PATH_MAX];
if (!tmpdir || !tmpdir[0])
tmpdir = "/tmp";
@@ -755,6 +1023,16 @@ static int build_stage_open(struct bpm_build_spec *spec)
return -ENAMETOOLONG;
if (!mkdtemp(spec->stage))
return -errno;
+ if (!realpath(spec->stage, resolved)) {
+ int rc = -errno;
+
+ rmdir(spec->stage);
+ return rc;
+ }
+ if (strscpy(spec->stage, resolved, sizeof(spec->stage)) < 0) {
+ rmdir(resolved);
+ return -ENAMETOOLONG;
+ }
return 0;
}
@@ -783,6 +1061,40 @@ static const char *build_shirudo_bpf_include(char *out)
return out;
}
+static int build_remove_tree(const char *path)
+{
+ struct dirent *entry;
+ struct stat st;
+ DIR *dir;
+ int rc = 0;
+
+ if (lstat(path, &st))
+ return errno == ENOENT ? 0 : -errno;
+ if (!S_ISDIR(st.st_mode))
+ return unlink(path) ? -errno : 0;
+ dir = opendir(path);
+ if (!dir)
+ return -errno;
+ while ((entry = readdir(dir))) {
+ char child[PATH_MAX];
+
+ if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, ".."))
+ continue;
+ if (strsprintf(child, sizeof(child), "%s/%s", path,
+ entry->d_name) < 0) {
+ rc = -ENAMETOOLONG;
+ break;
+ }
+ rc = build_remove_tree(child);
+ if (rc)
+ break;
+ }
+ closedir(dir);
+ if (!rc && rmdir(path))
+ rc = -errno;
+ return rc;
+}
+
static void build_stage_close(struct bpm_build_spec *spec)
{
char object[PATH_MAX + 8];
@@ -798,7 +1110,7 @@ static void build_stage_close(struct bpm_build_spec *spec)
unlink(u->load_path);
unlink(u->unload_path);
}
- rmdir(spec->stage);
+ build_remove_tree(spec->stage);
}
/*
@@ -807,7 +1119,9 @@ static void build_stage_close(struct bpm_build_spec *spec)
*/
static int build_upatches(struct bpm_build_spec *spec, const char *pkey,
const char *cert, const char *vmlinux_override,
- const char *shirudo_bpf_incdir)
+ const char *shirudo_bpf_incdir,
+ const struct bpm_build_input_override *overrides,
+ size_t n_overrides, bool update)
{
const char *vmlinux_h = vmlinux_override;
@@ -862,6 +1176,10 @@ static int build_upatches(struct bpm_build_spec *spec, const char *pkey,
unlink(object);
if (rc)
return rc < 0 ? rc : -EIO;
+ rc = build_rodata_apply(spec, u, load, pkey, cert, overrides,
+ n_overrides, update);
+ if (rc)
+ return rc;
if (upatch_open(load, &parsed))
return -EINVAL;
if (upatch_is_unload(&parsed) || !parsed.hdr.name[0]) {
@@ -1139,7 +1457,8 @@ static void build_usage(void)
"usage: shirudo bpm build [context] --version <version>\n"
" shirudo bpm build [context] -f <name>.bee --version <version>\n"
" [--keys-dir <dir>]\n"
- " [--vmlinux <vmlinux.h>]\n\n"
+ " [--vmlinux <vmlinux.h>]\n"
+ " [--rodata-input <name>=<path>]...\n\n"
"Builds a signed .bee package from a Beefile. The build command\n"
"is available only in shirudo-operator and requires signing keys.\n");
}
@@ -1148,6 +1467,8 @@ static int shirudo_build_bpm_build(int argc, char **argv)
{
const char *context = ".", *file_arg = NULL, *version = NULL;
const char *keys_arg = NULL, *vmlinux_arg = NULL;
+ struct bpm_build_input_override overrides[BPM_BUILD_MAX_ENTRIES] = {};
+ size_t n_overrides = 0;
const char *vmlinux_override = NULL;
const char *shirudo_bpf_incdir = NULL;
char build_file[PATH_MAX], resolved_file[PATH_MAX];
@@ -1191,6 +1512,36 @@ static int shirudo_build_bpm_build(int argc, char **argv)
vmlinux_arg = argv[i];
} else if (!strncmp(argv[i], "--vmlinux=", 10)) {
vmlinux_arg = argv[i] + 10;
+ } else if (!strcmp(argv[i], "--rodata-input")) {
+ const char *value;
+ const char *eq;
+ char path[PATH_MAX];
+ struct stat st;
+ size_t name_len;
+
+ if (++i >= argc || n_overrides == ARRAY_SIZE(overrides))
+ goto usage;
+ value = argv[i];
+ eq = strchr(value, '=');
+ if (!eq || eq == value || !eq[1])
+ goto usage;
+ name_len = (size_t)(eq - value);
+ if (name_len >= sizeof(overrides[0].name))
+ goto usage;
+ memcpy(overrides[n_overrides].name, value, name_len);
+ overrides[n_overrides].name[name_len] = '\0';
+ for (size_t j = 0; j < n_overrides; j++)
+ if (!strcmp(overrides[j].name,
+ overrides[n_overrides].name))
+ goto usage;
+ if (!realpath(eq + 1, path))
+ return -errno;
+ if (stat(path, &st) || !S_ISREG(st.st_mode))
+ return -EINVAL;
+ if (strscpy(overrides[n_overrides].path, path,
+ sizeof(overrides[n_overrides].path)) < 0)
+ return -ENAMETOOLONG;
+ n_overrides++;
} else if (argv[i][0] == '-') {
goto usage;
} else if (++positional == 1) {
@@ -1254,11 +1605,14 @@ static int shirudo_build_bpm_build(int argc, char **argv)
goto out;
rc = bpm_build_parse_beefile(body, body_len, spec);
if (!rc)
- rc = build_validate(spec);
+ rc = build_validate(spec, false);
if (rc) {
pr_err("bpm build: %s is not a valid Beefile", resolved_file);
goto out;
}
+ rc = build_rodata_overrides_known(spec, overrides, n_overrides);
+ if (rc)
+ goto out;
if (cert_read_file(cert_path, &cert)) {
rc = -ENOENT;
goto out;
@@ -1279,7 +1633,7 @@ static int shirudo_build_bpm_build(int argc, char **argv)
if (rc)
goto out_cert;
rc = build_upatches(spec, pkey, cert_path, vmlinux_override,
- shirudo_bpf_incdir);
+ shirudo_bpf_incdir, overrides, n_overrides, false);
if (!rc)
rc = build_archive(spec, version, cert_path, fingerprint, out_dir);
build_stage_close(spec);
@@ -1295,11 +1649,479 @@ usage:
return -EINVAL;
}
+static int build_copy_package_member(const char *package, const char *member,
+ const char *output)
+{
+ __u8 *body = NULL;
+ char parent[PATH_MAX];
+ size_t len = 0;
+ char *slash;
+ int fd = -1;
+ int rc;
+
+ rc = bpm_pkg_read_member(package, member, &body, &len,
+ BPM_BUILD_MAX_FILE);
+ if (rc)
+ return rc;
+ if (strscpy(parent, output, sizeof(parent)) < 0) {
+ rc = -ENAMETOOLONG;
+ goto out;
+ }
+ slash = strrchr(parent, '/');
+ if (slash) {
+ char *p;
+ struct stat st;
+
+ *slash = '\0';
+ for (p = parent + (parent[0] == '/'); ; p++) {
+ if (*p != '/' && *p != '\0')
+ continue;
+ {
+ char saved = *p;
+
+ *p = '\0';
+ if (mkdir(parent, 0700) && errno != EEXIST) {
+ rc = -errno;
+ goto out;
+ }
+ if (lstat(parent, &st)) {
+ rc = -errno;
+ goto out;
+ }
+ if (!S_ISDIR(st.st_mode)) {
+ rc = -ENOTDIR;
+ goto out;
+ }
+ *p = saved;
+ }
+ if (!*p)
+ break;
+ }
+ }
+ fd = open(output, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, 0600);
+ if (fd < 0) {
+ rc = -errno;
+ goto out;
+ }
+ rc = write_complete(fd, body, len);
+ if (!rc && fsync(fd))
+ rc = -errno;
+out:
+ if (fd >= 0)
+ close(fd);
+ if (body)
+ xfree(body, len + 1);
+ return rc;
+}
+
+static int build_download_package(const char *reference, char *path)
+{
+ struct bpm_oci_client client = {};
+ struct bpm_descriptor layers[8] = {};
+ struct bpm_buffer manifest = {};
+ char repository[BPM_MAX_ENDPOINT], tag[BPM_MAX_NAME];
+ char url[PATH_MAX], digest[BPM_MAX_DIGEST];
+ __u8 *body = NULL;
+ size_t body_len = 0;
+ int n_layers = 0, fd = -1, rc;
+
+ rc = bpm_oci_parse_pull_ref(reference, &client, repository,
+ sizeof(repository), tag, sizeof(tag));
+ if (rc)
+ return rc;
+ rc = bpm_oci_url(&client, repository, "manifests", tag, url,
+ sizeof(url));
+ if (rc)
+ return rc;
+ rc = bpm_oci_get_memory(&client, url, BPM_MANIFEST_MEDIA, &manifest);
+ if (rc)
+ goto out;
+ rc = bpm_oci_parse_manifest(manifest.data, manifest.len, layers,
+ ARRAY_SIZE(layers), &n_layers, NULL, 0);
+ if (rc)
+ goto out;
+ for (int i = 0; i < n_layers; i++) {
+ if (strcmp(layers[i].media, BPM_PACKAGE_MEDIA))
+ continue;
+ rc = bpm_oci_url(&client, repository, "blobs", layers[i].digest,
+ url, sizeof(url));
+ if (rc)
+ goto out;
+ fd = mkstemp(path);
+ if (fd < 0) {
+ rc = -errno;
+ goto out;
+ }
+ if (close(fd)) {
+ rc = -errno;
+ fd = -1;
+ goto out;
+ }
+ fd = -1;
+ rc = bpm_oci_get_file(&client, url, BPM_PACKAGE_MEDIA, path,
+ layers[i].size);
+ if (rc)
+ goto out;
+ rc = build_read_file(path, &body, &body_len, BPM_BUILD_MAX_FILE);
+ if (rc)
+ goto out;
+ rc = bpm_sha256_hex(body, body_len, digest, sizeof(digest));
+ if (!rc && !bpm_digest_matches(layers[i].digest, digest))
+ rc = -EKEYREJECTED;
+ goto out;
+ }
+ if (!rc)
+ rc = -ENOENT;
+out:
+ if (fd >= 0)
+ close(fd);
+ if (rc)
+ unlink(path);
+ if (body)
+ xfree(body, body_len + 1);
+ bpm_buffer_free(&manifest);
+ return rc;
+}
+
+int shirudo_build_bpm_config_update(int argc, char **argv)
+{
+ const char *file_arg = NULL, *base_arg = NULL;
+ const char *version = NULL, *keys_arg = NULL;
+ struct bpm_build_input_override overrides[BPM_BUILD_MAX_ENTRIES] = {};
+ size_t n_overrides = 0;
+ char build_file[PATH_MAX], resolved_file[PATH_MAX], source_dir[PATH_MAX];
+ char base_package[PATH_MAX], base_package_tmp[] =
+ "/tmp/shirudo-bpm-base-XXXXXX";
+ char keys_dir[PATH_MAX], keys_abs[PATH_MAX];
+ char out_dir[PATH_MAX], pkey[PATH_MAX], cert_path[PATH_MAX];
+ char fingerprint[SHIRUDO_CRYPTO_SHA256_LEN * 2 + 1];
+ __u8 digest[SHIRUDO_CRYPTO_SHA256_LEN], *body = NULL;
+ struct shirudo_cert cert = {};
+ struct bpm_package_info base_info = {};
+ struct bpm_build_spec *spec;
+ size_t body_len = 0;
+ int rc;
+ bool has_rodata = false, package_source, stage_open = false;
+ bool downloaded_package = false;
+
+ for (int i = 1; i < argc; i++) {
+ if (shirudo_build_is_help(argv[i])) {
+ fprintf(stdout,
+ "usage: shirudo bpm config update "
+ "--base-package <package.bee|oci://host/repo:tag> "
+ "--version <version> "
+ "[-f <name>.bee] [--rodata-input <name>=<path>]...\n"
+ "Without -f, the Beefile and updater inputs come from "
+ "--base-package and are trusted as operator-side code.\n");
+ return 0;
+ } else if (!strcmp(argv[i], "-f") ||
+ !strcmp(argv[i], "--file")) {
+ if (++i >= argc)
+ goto usage;
+ file_arg = argv[i];
+ } else if (!strcmp(argv[i], "--base-package")) {
+ if (++i >= argc)
+ goto usage;
+ base_arg = argv[i];
+ } else if (!strcmp(argv[i], "--version")) {
+ if (++i >= argc)
+ goto usage;
+ version = argv[i];
+ } else if (!strcmp(argv[i], "--keys-dir")) {
+ if (++i >= argc)
+ goto usage;
+ keys_arg = argv[i];
+ } else if (!strcmp(argv[i], "--rodata-input")) {
+ const char *value, *eq;
+ char path[PATH_MAX];
+ struct stat st;
+ size_t name_len;
+
+ if (++i >= argc || n_overrides == ARRAY_SIZE(overrides))
+ goto usage;
+ value = argv[i];
+ eq = strchr(value, '=');
+ if (!eq || eq == value || !eq[1])
+ goto usage;
+ name_len = (size_t)(eq - value);
+ if (name_len >= sizeof(overrides[0].name))
+ goto usage;
+ memcpy(overrides[n_overrides].name, value, name_len);
+ overrides[n_overrides].name[name_len] = '\0';
+ for (size_t j = 0; j < n_overrides; j++)
+ if (!strcmp(overrides[j].name,
+ overrides[n_overrides].name))
+ goto usage;
+ if (!realpath(eq + 1, path))
+ return -errno;
+ if (stat(path, &st) || !S_ISREG(st.st_mode))
+ return -EINVAL;
+ if (strscpy(overrides[n_overrides].path, path,
+ sizeof(overrides[n_overrides].path)) < 0)
+ return -ENAMETOOLONG;
+ n_overrides++;
+ } else {
+ goto usage;
+ }
+ }
+ if (!base_arg || !version || !build_version_ok(version))
+ goto usage;
+ if (!strncmp(base_arg, "oci://", 6)) {
+ rc = build_download_package(base_arg, base_package_tmp);
+ if (rc)
+ return rc;
+ if (strscpy(base_package, base_package_tmp,
+ sizeof(base_package)) < 0) {
+ unlink(base_package_tmp);
+ return -ENAMETOOLONG;
+ }
+ downloaded_package = true;
+ } else if (!realpath(base_arg, base_package)) {
+ goto usage;
+ }
+ rc = bpm_pkg_load_info(base_package, &base_info);
+ if (rc)
+ goto out_base;
+ if (bpm_semver_compare(version, base_info.version) <= 0) {
+ rc = -EINVAL;
+ goto out_base;
+ }
+ if (!getcwd(out_dir, sizeof(out_dir))) {
+ rc = -errno;
+ goto out_base;
+ }
+ if (!build_resolve_keys_dir(keys_arg, keys_dir, sizeof(keys_dir)) ||
+ !realpath(keys_dir, keys_abs)) {
+ rc = -ENOENT;
+ goto out_base;
+ }
+ rc = key_paths(keys_abs, pkey, sizeof(pkey), cert_path,
+ sizeof(cert_path));
+ if (rc)
+ goto out_base;
+ if (shirudo_build_check_keys(pkey, cert_path))
+ goto key_error;
+ package_source = !file_arg;
+ spec = xmalloc(sizeof(*spec));
+ if (!spec)
+ goto alloc_error;
+ if (package_source) {
+ rc = build_stage_open(spec);
+ if (rc)
+ goto out;
+ stage_open = true;
+ if (strsprintf(source_dir, sizeof(source_dir), "%s/source",
+ spec->stage) < 0) {
+ rc = -ENAMETOOLONG;
+ goto out;
+ }
+ if (mkdir(source_dir, 0700)) {
+ rc = -errno;
+ goto out;
+ }
+ if (strsprintf(build_file, sizeof(build_file), "%s/Beefile",
+ source_dir) < 0) {
+ rc = -ENAMETOOLONG;
+ goto out;
+ }
+ rc = build_copy_package_member(base_package, "Beefile", build_file);
+ if (rc == -ENOENT) {
+ pr_err("bpm config update: base package %s has no Beefile; "
+ "rebuild it with a Beefile or pass -f <name>.bee",
+ base_package);
+ rc = -EINVAL;
+ }
+ if (rc)
+ goto out;
+ } else if (strscpy(build_file, file_arg, sizeof(build_file)) < 0) {
+ rc = -ENAMETOOLONG;
+ goto out;
+ }
+ if (!realpath(build_file, resolved_file)) {
+ rc = -errno;
+ goto out;
+ }
+ strscpy(spec->scope, resolved_file, sizeof(spec->scope));
+ {
+ char *slash = strrchr(spec->scope, '/');
+
+ if (!slash) {
+ rc = -EINVAL;
+ goto out;
+ }
+ *slash = '\0';
+ }
+ rc = build_read_file(resolved_file, &body, &body_len,
+ BPM_BUILD_MAX_FILE);
+ if (rc)
+ goto out;
+ rc = bpm_build_parse_beefile(body, body_len, spec);
+ if (!rc && package_source) {
+ for (size_t i = 0; i < spec->n_files && !rc; i++) {
+ char output[PATH_MAX];
+
+ if (build_target_ok(spec->files[i].source) ||
+ build_target_ok(spec->files[i].target)) {
+ rc = -EINVAL;
+ break;
+ }
+ if (build_join(output, sizeof(output), spec->scope,
+ spec->files[i].source)) {
+ rc = -ENAMETOOLONG;
+ break;
+ }
+ rc = build_copy_package_member(base_package,
+ spec->files[i].target,
+ output);
+ }
+ if (!rc) {
+ char readme[PATH_MAX];
+
+ if (build_join(readme, sizeof(readme), spec->scope,
+ "README.md")) {
+ rc = -ENAMETOOLONG;
+ } else {
+ rc = build_copy_package_member(base_package,
+ "README.md", readme);
+ if (rc == -ENOENT)
+ rc = 0;
+ }
+ }
+ }
+ if (!rc)
+ rc = build_validate(spec, package_source);
+ if (!rc)
+ rc = build_rodata_overrides_known(spec, overrides, n_overrides);
+ if (!rc && strcmp(spec->name, base_info.name))
+ rc = -EINVAL;
+ for (size_t i = 0; !rc && i < spec->n_upatches; i++)
+ if (spec->upatches[i].n_rodata)
+ has_rodata = true;
+ if (!rc && !has_rodata)
+ rc = -EINVAL;
+ if (rc)
+ goto out;
+ if (cert_read_file(cert_path, &cert)) {
+ rc = -ENOENT;
+ goto out_cert;
+ }
+ rc = cert_pubkey_digest(&cert, digest);
+ if (rc)
+ goto out_cert;
+ hex_encode(digest, sizeof(digest), fingerprint);
+ if (strcmp(fingerprint, base_info.signer)) {
+ rc = -EKEYREJECTED;
+ goto out_cert;
+ }
+ if (chdir(spec->scope)) {
+ rc = -errno;
+ goto out_cert;
+ }
+ if (!stage_open) {
+ rc = build_stage_open(spec);
+ if (rc)
+ goto out_cert;
+ stage_open = true;
+ }
+ for (size_t i = 0; i < spec->n_upatches && !rc; i++) {
+ struct bpm_build_upatch *upatch = &spec->upatches[i];
+ char load[PATH_MAX], unload[PATH_MAX];
+ char expected_name[SHIRUDO_UPATCH_NAME_MAX];
+ struct shirudo_upatch parsed = {};
+ __u8 payload[SHIRUDO_CRYPTO_SHA256_LEN];
+
+ if (strsprintf(load, sizeof(load), "%s/update-%zu.upatch",
+ spec->stage, i) < 0 ||
+ strsprintf(unload, sizeof(unload), "%s/update-%zu.unload.upatch",
+ spec->stage, i) < 0) {
+ rc = -ENAMETOOLONG;
+ break;
+ }
+ rc = build_copy_package_member(base_package, upatch->load_target,
+ load);
+ if (rc)
+ break;
+ rc = shirudo_build_package_verify(load, cert_path);
+ if (rc)
+ break;
+ build_upatch_name(upatch->source, expected_name,
+ sizeof(expected_name));
+ rc = upatch_open(load, &parsed);
+ if (rc)
+ break;
+ if (upatch_is_unload(&parsed) ||
+ strcmp(parsed.hdr.name, expected_name)) {
+ rc = -EINVAL;
+ upatch_close(&parsed);
+ break;
+ }
+ upatch_close(&parsed);
+ rc = build_rodata_apply(spec, upatch, load, pkey, cert_path,
+ overrides, n_overrides, true);
+ if (rc)
+ break;
+ rc = upatch_open(load, &parsed);
+ if (rc)
+ break;
+ if (upatch_is_unload(&parsed)) {
+ rc = -EINVAL;
+ upatch_close(&parsed);
+ break;
+ }
+ strscpy(upatch->name, parsed.hdr.name, sizeof(upatch->name));
+ memcpy(payload, parsed.hdr.payload_sha256, sizeof(payload));
+ hex_encode(payload, sizeof(payload), upatch->payload_sha256);
+ strscpy(upatch->type, upatch_type_str(&parsed),
+ sizeof(upatch->type));
+ upatch_close(&parsed);
+ strscpy(upatch->load_path, load, sizeof(upatch->load_path));
+ strscpy(upatch->unload_path, unload, sizeof(upatch->unload_path));
+ rc = shirudo_build_package_unload(upatch->name, payload, unload,
+ pkey, cert_path);
+ }
+ if (!rc)
+ rc = build_archive(spec, version, cert_path, fingerprint, out_dir);
+out_cert:
+ cert_free(&cert);
+out:
+ if (stage_open) {
+ if (chdir(out_dir) && !rc)
+ rc = -errno;
+ build_stage_close(spec);
+ }
+ if (body)
+ xfree(body, body_len + 1);
+ bpm_build_spec_free(spec);
+ goto out_base;
+key_error:
+ rc = -EACCES;
+ goto out_base;
+alloc_error:
+ rc = -ENOMEM;
+out_base:
+ if (base_info.cert)
+ xfree(base_info.cert, base_info.cert_len + 1);
+ if (downloaded_package)
+ unlink(base_package);
+ return rc;
+usage:
+ fprintf(stderr,
+ "usage: shirudo bpm config update --base-package "
+ "<package.bee|oci://host/repo:tag> --version <version> "
+ "[-f <name>.bee] "
+ "[--rodata-input <name>=<path>]... [--keys-dir <dir>]\n");
+ return -EINVAL;
+}
+
static void bpm_usage(FILE *fp)
{
fprintf(fp,
"usage: shirudo bpm build [context] --version <version> [-f <name>.bee]\n"
" [--keys-dir <dir>] [--vmlinux <vmlinux.h>]\n"
+ " [--rodata-input <name>=<path>]...\n"
+ " shirudo bpm config update --base-package <package.bee|oci://...>\n"
+ " --version <version> [-f <name>.bee]\n"
+ " [--rodata-input <name>=<path>]...\n"
" shirudo bpm push <package-file> <repository> [--keys-dir <dir> |\n"
" --index-cert <cert.der> --index-key <key.pem>]\n"
" shirudo bpm tree append <package-file> <repository> [options]\n\n"
@@ -1327,6 +2149,13 @@ int shirudo_build_bpm(int argc, char **argv)
pr_err("bpm build: %s", strerror(-rc));
return rc ? 1 : 0;
}
+ if (!strcmp(argv[1], "config") && argc >= 3 &&
+ !strcmp(argv[2], "update")) {
+ rc = shirudo_build_bpm_config_update(argc - 2, argv + 2);
+ if (rc < 0 && rc != -EINVAL)
+ pr_err("bpm config update: %s", strerror(-rc));
+ return rc ? 1 : 0;
+ }
if (!strcmp(argv[1], "push"))
return shirudo_build_bpm_push(argc - 1, argv + 1);
if (!strcmp(argv[1], "tree"))
diff --git a/tools/shirudo-build/bpm.h b/tools/shirudo-build/bpm.h
index e21fb7d8..e37dc8ef 100644
--- a/tools/shirudo-build/bpm.h
+++ b/tools/shirudo-build/bpm.h
@@ -19,6 +19,22 @@
#include "upatch.h"
#define BPM_BUILD_MAX_ENTRIES 128
+#define BPM_BUILD_MAX_RODATA 16
+#define BPM_BUILD_MAX_COMMAND_ARGS 16
+
+struct bpm_build_rodata {
+ char symbol[128];
+ char input[PATH_MAX];
+ char generator[BPM_BUILD_MAX_COMMAND_ARGS][SHIRUDO_TREE_STRING_MAX];
+ char update[BPM_BUILD_MAX_COMMAND_ARGS][SHIRUDO_TREE_STRING_MAX];
+ int n_generator;
+ int n_update;
+};
+
+struct bpm_build_input_override {
+ char name[128];
+ char path[PATH_MAX];
+};
struct bpm_build_file {
char source[PATH_MAX];
@@ -49,6 +65,8 @@ struct bpm_build_upatch {
char name[SHIRUDO_UPATCH_NAME_MAX];
char payload_sha256[SHIRUDO_CRYPTO_SHA256_LEN * 2 + 1];
struct bpm_build_tree tree;
+ struct bpm_build_rodata *rodata;
+ size_t n_rodata;
};
struct bpm_build_spec {
@@ -73,6 +91,7 @@ int bpm_build_parse_beefile(const __u8 *body, size_t len,
void bpm_build_spec_free(struct bpm_build_spec *spec);
int shirudo_build_bpm(int argc, char **argv);
+int shirudo_build_bpm_config_update(int argc, char **argv);
int shirudo_build_bpm_push(int argc, char **argv);
int shirudo_build_bpm_tree(int argc, char **argv);
bool shirudo_build_is_help(const char *arg);
diff --git a/tools/shirudo-build/package.c b/tools/shirudo-build/package.c
index d2743c04..407b4c4e 100644
--- a/tools/shirudo-build/package.c
+++ b/tools/shirudo-build/package.c
@@ -87,7 +87,7 @@ static void pack_header(struct shirudo_upatch_header *h,
__u32 meta_off, __u32 meta_len,
__u32 data_off, __u32 data_len,
__u32 log_buf_sz,
- __u32 nr_maps, __u32 nr_progs)
+ __u32 rodata_data_off, __u32 nr_maps, __u32 nr_progs)
{
memset(h, 0, sizeof(*h));
h->magic = htole64(SHIRUDO_UPATCH_MAGIC);
@@ -107,23 +107,24 @@ static void pack_header(struct shirudo_upatch_header *h,
h->log_buf_sz = htole32(log_buf_sz);
h->nr_maps = htole32(nr_maps);
h->nr_progs = htole32(nr_progs);
- h->reserved0 = 0;
+ h->rodata_data_off = htole32(rodata_data_off);
h->type = htole32(type);
h->reserved1 = 0;
}
-int shirudo_build_package_resign(const char *original,
- const char *modified, const char *output,
- const struct shirudo_data_range *ranges,
- size_t nr_ranges, const char *pkey_path,
- const char *cert_path)
+static int package_resign_symbols(const char *original,
+ const char *modified, const char *output,
+ const struct shirudo_data_range *ranges,
+ size_t nr_ranges, const char *const *symbols,
+ size_t nr_symbols, const char *pkey_path,
+ const char *cert_path)
{
struct shirudo_upatch_header hdr;
struct shirudo_sign_io sio = {};
struct shirudo_upatch src = {}, mod = {};
- struct shirudo_rodata_range watch_ranges[2] = {};
+ struct shirudo_rodata_range expected[16] = {};
const __u8 *src_data, *mod_data;
- bool range_found[2] = {};
+ bool range_found[16] = {};
__u8 digest[SHIRUDO_SHA256_LEN], *payload = NULL, *sig_buf = NULL;
char name[SHIRUDO_UPATCH_NAME_MAX + 1];
__u32 loader_off, sig_off, data_off, meta_off;
@@ -133,8 +134,9 @@ int shirudo_build_package_resign(const char *original,
int fd = -1;
int rc;
- if (!original || !modified || !output || !ranges || !nr_ranges ||
- nr_ranges > 16 || !strcmp(original, output) ||
+ if (!original || !modified || !output || !ranges || !symbols ||
+ !nr_ranges || nr_ranges > ARRAY_SIZE(expected) ||
+ nr_symbols != nr_ranges || !strcmp(original, output) ||
!strcmp(modified, output))
return -EINVAL;
rc = upatch_open(original, &src);
@@ -213,22 +215,20 @@ int shirudo_build_package_resign(const char *original,
rc = -EBADMSG;
goto out;
}
- rc = upatch_rodata_watch_ranges(&src, watch_ranges);
- if (rc)
- goto out;
- if (nr_ranges != ARRAY_SIZE(watch_ranges)) {
- rc = -EINVAL;
- goto out;
+ for (i = 0; i < nr_symbols; i++) {
+ rc = upatch_rodata_symbol_range(&src, symbols[i], &expected[i]);
+ if (rc)
+ goto out;
}
for (i = 0; i < nr_ranges; i++) {
- for (j = 0; j < ARRAY_SIZE(watch_ranges); j++)
- if (ranges[i].offset == watch_ranges[j].offset &&
- ranges[i].length == watch_ranges[j].size &&
+ for (j = 0; j < nr_symbols; j++)
+ if (ranges[i].offset == expected[j].offset &&
+ ranges[i].length == expected[j].size &&
!range_found[j]) {
range_found[j] = true;
break;
}
- if (j == ARRAY_SIZE(watch_ranges)) {
+ if (j == nr_symbols) {
rc = -EPERM;
goto out;
}
@@ -276,7 +276,8 @@ int shirudo_build_package_resign(const char *original,
sig_off, (__u32)sio.signature_sz,
mod.hdr.metadata_len ? meta_off : 0, mod.hdr.metadata_len,
sio.data_sz ? data_off : 0, (__u32)sio.data_sz,
- mod.hdr.log_buf_sz, mod.hdr.nr_maps, mod.hdr.nr_progs);
+ mod.hdr.log_buf_sz, mod.hdr.rodata_data_off,
+ mod.hdr.nr_maps, mod.hdr.nr_progs);
fd = open(output, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644);
if (fd < 0) {
rc = -errno;
@@ -305,6 +306,163 @@ out:
return rc;
}
+int shirudo_build_package_resign(const char *original,
+ const char *modified, const char *output,
+ const struct shirudo_data_range *ranges,
+ size_t nr_ranges, const char *pkey_path,
+ const char *cert_path)
+{
+ static const char *const symbols[] = {
+ "obs_watch_v4", "obs_watch_v6",
+ };
+
+ return package_resign_symbols(original, modified, output, ranges,
+ nr_ranges, symbols, ARRAY_SIZE(symbols),
+ pkey_path, cert_path);
+}
+
+int shirudo_build_package_patch_rodata(const char *input, const char *output,
+ const char *symbol, const __u8 *value,
+ size_t value_len, const char *pkey_path,
+ const char *cert_path)
+{
+ struct shirudo_upatch src = {};
+ struct shirudo_rodata_range range = {};
+ struct shirudo_data_range allowed = {};
+ const char *symbols[1] = { symbol };
+ __u8 digest[SHIRUDO_SHA256_LEN], *payload = NULL, *candidate = NULL;
+ char modified[] = "/tmp/shirudo-rodata-XXXXXX";
+ __u64 payload_len;
+ __u32 digest_len;
+ int fd = -1;
+ int rc;
+
+ if (!input || !output || !symbol || !value || !value_len ||
+ !strcmp(input, output))
+ return -EINVAL;
+ rc = upatch_open(input, &src);
+ if (rc)
+ return rc;
+ if (upatch_is_unload(&src)) {
+ rc = -EINVAL;
+ goto out;
+ }
+ payload_len = (__u64)src.hdr.loader_insns_len + src.hdr.data_len;
+ if (payload_len > SIZE_MAX) {
+ rc = -EOVERFLOW;
+ goto out;
+ }
+ payload = xmalloc((size_t)payload_len);
+ if (!payload) {
+ rc = -ENOMEM;
+ goto out;
+ }
+ memcpy(payload, upatch_loader(&src), src.hdr.loader_insns_len);
+ memcpy(payload + src.hdr.loader_insns_len, upatch_data(&src),
+ src.hdr.data_len);
+ rc = bpm_verify_cms(payload, (size_t)payload_len,
+ upatch_signature(&src), src.hdr.signature_len,
+ cert_path);
+ if (rc)
+ goto out;
+ if (EVP_Digest(payload, (size_t)payload_len, digest, &digest_len,
+ EVP_sha256(), NULL) != 1 ||
+ digest_len != sizeof(digest) ||
+ memcmp(digest, src.hdr.payload_sha256, sizeof(digest))) {
+ rc = -EBADMSG;
+ goto out;
+ }
+ rc = upatch_rodata_symbol_range(&src, symbol, &range);
+ if (rc)
+ goto out;
+ if (value_len != range.size || range.offset > src.hdr.data_len ||
+ value_len > src.hdr.data_len - range.offset) {
+ rc = -EINVAL;
+ goto out;
+ }
+ candidate = xmalloc(src.map_size);
+ if (!candidate) {
+ rc = -ENOMEM;
+ goto out;
+ }
+ memcpy(candidate, src.map, src.map_size);
+ memcpy(candidate + src.hdr.data_off + range.offset, value, value_len);
+ fd = mkstemp(modified);
+ if (fd < 0) {
+ rc = -errno;
+ goto out;
+ }
+ rc = write_complete(fd, candidate, src.map_size);
+ if (!rc && fsync(fd))
+ rc = -errno;
+ if (close(fd) && !rc)
+ rc = -errno;
+ fd = -1;
+ if (rc)
+ goto out;
+ allowed.offset = range.offset;
+ allowed.length = range.size;
+ rc = package_resign_symbols(input, modified, output, &allowed, 1,
+ symbols, ARRAY_SIZE(symbols), pkey_path,
+ cert_path);
+out:
+ if (fd >= 0)
+ close(fd);
+ if (modified[0] && access(modified, F_OK) == 0)
+ unlink(modified);
+ if (candidate)
+ xfree(candidate, src.map_size);
+ if (payload)
+ xfree(payload, (size_t)payload_len);
+ upatch_close(&src);
+ return rc;
+}
+
+int shirudo_build_package_verify(const char *input, const char *cert_path)
+{
+ struct shirudo_upatch upatch = {};
+ __u8 digest[SHIRUDO_SHA256_LEN], *payload = NULL;
+ __u64 payload_len;
+ __u32 digest_len;
+ int rc;
+
+ rc = upatch_open(input, &upatch);
+ if (rc)
+ return rc;
+ if (upatch_is_unload(&upatch)) {
+ rc = -EINVAL;
+ goto out;
+ }
+ payload_len = (__u64)upatch.hdr.loader_insns_len + upatch.hdr.data_len;
+ if (payload_len > SIZE_MAX) {
+ rc = -EOVERFLOW;
+ goto out;
+ }
+ payload = xmalloc((size_t)payload_len);
+ if (!payload) {
+ rc = -ENOMEM;
+ goto out;
+ }
+ memcpy(payload, upatch_loader(&upatch), upatch.hdr.loader_insns_len);
+ memcpy(payload + upatch.hdr.loader_insns_len, upatch_data(&upatch),
+ upatch.hdr.data_len);
+ rc = bpm_verify_cms(payload, (size_t)payload_len,
+ upatch_signature(&upatch), upatch.hdr.signature_len,
+ cert_path);
+ if (rc)
+ goto out;
+ if (EVP_Digest(payload, (size_t)payload_len, digest, &digest_len,
+ EVP_sha256(), NULL) != 1 ||
+ digest_len != sizeof(digest) ||
+ memcmp(digest, upatch.hdr.payload_sha256, sizeof(digest)))
+ rc = -EBADMSG;
+out:
+ if (payload)
+ xfree(payload, (size_t)payload_len);
+ upatch_close(&upatch);
+ return rc;
+}
+
int shirudo_build_upatch_cli(int argc, char **argv)
{
const char *keys_dir = NULL, *original = NULL, *modified = NULL;
@@ -1376,12 +1534,16 @@ static int finalize_object(struct bpf_object *obj, const char *out_path,
__u32 write_meta_len = meta_len, attach_meta_len = 0;
__u32 decoder_blob_len = 0, signed_data_len = 0;
__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;
+ size_t loader_data_len;
void *signed_data_buf = NULL;
+ void *loader_data_buf = NULL;
void *decoder_blob = NULL;
__u32 nr_decoders = 0;
void *attach_meta = NULL;
@@ -1451,6 +1613,29 @@ static int finalize_object(struct bpf_object *obj, const char *out_path,
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;
+ goto out;
+ }
+ loader_data_buf = xmalloc(loader_data_len);
+ if (!loader_data_buf) {
+ err = -ENOMEM;
+ goto out;
+ }
+ memcpy(loader_data_buf, opts.insns, opts.insns_sz);
+ if (signed_data_len)
+ memcpy((__u8 *)loader_data_buf + opts.insns_sz, signed_data,
+ signed_data_len);
+ rodata_upatch.map = loader_data_buf;
+ rodata_upatch.hdr.loader_insns_len = (__u32)opts.insns_sz;
+ rodata_upatch.hdr.data_off = (__u32)opts.insns_sz;
+ rodata_upatch.hdr.data_len = signed_data_len;
+ err = upatch_rodata_data_offset(&rodata_upatch, &rodata_data_off);
+ if (err == -ENOENT)
+ err = 0;
+ if (err)
+ goto out;
sig_buf = xmalloc(SHIRUDO_MAX_SIG_SIZE);
if (!sig_buf) {
@@ -1482,7 +1667,7 @@ static int finalize_object(struct bpf_object *obj, const char *out_path,
write_meta_len ? meta_off : 0, write_meta_len,
data_len ? data_off : 0, data_len,
1u * 1024u * 1024u,
- nr_maps, nr_progs);
+ rodata_data_off, nr_maps, nr_progs);
fd = open(out_path, O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (fd < 0) {
@@ -1517,6 +1702,8 @@ static int finalize_object(struct bpf_object *obj, const char *out_path,
out:
if (fd >= 0)
close(fd);
+ if (loader_data_buf)
+ xfree(loader_data_buf, loader_data_len);
free_decoder_set(&decoders);
xfree(signed_data_buf, signed_data_len);
xfree(decoder_blob, decoder_blob_len);
diff --git a/tools/shirudo-build/package.h b/tools/shirudo-build/package.h
index 3e1e8c72..683aea65 100644
--- a/tools/shirudo-build/package.h
+++ b/tools/shirudo-build/package.h
@@ -30,6 +30,11 @@ int shirudo_build_package_resign(const char *original,
const struct shirudo_data_range *ranges,
size_t nr_ranges, const char *pkey_path,
const char *cert_path);
+int shirudo_build_package_patch_rodata(const char *input, const char *output,
+ const char *symbol, const __u8 *value,
+ size_t value_len, const char *pkey_path,
+ const char *cert_path);
+int shirudo_build_package_verify(const char *input, const char *cert_path);
int shirudo_build_upatch_cli(int argc, char **argv);
#endif /* SHIRUDO_BUILD_PACKAGE_H */
diff --git a/upatches/kernel-obs/Beefile b/upatches/kernel-obs/Beefile
new file mode 100644
index 00000000..975e7d31
--- /dev/null
+++ b/upatches/kernel-obs/Beefile
@@ -0,0 +1,36 @@
+[package]
+name = "kernel-obs"
+description = "shirudo kernel observability: exec, network, DNS, listeners, watched destinations, executable mappings, privilege and sensitive file access"
+license = "GPL-2.0 OR BSD-2-Clause"
+authors = ["Authors of shirudo"]
+
+[[upatches]]
+source = "kernel-obs.bpf.c"
+
+[[upatches.rodata]]
+symbol = "obs_watch_v4"
+input = "watch.list"
+generator = ["python3", "gen_watch_rodata.py"]
+update = ["python3", "gen_watch_rodata.py"]
+
+[[upatches.rodata]]
+symbol = "obs_watch_v6"
+input = "watch.list"
+generator = ["python3", "gen_watch_rodata.py"]
+update = ["python3", "gen_watch_rodata.py"]
+
+[[files]]
+source = "gen_watch_rodata.py"
+target = "gen_watch_rodata.py"
+
+[[files]]
+source = "gen_watch.py"
+target = "gen_watch.py"
+
+[[files]]
+source = "watch_generated.h"
+target = "watch_generated.h"
+
+[[files]]
+source = "watch.list"
+target = "watch.list"
diff --git a/upatches/kernel-obs/README.md b/upatches/kernel-obs/README.md
index 4b1d0e31..567bb60a 100644
--- a/upatches/kernel-obs/README.md
+++ b/upatches/kernel-obs/README.md
@@ -109,6 +109,33 @@ write a separate artifact. The tool refuses a list that needs more trie
nodes than the existing arrays hold; changing those capacities still
requires rebuilding the BPF object.
+The Beefile also declares `watch.list` as the input for both watch trie
+variables. `bpm build` uses `gen_watch_rodata.py` to create their raw BTF
+values. The input name is derived from the basename before its first dot,
+so `watch.list` is named `watch`; override it for one build with:
+
+```sh
+shirudo bpm build ./upatches/kernel-obs --version 0.1.1 \
+ --rodata-input watch=./customer/watch.list
+```
+
+To update the data without recompiling BPF, `bpm config update` reads the
+Beefile and updater dependencies from a previously built package. This
+chooses to trust and run the package's updater on the operator; those files
+are not covered by the upatch CMS signature. It then writes a new versioned
+package:
+
+```sh
+shirudo bpm config update \
+ --base-package oci://registry.example.com/shirudo/kernel-obs:0.1.0 \
+ --version 0.1.1 \
+ --rodata-input watch=./customer/watch.list
+```
+
+Pass `-f ./upatches/kernel-obs/Beefile` to use the local Beefile
+and updater files instead. The target receives only the newly signed
+upatch and never runs the updater.
+
## Read the tables
```sh
diff --git a/upatches/kernel-obs/gen_watch_rodata.py b/upatches/kernel-obs/gen_watch_rodata.py
new file mode 100644
index 00000000..8a24814c
--- /dev/null
+++ b/upatches/kernel-obs/gen_watch_rodata.py
@@ -0,0 +1,62 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: BSD-2-Clause
+# Copyright (c) 2026 Authors of shirudo
+"""Generate one kernel-obs watch trie as a raw BTF variable value."""
+
+import argparse
+from pathlib import Path
+import re
+import struct
+
+from gen_watch import build_trie, read_networks
+
+
+NODE_SIZE = 520
+CHILD_OFFSET = 0
+TERMINAL_OFFSET = 512
+
+
+def node_capacity(symbol):
+ version = {"obs_watch_v4": "V4", "obs_watch_v6": "V6"}.get(symbol)
+ if not version:
+ raise ValueError(f"unsupported watch symbol: {symbol}")
+ text = Path("watch_generated.h").read_text()
+ match = re.search(rf"^#define OBS_WATCH_{version}_NODES (\d+)u$",
+ text, re.MULTILINE)
+ if not match:
+ raise ValueError(f"missing OBS_WATCH_{version}_NODES in watch_generated.h")
+ return int(match.group(1))
+
+
+def encode(nodes, capacity):
+ if len(nodes) > capacity:
+ raise ValueError(f"trie needs {len(nodes)} nodes; object holds {capacity}")
+ data = bytearray(capacity * NODE_SIZE)
+ for index, node in enumerate(nodes):
+ base = index * NODE_SIZE
+ for octet, child in node["children"].items():
+ struct.pack_into("<H", data,
+ base + CHILD_OFFSET + octet * 2, child + 1)
+ struct.pack_into("<H", data, base + TERMINAL_OFFSET,
+ int(node["terminal"]))
+ return data
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--input", required=True, type=Path)
+ parser.add_argument("--symbol", required=True)
+ parser.add_argument("--output", required=True, type=Path)
+ args = parser.parse_args()
+ version = 4 if args.symbol == "obs_watch_v4" else 6
+ try:
+ networks = read_networks(args.input)
+ data = encode(build_trie(networks, version), node_capacity(args.symbol))
+ args.output.write_bytes(data)
+ except (OSError, ValueError) as error:
+ parser.error(str(error))
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/upatches/kernel-obs/kernel-obs.bee b/upatches/kernel-obs/kernel-obs.bee
deleted file mode 100644
index 038135c8..00000000
--- a/upatches/kernel-obs/kernel-obs.bee
+++ /dev/null
@@ -1,8 +0,0 @@
-[package]
-name = "kernel-obs"
-description = "shirudo kernel observability: exec, network, DNS, listeners, watched destinations, executable mappings, privilege and sensitive file access"
-license = "GPL-2.0 OR BSD-2-Clause"
-authors = ["Authors of shirudo"]
-
-[[upatches]]
-source = "kernel-obs.bpf.c"
diff --git a/upatches/kernel-obs/rewrite_watch_upatch.py b/upatches/kernel-obs/rewrite_watch_upatch.py
index d0cd6578..41ba14e4 100644
--- a/upatches/kernel-obs/rewrite_watch_upatch.py
+++ b/upatches/kernel-obs/rewrite_watch_upatch.py
@@ -28,16 +28,6 @@ BTF_KIND_RESTRICT = 11
BTF_KIND_VAR = 14
BTF_KIND_DATASEC = 15
BTF_KIND_TYPE_TAG = 18
-BPF_PSEUDO_MAP_IDX_VALUE = 6
-BPF_FUNC_SYS_BPF = 166
-BPF_MAP_CREATE = 0
-BPF_MAP_UPDATE_ELEM = 2
-BPF_LDDW = 0x18
-BPF_JMP_CALL = 0x85
-BPF_ALU64_MOV_IMM = 0xB7
-BPF_LDXW = 0x61
-BPF_STXW = 0x63
-BPF_STXDW = 0x7B
class RewriteError(Exception):
@@ -235,131 +225,6 @@ def btf_name(types, name_off):
raise RewriteError("BTF string table is unavailable")
-def decode_insn(raw, index):
- return struct.unpack_from("<BBhi", raw, index * 8)
-
-
-def lddw_offset(insns, index, reg):
- if index + 1 >= len(insns):
- return None
- code, regs, off, imm = insns[index]
- next_code, _, next_off, next_imm = insns[index + 1]
- if (code != BPF_LDDW or regs & 0xf != reg or regs >> 4 !=
- BPF_PSEUDO_MAP_IDX_VALUE or off or imm or next_code or next_off):
- return None
- return next_imm & 0xffffffff
-
-
-def sys_bpf_call(insns, index):
- if index < 4 or index >= len(insns):
- return None
- if insns[index][0] != BPF_JMP_CALL or insns[index][3] != BPF_FUNC_SYS_BPF:
- return None
- cmd = insns[index - 4]
- attr_size = insns[index - 1]
- if (cmd[0] != BPF_ALU64_MOV_IMM or cmd[1] != 1 or
- insns[index - 3][0] != BPF_LDDW or
- attr_size[0] != BPF_ALU64_MOV_IMM or attr_size[1] != 3):
- return None
- attr = lddw_offset(insns, index - 3, 2)
- if attr is None:
- return None
- return cmd[3], attr, attr_size[3]
-
-
-def next_sys_bpf(insns, start):
- for index in range(start, len(insns)):
- if sys_bpf_call(insns, index):
- return index
- return len(insns)
-
-
-def map_create_slot(insns, call, end):
- for index in range(call + 1, end - 2):
- offset = lddw_offset(insns, index, 1)
- if offset is None:
- continue
- code, regs, off, imm = insns[index + 2]
- if (code == BPF_STXW and regs & 0xf == 1 and regs >> 4 == 7 and
- off == 0 and offset % 4 == 0):
- return offset // 4
- return None
-
-
-def map_update_slot(insns, call, attr):
- start = max(0, call - 48)
- for index in range(start, call - 5):
- fd_array_offset = lddw_offset(insns, index, 2)
- if fd_array_offset is None:
- continue
- code, regs, off, imm = insns[index + 2]
- if (code != BPF_LDXW or regs & 0xf != 0 or regs >> 4 != 2 or off or
- lddw_offset(insns, index + 3, 1) != attr):
- continue
- code, regs, off, imm = insns[index + 5]
- if (code == BPF_STXW and regs & 0xf == 1 and regs >> 4 == 0 and
- off == 0 and fd_array_offset % 4 == 0):
- return fd_array_offset // 4
- return None
-
-
-def map_update_value_offset(insns, call, attr):
- start = max(0, call - 24)
- for index in range(start, call - 4):
- value_offset = lddw_offset(insns, index, 0)
- if value_offset is None:
- continue
- if lddw_offset(insns, index + 2, 1) != attr + 16:
- continue
- code, regs, off, imm = insns[index + 4]
- if (code == BPF_STXDW and regs & 0xf == 1 and regs >> 4 == 0 and
- off == 0):
- return value_offset
- return None
-
-
-def locate_rodata_data(loader, data_blob, datasec_size):
- if len(loader) % 8:
- raise RewriteError("loader instruction section has an invalid size")
- insns = [decode_insn(loader, i) for i in range(len(loader) // 8)]
- created = {}
- for index, insn in enumerate(insns):
- call = sys_bpf_call(insns, index)
- if not call:
- continue
- cmd, attr_offset, attr_size = call
- if attr_offset > len(data_blob) or attr_size > len(data_blob) - attr_offset:
- raise RewriteError("loader BPF attribute is outside its data section")
- if cmd == BPF_MAP_CREATE:
- if attr_size < 44:
- continue
- map_name = data_blob[attr_offset + 28:attr_offset + 44]
- map_name = map_name.split(b"\0", 1)[0].decode("ascii", "ignore")
- if not map_name.endswith(".rodata"):
- continue
- slot = map_create_slot(insns, index,
- next_sys_bpf(insns, index + 1))
- if slot is None:
- raise RewriteError("cannot find the loader slot for .rodata")
- value_size = struct.unpack_from("<I", data_blob,
- attr_offset + 8)[0]
- if value_size != datasec_size:
- raise RewriteError(".rodata map size does not match BTF")
- created[slot] = value_size
- elif cmd == BPF_MAP_UPDATE_ELEM:
- slot = map_update_slot(insns, index, attr_offset)
- if slot not in created or created[slot] != datasec_size:
- continue
- value_offset = map_update_value_offset(insns, index, attr_offset)
- if value_offset is None:
- continue
- if value_offset > len(data_blob) or \
- datasec_size > len(data_blob) - value_offset:
- raise RewriteError(".rodata initializer is outside loader data")
- return value_offset
- raise RewriteError("loader has no initial .rodata map value")
-
-
def encode_nodes(nodes, layout):
if len(nodes) > layout["count"]:
raise RewriteError(
@@ -400,7 +265,7 @@ def rewrite(args):
raise RewriteError("input is not a bounded .upatch file")
magic, version, flags = struct.unpack_from("<QII", artifact, 0)
if magic != 0x53485244554e4150 or version != 1 or flags & 1:
- raise RewriteError("input must be a load upatch in version 1 format")
+ raise RewriteError("input must be a version 1 load upatch")
loader_off, loader_len, sig_off, sig_len, meta_off, meta_len, \
data_off, data_len = struct.unpack_from("<8I", artifact, 304)
if (loader_off > len(artifact) or loader_len > len(artifact) - loader_off or
@@ -411,12 +276,14 @@ def rewrite(args):
raise RewriteError("upatch section bounds are invalid")
data_blob = artifact[data_off:data_off + data_len]
types, variables = read_watch_arrays(data_blob)
+ rodata_offset = struct.unpack_from("<I", artifact, 348)[0]
datasec_id = next(i for i, typ in enumerate(types)
if typ["kind"] == BTF_KIND_DATASEC and
typ["name"] == ".rodata")
datasec_size = types[datasec_id]["size_type"]
- rodata_offset = locate_rodata_data(
- artifact[loader_off:loader_off + loader_len], data_blob, datasec_size)
+ if rodata_offset > len(data_blob) or \
+ datasec_size > len(data_blob) - rodata_offset:
+ raise RewriteError(".rodata initializer is outside loader data")
networks = read_networks(Path(args.iplist))
new_data = bytearray(data_blob)
counts = {}
diff --git a/util/upatch.c b/util/upatch.c
index 7215fcc6..786ff555 100644
--- a/util/upatch.c
+++ b/util/upatch.c
@@ -69,13 +69,13 @@ static int parse_header(const __u8 *m, size_t n,
p += 4;
out->nr_progs = rd_le32(p);
p += 4;
- out->reserved0 = rd_le32(p);
+ out->rodata_data_off = rd_le32(p);
p += 4;
out->type = rd_le32(p);
p += 4;
out->reserved1 = rd_le32(p);
p += 4;
- if (out->reserved0 != 0 || out->reserved1 != 0)
+ if (out->reserved1 != 0)
return -EINVAL;
return 0;
}
@@ -104,6 +104,8 @@ static int validate_bounds(const struct shirudo_upatch_header *h, size_t n)
return -EINVAL;
if (!section_inside(h->data_off, h->data_len, n))
return -EINVAL;
+ if (h->rodata_data_off > h->data_len)
+ return -EINVAL;
if (h->loader_insns_len == 0 || h->signature_len == 0)
return -EINVAL;
return 0;
@@ -206,6 +208,7 @@ static int upatch_parse(const void *data, size_t size,
rc = parse_header(out->map, out->map_size, &out->hdr);
if (rc)
goto err;
+ out->rodata_offset_valid = true;
rc = validate_bounds(&out->hdr, out->map_size);
if (rc)
goto err;
diff --git a/util/upatch.h b/util/upatch.h
index 592d9ad3..be96b1d8 100644
--- a/util/upatch.h
+++ b/util/upatch.h
@@ -23,6 +23,7 @@ struct shirudo_upatch {
const __u8 *map;
size_t map_size;
bool mapped;
+ bool rodata_offset_valid;
const struct shirudo_upatch_decoder_blob *decoder_blob;
__u32 decoder_blob_len;
__u32 nr_decoders;
diff --git a/util/upatch_rodata.c b/util/upatch_rodata.c
index 0e37d724..1ef28775 100644
--- a/util/upatch_rodata.c
+++ b/util/upatch_rodata.c
@@ -296,22 +296,52 @@ static int btf_rodata_btf(const struct shirudo_upatch *u,
if (!found)
return -ENOENT;
view->btf = found;
+ if (u->rodata_offset_valid) {
+ const struct btf_type *sec = btf__type_by_id(found, found_id);
+ __u32 size = sec ? sec->size : 0;
+
+ if (!size || u->hdr.rodata_data_off > u->hdr.data_len ||
+ size > u->hdr.data_len - u->hdr.rodata_data_off) {
+ btf__free(found);
+ view->btf = NULL;
+ return -EINVAL;
+ }
+ view->bytes = (const __u8 *)upatch_data(u) +
+ u->hdr.rodata_data_off;
+ view->data_offset = u->hdr.rodata_data_off;
+ view->size = size;
+ view->type_id = found_id;
+ return 0;
+ }
return find_rodata_data(u, found, found_id, view);
}
-int upatch_rodata_watch_ranges(const struct shirudo_upatch *u,
- struct shirudo_rodata_range ranges[2])
+int upatch_rodata_data_offset(const struct shirudo_upatch *u, __u32 *offset)
+{
+ struct rodata_view view = {};
+ int rc;
+
+ if (!u || !offset)
+ return -EINVAL;
+ rc = btf_rodata_btf(u, &view);
+ if (!rc)
+ *offset = view.data_offset;
+ btf__free(view.btf);
+ return rc;
+}
+
+int upatch_rodata_symbol_range(const struct shirudo_upatch *u,
+ const char *symbol,
+ struct shirudo_rodata_range *range)
{
- static const char *const names[] = {
- "obs_watch_v4", "obs_watch_v6",
- };
struct rodata_view view = {};
const struct btf_type *sec;
const struct btf_var_secinfo *vars;
- __u32 found = 0, i;
+ bool found = false;
+ __u32 i;
int rc;
- if (!u || !ranges)
+ if (!u || !symbol || !symbol[0] || !range)
return -EINVAL;
rc = btf_rodata_btf(u, &view);
if (rc) {
@@ -327,7 +357,7 @@ int upatch_rodata_watch_ranges(const struct shirudo_upatch *u,
for (i = 0; i < BTF_INFO_VLEN(sec->info); i++) {
const struct btf_type *var;
const char *name;
- __u32 j, offset, size;
+ __u32 offset, size;
var = btf__type_by_id(view.btf, vars[i].type);
if (!var || BTF_INFO_KIND(var->info) != BTF_KIND_VAR)
@@ -335,33 +365,44 @@ int upatch_rodata_watch_ranges(const struct shirudo_upatch *u,
name = btf__name_by_offset(view.btf, var->name_off);
if (!name)
continue;
- for (j = 0; j < ARRAY_SIZE(names); j++) {
- if (strcmp(name, names[j]))
- continue;
- if (found & (1u << j)) {
- rc = -EEXIST;
- goto out;
- }
- offset = vars[i].offset;
- size = vars[i].size;
- if (offset > view.size || size > view.size - offset ||
- view.data_offset > u->hdr.data_len ||
- offset > u->hdr.data_len - view.data_offset ||
- size > u->hdr.data_len - view.data_offset - offset) {
- rc = -EINVAL;
- goto out;
- }
- ranges[j].offset = view.data_offset + offset;
- ranges[j].size = size;
- found |= 1u << j;
+ if (strcmp(name, symbol))
+ continue;
+ if (found) {
+ rc = -EEXIST;
+ goto out;
+ }
+ offset = vars[i].offset;
+ size = vars[i].size;
+ if (offset > view.size || size > view.size - offset ||
+ view.data_offset > u->hdr.data_len ||
+ offset > u->hdr.data_len - view.data_offset ||
+ size > u->hdr.data_len - view.data_offset - offset) {
+ rc = -EINVAL;
+ goto out;
}
+ range->offset = view.data_offset + offset;
+ range->size = size;
+ found = true;
}
- rc = found == (1u << ARRAY_SIZE(names)) - 1 ? 0 : -ENOENT;
+ rc = found ? 0 : -ENOENT;
out:
btf__free(view.btf);
return rc;
}
+int upatch_rodata_watch_ranges(const struct shirudo_upatch *u,
+ struct shirudo_rodata_range ranges[2])
+{
+ int rc;
+
+ if (!ranges)
+ return -EINVAL;
+ rc = upatch_rodata_symbol_range(u, "obs_watch_v4", &ranges[0]);
+ if (rc)
+ return rc;
+ return upatch_rodata_symbol_range(u, "obs_watch_v6", &ranges[1]);
+}
+
static __u32 btf_unwrap(const struct btf *btf, __u32 id)
{
const struct btf_type *t;
diff --git a/util/upatch_rodata.h b/util/upatch_rodata.h
index b1e3a69c..52a223e0 100644
--- a/util/upatch_rodata.h
+++ b/util/upatch_rodata.h
@@ -19,6 +19,10 @@ struct shirudo_rodata_range {
int upatch_rodata_print(const struct shirudo_upatch *u, const char *path,
bool json);
+int upatch_rodata_symbol_range(const struct shirudo_upatch *u,
+ const char *symbol,
+ struct shirudo_rodata_range *range);
+int upatch_rodata_data_offset(const struct shirudo_upatch *u, __u32 *offset);
int upatch_rodata_watch_ranges(const struct shirudo_upatch *u,
struct shirudo_rodata_range ranges[2]);