eBPF-based security platform
coccinelle: report a struct that leaves its secret unscrubbed
Tobias Klausercfbd9a702744
diff --git a/.agents/skills/coding/SKILL.md b/.agents/skills/coding/SKILL.mdindex 537250d7..704b95c3 100644--- a/.agents/skills/coding/SKILL.md+++ b/.agents/skills/coding/SKILL.md@@ -160,7 +160,9 @@ code, signing and the package builder, stays out of the core binary.helper with a big buffer is `noinline_for_stack`.- Scrub a key, a seed, a credential or a buffer that held one with`memzero_explicit()` on every path out, error paths included, and- compare it with `memneq_explicit()`.+ compare it with `memneq_explicit()`. Mark a struct member that holds+ one `__sensitive`: a check then wants every local of that struct+ scrubbed the same way, member filled by a parser and all.- All JSON goes through `util/json.c`; text from outside is writtenwith its lossy writers. All logging goes through `pr_*()` to syslog;shirudo writes no log file of its own.diff --git a/Documentation/contribute/code/developer-guide.rst b/Documentation/contribute/code/developer-guide.rstindex cba1e7c5..081c946c 100644--- a/Documentation/contribute/code/developer-guide.rst+++ b/Documentation/contribute/code/developer-guide.rst@@ -566,6 +566,13 @@ can rewrite what it finds does so with ``-D patch``:ECDH shared value, or by ``hex_bytes()``, ``hex_decode()`` or``getrandom()`` when named for a secret, that a path out leaveswithout ``memzero_explicit()``.+ * - ``sensitive_scrub``+ - A local of a struct with a member marked ``__sensitive`` that a+ path out leaves, once the function has used it, without+ ``memzero_explicit()`` of the whole struct or a ``__cleanup()``+ function, and the address of a compound literal of such a struct.+ The structs come from the headers under :src:`include/`,+ :src:`util/` and :src:`tools/` and at the top of the tree.* - ``secret_cmp``- ``memcmp()`` of a secret or what derives from one rather than``memneq_explicit()``.diff --git a/include/shirudo/compiler.h b/include/shirudo/compiler.hindex 5dd755fa..23e2ce26 100644--- a/include/shirudo/compiler.h+++ b/include/shirudo/compiler.h@@ -16,6 +16,12 @@#define noinline __attribute__((noinline))/* A function with a large frame that inlining would add to its caller's. */#define noinline_for_stack noinline+/*+ * A struct member that holds a secret. It expands to nothing; it puts the+ * struct under testing/coccinelle/sensitive_scrub.cocci, which wants every+ * local of it scrubbed on each path out.+ */+#define __sensitive/** clang's -Wimplicit-fallthrough takes the attribute and never a comment.* Token for token as in bpf/lib/misc.h.diff --git a/testing/ci-checks/t0006-check-coccinelle.sh b/testing/ci-checks/t0006-check-coccinelle.shindex b8512bac..61eb69c1 100755--- a/testing/ci-checks/t0006-check-coccinelle.sh+++ b/testing/ci-checks/t0006-check-coccinelle.sh@@ -6,7 +6,7 @@# check with file, line, rule and message, one that does not passes it,# a rule that can rewrite does with -D patch, a rule reads the headers# its #spatch line asks for, on a throwaway repository, each rule taken-# from CERT C, each BPF hazard rule and scrub_missing report a sample of+# from CERT C, each BPF hazard rule and each scrub rule report a sample of# what they refuse, and the tree itself.cd "$(dirname "$0")/.."@@ -415,15 +415,79 @@ int digest_public(const char *hex)EOF}-test_expect_success 'scrub_missing reports its samples and spares the scrubbed form' '+# The same for a struct a header marks: the two returns after its use,+# the compound literal and the scrub of one field alone are reported, the+# return before its use, the scrubbed form and the __cleanup() one not.+write_sensitive_samples() {+ mkdir -p "$1/include" &&+ printf 'struct client {\n\tchar name[32];\n\tchar __sensitive password[64];\n};\n' \+ >"$1/include/client.h" &&+ cat >"$1/sensitive.c" <<'EOF'+int client_left(const char *url)+{+ struct client c = {};++ if (early())+ return -EINVAL;+ if (client_parse(url, &c))+ return -EINVAL;+ return use(&c);+}++int client_scrubbed(const char *url)+{+ struct client c = {};+ int ret = -EINVAL;++ if (early())+ goto out;+ ret = client_parse(url, &c);+ if (!ret)+ ret = use(&c);+out:+ memzero_explicit(&c, sizeof(c));+ return ret;+}++int client_cleanup(const char *url)+{+ struct client c __cleanup(client_clear) = {};++ if (client_parse(url, &c))+ return -EINVAL;+ return use(&c);+}++int client_literal(const char *url)+{+ return client_parse(url, &(struct client){});+}++int client_field(const char *url)+{+ struct client c = {};++ c.name[0] = url[0];+ memzero_explicit(c.password, sizeof(c.password));+ return 0;+}+EOF+}++test_expect_success 'each scrub rule reports its samples and spares the scrubbed forms' 'R4=$W/scrub &&mkdir -p "$R4/testing/coccinelle" &&git init -q "$R4" &&cp "$ROOT/testing/coccinelle/scrub_missing.cocci" \+ "$ROOT/testing/coccinelle/sensitive_scrub.cocci" \"$R4/testing/coccinelle/" &&write_scrub_samples "$R4/samples.c" &&+ write_sensitive_samples "$R4" &&! (cd "$R4" && git add -A && sh "$S") >"$W/out" 2>"$W/err" &&- [ "$(grep -c "^scrub_missing: samples.c:" "$W/err")" = 4 ]+ grep -q "2 of 2 rules matched" "$W/err" &&+ [ "$(grep -c "^scrub_missing: samples.c:" "$W/err")" = 4 ] &&+ [ "$(grep -c "^sensitive_scrub: sensitive.c:" "$W/err")" = 4 ] &&+ [ "$(grep -c "^[a-z_]*: " "$W/err")" = 8 ]'test_expect_success 'the tree passes' 'diff --git a/testing/coccinelle/sensitive_scrub.cocci b/testing/coccinelle/sensitive_scrub.coccinew file mode 100644index 00000000..f11cb350--- /dev/null+++ b/testing/coccinelle/sensitive_scrub.cocci@@ -0,0 +1,99 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo+//+// A local of a struct with a field a header marks __sensitive holds a+// secret once the function uses it, and is scrubbed on every path out of+// the function, the error paths included: by memzero_explicit() of the+// whole struct, or by a __cleanup() function that does, as+// config_clear() and bpm_oci_client_clear() do. A compound literal of+// such a struct has no name to scrub. The struct names come from the+// headers under include/, util/ and tools/ and at the top of the tree,+// so that marking a field brings its struct under the rule.++virtual report++@initialize:python@+@@+import os+import re++STRUCT = re.compile(r"^struct (\w+) \{")++def sensitive_structs():+ paths = [f for f in os.listdir(".") if f.endswith(".h")]+ for top in ("include", "util", "tools"):+ for root, dirs, files in os.walk(top):+ paths += [os.path.join(root, f) for f in files if f.endswith(".h")]+ found = set()+ for path in paths:+ name = None+ with open(path, errors="replace") as f:+ for line in f:+ m = STRUCT.match(line)+ if m:+ name = m.group(1)+ elif line.startswith("}"):+ name = None+ elif name and re.search(r"\b__sensitive\b", line) and \+ not line.lstrip().startswith(("*", "/*")):+ found.add(name)+ return found++SENSITIVE = sensitive_structs()+# Run from elsewhere than the top of the tree, the rule would find no+# struct and pass whatever the code does.+if not SENSITIVE:+ raise RuntimeError("sensitive_scrub: no __sensitive field found; run spatch from the top of the tree")++def declared_with_cleanup(p):+ with open(p[0].file, errors="replace") as f:+ for i, line in enumerate(f, 1):+ if i == int(p[0].line):+ return "__cleanup(" in line+ return False++// What a memzero_explicit() names is no use the secret starts from.+@m@+identifier x;+position pm;+@@+memzero_explicit(<+... x@pm ...+>, ...)++@m2@+identifier x;+expression E;+position pm;+@@+memzero_explicit(E, <+... x@pm ...+>)++@r exists@+identifier sname : script:python() { sname in SENSITIVE };+identifier x;+position pd, p1 != {m.pm, m2.pm}, p2;+@@+struct sname@pd x;+... when != x+x@p1+... when != memzero_explicit(&x, ...)+return@p2 ...;++@c@+identifier sname : script:python() { sname in SENSITIVE };+position p;+@@+ &(struct sname){...}@p++@script:python depends on report@+x << r.x;+pd << r.pd;+p2 << r.p2;+@@+# The tests hold the throwaway secrets of a test VM.+if not p2[0].file.startswith("testing/") and not declared_with_cleanup(pd):+ coccilib.report.print_report(p2[0], "returns without memzero_explicit() of %s, which holds a secret" % x)++@script:python depends on report@+p << c.p;+@@+if not p[0].file.startswith("testing/"):+ coccilib.report.print_report(p[0], "a compound literal holds a secret that nothing scrubs")diff --git a/util/attest.h b/util/attest.hindex d8423963..ffedb3eb 100644--- a/util/attest.h+++ b/util/attest.h@@ -88,16 +88,16 @@ struct attest_expect {__u32 pcr_expect_mask;__u8 pcrs[24][32];bool have_credential;- __u8 credential[TPM_CREDENTIAL_LEN];+ __u8 credential[TPM_CREDENTIAL_LEN] __sensitive;bool have_ek_name;__u8 ek_name[TPM_NAME_LEN];bool require_initrd; /* the binding must be the initrd's */- __u32 bind_expect_mask; /* PCR values at binding time */+ __u32 bind_expect_mask; /* PCR values at binding time */__u8 bind_values[24][32];bool have_config_root;__u8 config_root[32];bool have_config_pcr;- __u32 config_pcr;+ __u32 config_pcr;};/*diff --git a/util/bpm_oci.h b/util/bpm_oci.hindex 1323ce77..1b6c020b 100644--- a/util/bpm_oci.h+++ b/util/bpm_oci.h@@ -73,8 +73,8 @@ struct bpm_oci_client {char base_url[BPM_MAX_ENDPOINT];char registry[BPM_MAX_ENDPOINT];char username[BPM_OCI_USERNAME_SIZE];- char password[BPM_OCI_PASSWORD_SIZE];- char token[BPM_OCI_TOKEN_SIZE];+ char password[BPM_OCI_PASSWORD_SIZE] __sensitive;+ char token[BPM_OCI_TOKEN_SIZE] __sensitive;char ca_file[PATH_MAX];struct tls_ca tls_ca;};diff --git a/util/config.h b/util/config.hindex 3c66545b..4937b49c 100644--- a/util/config.h+++ b/util/config.h@@ -30,7 +30,7 @@ struct config {* Owner-hierarchy auth used to define the NV index on TPMs whose* owner auth is set. Empty (len 0) = empty-password session.*/- char tpm_owner_auth[OWNER_AUTH_MAX];+ char tpm_owner_auth[OWNER_AUTH_MAX] __sensitive;size_t tpm_owner_auth_len;/** The TCTI of util/tpm.c, empty for /dev/tpmrm0; the environment