Skip to content

eBPF-based security platform

coccinelle: refuse a map value read after its entry is deleted

Mahe Tardye41f225c163a
diff --git a/.github/scripts/check-spdx.sh b/.github/scripts/check-spdx.sh
index 6a829236..92176fac 100755
--- a/.github/scripts/check-spdx.sh
+++ b/.github/scripts/check-spdx.sh
@@ -5,8 +5,9 @@
# .github/scripts/check-spdx.sh -- verify the SPDX-License-Identifier tags of the
# tracked sources against the licensing rules in AGENTS.md: every source
# file carries a tag in the kernel's form for its type, the expression is
-# BSD-2-Clause or GPL-2.0 OR BSD-2-Clause, and everything compiled into a
-# BPF object, the headers it includes too, and every source a Beefile
+# BSD-2-Clause or GPL-2.0 OR BSD-2-Clause, or the upstream one of a file
+# carried from another project, and everything compiled into a BPF
+# object, the headers it includes too, and every source a Beefile
# packages carries the dual licence.
#
# .github/scripts/check-spdx.sh
@@ -58,6 +59,17 @@ vendor_ok() {
return 1
}
+# A file carried from another project outside vendor/ keeps its upstream
+# tag, which offers the BSD-2-Clause branch shirudo takes it under:
+# bpf_map_use_after_delete.cocci comes from tetragon.
+carried_ok() {
+ case "$1:$2" in
+ 'testing/coccinelle/bpf_map_use_after_delete.cocci:(GPL-2.0-only OR BSD-2-Clause)')
+ return 0 ;;
+ esac
+ return 1
+}
+
check_vendor() {
f=$1
l1=''
@@ -156,8 +168,10 @@ check_file() {
"$BSD"|"$DUAL")
;;
*)
- report "$f" "licence expression '$expr' is neither '$BSD' nor '$DUAL'"
- return ;;
+ carried_ok "$f" "$expr" || {
+ report "$f" "licence expression '$expr' is neither '$BSD' nor '$DUAL'"
+ return
+ } ;;
esac
expected="${prefix}SPDX-License-Identifier: ${expr}${suffix}"
if [ "$line" != "$expected" ]; then
diff --git a/AGENTS.md b/AGENTS.md
index e3c7c1e7..0fe99e45 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -372,9 +372,10 @@ one usually still compiles and passes tests.
on every kernel: update a value other CPUs share, of a map that is not
per-CPU or in inode, socket or cgroup storage, with
`__sync_fetch_and_add()` and its kin; insert a missing key with
- `BPF_NOEXIST` and look it up again on `-EEXIST`; check every
- compare-and-swap result, as a failed one changes and orders nothing;
- publish a filled record with
+ `BPF_NOEXIST` and look it up again on `-EEXIST`; read or copy a map
+ value before deleting its entry, as the map hands the element to the
+ next update at once; check every compare-and-swap result, as a failed
+ one changes and orders nothing; publish a filled record with
`__atomic_store_n(&p, v, __ATOMIC_RELEASE)` or a value-returning
atomic, never `WRITE_ONCE()`, and read it through `READ_ONCE()` and an
address dependency, or a load-acquire where the code compares the index
@@ -522,8 +523,10 @@ one usually still compiles and passes tests.
from `<shirudo/byteorder.h>`. `.github/scripts/check-coccinelle.sh`
runs the semantic patches in `testing/coccinelle/`, each a pattern the
tree is kept free of, and fails on any match; a pattern worth refusing
- for good gets a rule there, written from scratch, with the tree fixed
- first. CI runs all five on every pull request,
+ for good gets a rule there, written from scratch or carried with its
+ SPDX and copyright lines from a project that offers it with a
+ BSD-2-Clause branch, with the tree fixed first. CI runs all five on
+ every pull request,
and `.github/scripts/build-commits.sh <range>` builds every commit of
a pull request on its own; run them before handing work over.
- Shell that a workflow runs lives in `.github/scripts/`, not inline in
diff --git a/Documentation/contribute/code/developer-guide.rst b/Documentation/contribute/code/developer-guide.rst
index e3051fd8..061af800 100644
--- a/Documentation/contribute/code/developer-guide.rst
+++ b/Documentation/contribute/code/developer-guide.rst
@@ -655,17 +655,23 @@ can rewrite what it finds does so with ``-D patch``:
* - ``bpf_user_double_fetch``
- Two reads of the same user address, between which the memory can
change.
+ * - ``bpf_map_use_after_delete``
+ - A map value read through the pointer a lookup returned after
+ ``bpf_map_delete_elem()`` removed an entry of the same map, whose
+ element another update can already have taken.
A new pattern worth refusing gets a rule: write it from scratch under
-the BSD-2-Clause, with a header that says why the pattern is refused,
-fix the tree in the commits before it, and add it to the table. A rule
-exists only to run in CI. Where the tree gives it no match, add a case
-of what it refuses to ``t0006-check-coccinelle``, which shows that it
-matches.
-``check-coccinelle.sh`` runs a rule without the headers a file
-includes, which keeps it fast but leaves the types they declare
-unknown. A rule that needs them, as ``sizeof_ptr`` needs the type of a
-struct member, names its include options on a ``#spatch`` line.
+the BSD-2-Clause, or carry one from a project that offers it with a
+BSD-2-Clause branch, keeping its SPDX and copyright lines and naming it
+in ``check-spdx.sh``, as ``bpf_map_use_after_delete`` comes from
+tetragon. Give it a header that says why the pattern is refused, fix the
+tree in the commits before it, and add it to the table. A rule exists
+only to run in CI. Where the tree gives it no match, add a case of what
+it refuses to ``t0006-check-coccinelle``, which shows that it matches.
+``check-coccinelle.sh`` runs a rule without the headers a file includes,
+which keeps it fast but leaves the types they declare unknown. A rule
+that needs them, as ``sizeof_ptr`` needs the type of a struct member,
+names its include options on a ``#spatch`` line.
The ``bpf_`` rules read the BPF sources through
:src:`testing/coccinelle/bpf.macros`, which tells Coccinelle what
diff --git a/Documentation/contribute/testing/test-coverage.rst b/Documentation/contribute/testing/test-coverage.rst
index a8c99507..5ba53eb1 100644
--- a/Documentation/contribute/testing/test-coverage.rst
+++ b/Documentation/contribute/testing/test-coverage.rst
@@ -37,7 +37,7 @@ signed config image.
* - ``t0002-check-spdx``
- ``check-spdx.sh``: tag form by file type, the two expressions,
the dual license of BPF sources and package files, vendored
- licenses, and the tree itself
+ licenses, the upstream tag of a carried file, and the tree itself
* - ``t0003-check-style``
- ``check-style.sh``: checkpatch at 100 columns, the block-comment
opener, the subject length, the integer, parser, copy and
diff --git a/Documentation/upatches/write/memory-consistency/hazards.rst b/Documentation/upatches/write/memory-consistency/hazards.rst
index dcfa4d22..f53935a9 100644
--- a/Documentation/upatches/write/memory-consistency/hazards.rst
+++ b/Documentation/upatches/write/memory-consistency/hazards.rst
@@ -106,7 +106,8 @@ kernel.
that a process runs. Not where only ``kprobe`` and ``kretprobe``
programs use it, nor where one guarded program uses it alone.
* - Updates of shared values, inserting a missing key,
- compare-and-swap, reading user memory twice
+ compare-and-swap, using a value after deleting its entry, reading
+ user memory twice
- On every kernel: other CPUs, or another thread, run at the same
time.
* - Publishing a record
@@ -171,6 +172,19 @@ any update made to it in between. Insert with ``BPF_NOEXIST``, and when
it returns ``-EEXIST``, look the key up again and use the entry the
other CPU made. ``bpf_check_then_insert`` refuses the ``BPF_ANY`` form.
+Using a value after deleting its entry
+--------------------------------------
+
+``bpf_map_delete_elem()`` gives a hash map's element back to the map's
+free list at once, without waiting for an RCU grace period. An update on
+this CPU or another one can take it and fill it with another entry while
+a pointer from an earlier lookup still reads it: RCU keeps the memory
+valid, not its contents. Read or copy what the code needs before the
+delete. ``bpf_map_use_after_delete`` refuses a read through the pointer
+after a delete from the same map; it cannot tell whether the two keys
+are equal and takes any delete. Testing the pointer against ``NULL``
+reads nothing and is left alone.
+
Compare-and-swap
----------------
diff --git a/testing/ci-checks/t0002-check-spdx.sh b/testing/ci-checks/t0002-check-spdx.sh
index 9e7f1ff7..e060a63e 100755
--- a/testing/ci-checks/t0002-check-spdx.sh
+++ b/testing/ci-checks/t0002-check-spdx.sh
@@ -5,7 +5,8 @@
# t0002 -- .github/scripts/check-spdx.sh: the tag every source needs, its form
# by file type, the two expressions, the dual licence of everything a
# BPF object compiles and a Beefile ships, the licences vendored C may
-# carry, on a throwaway repository, and the tree itself.
+# carry, the upstream tag of a file carried from another project, on a
+# throwaway repository, and the tree itself.
cd "$(dirname "$0")/.."
. ./test-lib.sh
@@ -63,10 +64,13 @@ put "$R/pkg/p.bpf.c" '// SPDX-License-Identifier: GPL-2.0 OR BSD-2-Clause' \
'#include "vmlinux.h"' '#include "common.h"'
put "$R/pkg/decoders/x.lua" '-- SPDX-License-Identifier: GPL-2.0 OR BSD-2-Clause'
put "$R/pkg/gen.py" '#!/usr/bin/env python3' '# SPDX-License-Identifier: BSD-2-Clause'
+put "$R/testing/coccinelle/bpf_map_use_after_delete.cocci" \
+ '// SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)' \
+ '// Copyright Authors of Tetragon'
test_expect_success 'a tree of well-tagged files passes' '
check "$R" &&
- grep -q "SPDX: 18 files checked" "$W/out"
+ grep -q "SPDX: 19 files checked" "$W/out"
'
B=$W/bad
@@ -96,10 +100,12 @@ put "$B/pkg/gen.py" '# SPDX-License-Identifier: BSD-2-Clause'
put "$B/nolic/Beefile" '[package]' 'name = "x"'
put "$B/vendor/types.h" '/* SPDX-License-Identifier: GPL-2.0 */'
put "$B/vendor/bare.c" 'int x;'
+put "$B/testing/coccinelle/other.cocci" \
+ '// SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)'
test_expect_success 'a tree of badly tagged files fails' '
! check "$B" &&
- grep -q "^16 SPDX problems" "$W/err"
+ grep -q "^17 SPDX problems" "$W/err"
'
test_expect_success 'the form of the tag follows the file type' '
@@ -138,6 +144,10 @@ test_expect_success 'vendored C carries a licence the binaries can take' '
grep -q "^vendor/bare.c: vendored without an SPDX-License-Identifier tag on line 1" "$W/err"
'
+test_expect_success 'only a file carried from another project keeps its upstream tag' '
+ grep -q "^testing/coccinelle/other.cocci: licence expression .(GPL-2.0-only OR BSD-2-Clause). is neither" "$W/err"
+'
+
test_expect_success 'the tree passes' '
(cd "$ROOT" && sh "$S") >"$W/out" 2>"$W/err" &&
grep -q "^SPDX: [0-9]* files checked" "$W/out"
diff --git a/testing/ci-checks/t0006-check-coccinelle.sh b/testing/ci-checks/t0006-check-coccinelle.sh
index 69e2e537..8dd5a419 100755
--- a/testing/ci-checks/t0006-check-coccinelle.sh
+++ b/testing/ci-checks/t0006-check-coccinelle.sh
@@ -149,7 +149,7 @@ test_expect_success 'each rule taken from CERT C reports its sample' '
# One case of each BPF hazard, and beside it the safe form, which no rule
# reports: the count of reports shows the safe forms stay quiet.
BPF_RULES="bpf_map_rmw bpf_cas_unchecked bpf_check_then_insert \
-bpf_publish bpf_user_double_fetch"
+bpf_publish bpf_user_double_fetch bpf_map_use_after_delete"
write_bpf_samples() {
cat >"$1" <<'EOF'
struct {
@@ -275,6 +275,32 @@ void flags_task(struct task_struct *task)
m->flags |= 1;
}
+__u64 read_after_delete(__u32 *k)
+{
+ struct val *v;
+
+ v = bpf_map_lookup_elem(&vals, k);
+ if (!v)
+ return 0;
+ bpf_map_delete_elem(&vals, k);
+ return v->count;
+}
+
+__u64 read_before_delete(__u32 *k)
+{
+ struct val *v;
+ __u64 n;
+
+ v = bpf_map_lookup_elem(&vals, k);
+ if (!v)
+ return 0;
+ n = v->count;
+ bpf_map_delete_elem(&vals, k);
+ if (!v)
+ return 0;
+ return n;
+}
+
struct meta *flags_reassigned(struct sock *sk)
{
struct meta *m = bpf_sk_storage_get(&socks, sk, 0, 0);
@@ -303,8 +329,8 @@ test_expect_success 'each BPF rule reports its sample and spares the safe form'
for r in $BPF_RULES; do
grep -q "^$r: samples.bpf.c:" "$W/err" || exit 1
done &&
- grep -q "5 of 5 rules matched" "$W/err" &&
- [ "$(grep -c "^bpf_[a-z_]*: samples.bpf.c:" "$W/err")" = 6 ]
+ grep -q "6 of 6 rules matched" "$W/err" &&
+ [ "$(grep -c "^bpf_[a-z_]*: samples.bpf.c:" "$W/err")" = 7 ]
'
test_expect_success 'the tree passes' '
diff --git a/testing/coccinelle/bpf_map_use_after_delete.cocci b/testing/coccinelle/bpf_map_use_after_delete.cocci
new file mode 100644
index 00000000..42cbc858
--- /dev/null
+++ b/testing/coccinelle/bpf_map_use_after_delete.cocci
@@ -0,0 +1,49 @@
+// SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)
+// Copyright Authors of Tetragon
+//
+// A hash map element that bpf_map_delete_elem() removes goes back to the
+// map's free list at once, without waiting for an RCU grace period, so an
+// update on this CPU or another one can take it and fill it with another
+// entry while a pointer from an earlier lookup still reads it. RCU keeps
+// the memory valid, not its contents, on every kernel. Read or copy what
+// is needed before the delete. The rule cannot tell whether two keys are
+// equal and takes any delete from the same map; a test of the pointer
+// against NULL or another pointer reads nothing and is left alone.
+#spatch --no-includes --macro-file testing/coccinelle/bpf.macros
+
+virtual report
+
+@r exists@
+attribute name SEC;
+identifier m, p, f, fn;
+expression k1, k2, e, x, i;
+type T;
+position pd, pu;
+@@
+(
+p = bpf_map_lookup_elem(&m, k1);
+|
+T *p = bpf_map_lookup_elem(&m, k1);
+)
+... when != p = e
+bpf_map_delete_elem@pd(&m, k2);
+... when != p = e
+(
+p@pu->f
+|
+ *p@pu
+|
+p@pu[i]
+|
+fn(..., p@pu, ...)
+|
+x = p@pu
+)
+
+@script:python depends on report@
+p << r.p;
+pd << r.pd;
+pu << r.pu;
+@@
+coccilib.report.print_report(pu[0],
+ "%s read after its entry was deleted on line %s: copy what is needed before the delete" % (p, pd[0].line))