Skip to content

eBPF-based security platform

testing: add Coccinelle rules taken from CERT C and ISO/IEC TS 17961

Daniel Borkmanna00dcc80b26d
diff --git a/Documentation/contribute/code/developer-guide.rst b/Documentation/contribute/code/developer-guide.rst
index aa05a9a4..08c6171e 100644
--- a/Documentation/contribute/code/developer-guide.rst
+++ b/Documentation/contribute/code/developer-guide.rst
@@ -622,10 +622,31 @@ can rewrite what it finds does so with ``-D patch``:
- A ``char`` array too short for the NUL of the literal it holds, a
``char`` that keeps what ``getc()`` returns, and ``getenv()``
passed on unchecked, after the CERT C rules.
+ * - ``errno_clobber``
+ - A cleanup call, such as ``close()``, between a failure and the
+ read of its ``errno``, after CERT C ERR30-C.
+ * - ``positive_errno``
+ - A bare error number or ``errno`` returned or put in ``ret``,
+ where a negative error number belongs.
+ * - ``double_close``
+ - A descriptor passed to a call after it was closed, after CERT C
+ FIO46-C.
+ * - ``wrong_test``
+ - A test for a negative value or ``NULL``, right after an
+ assignment, of another variable than the one assigned.
+ * - ``scaled_arith``
+ - A ``sizeof`` added to a pointer to anything wider than a byte,
+ after CERT C ARR39-C.
+ * - ``fclose_unchecked``
+ - ``fclose()`` of a stream opened for writing with its result
+ ignored, after CERT C ERR33-C.
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.
+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
diff --git a/Documentation/contribute/testing/test-coverage.rst b/Documentation/contribute/testing/test-coverage.rst
index 7d4d87af..c9fc140a 100644
--- a/Documentation/contribute/testing/test-coverage.rst
+++ b/Documentation/contribute/testing/test-coverage.rst
@@ -51,7 +51,8 @@ signed config image.
* - ``t0006-check-coccinelle``
- ``check-coccinelle.sh``: a match that fails the check with its
file, line and rule, the vendored sources left out, a rule named
- alone, the rewrite of ``-D patch``, and the tree itself
+ alone, the rewrite of ``-D patch``, a case for each rule taken
+ from CERT C, and the tree itself
* - ``t0007-check-operator-linkage``
- ``check-operator-linkage.sh``: the libraries an operator binary
may link and its own interpreter, another loader, a library
diff --git a/testing/ci-checks/t0006-check-coccinelle.sh b/testing/ci-checks/t0006-check-coccinelle.sh
index 9aeab9b4..8e6a853a 100755
--- a/testing/ci-checks/t0006-check-coccinelle.sh
+++ b/testing/ci-checks/t0006-check-coccinelle.sh
@@ -5,8 +5,8 @@
# t0006 -- .github/scripts/check-coccinelle.sh: a rule that matches fails the
# 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, and the tree
-# itself.
+# its #spatch line asks for, on a throwaway repository, each rule taken
+# from CERT C reports a sample of what it refuses, and the tree itself.
cd "$(dirname "$0")/.."
. ./test-lib.sh
@@ -63,6 +63,88 @@ test_expect_success 'a rule rewrites what it finds with -D patch' '
check
'
+# One case of what each rule taken from CERT C and ISO/IEC TS 17961
+# refuses. A rule the tree gives no match proves nothing until it matches
+# here.
+CERT_RULES="errno_clobber positive_errno double_close wrong_test scaled_arith fclose_unchecked"
+write_samples() {
+ cat >"$1" <<'EOF'
+int clobber_stored(const char *path, int other)
+{
+ int fd = open(path, O_RDONLY);
+
+ close(other);
+ if (fd < 0)
+ return -errno;
+ return fd;
+}
+
+int clobber_tested(int fd)
+{
+ if (fsync(fd)) {
+ close(fd);
+ return -errno;
+ }
+ return 0;
+}
+
+int positive(int x)
+{
+ if (x)
+ return EINVAL;
+ return 0;
+}
+
+int reuse(int fd)
+{
+ close(fd);
+ return fsync(fd);
+}
+
+int untested(const char *path, int other)
+{
+ int fd;
+
+ fd = open(path, O_RDONLY);
+ if (other < 0)
+ return -1;
+ return fd;
+}
+
+unsigned int scaled(unsigned int *words)
+{
+ return *(words + sizeof(struct hdr));
+}
+
+int unflushed(const char *path)
+{
+ FILE *f = fopen(path, "w");
+
+ if (!f)
+ return -1;
+ fputs("x", f);
+ fclose(f);
+ return 0;
+}
+EOF
+}
+
+test_expect_success 'each rule taken from CERT C reports its sample' '
+ R2=$W/samples &&
+ mkdir -p "$R2/testing/coccinelle" &&
+ git init -q "$R2" &&
+ for r in $CERT_RULES; do
+ cp "$ROOT/testing/coccinelle/$r.cocci" "$R2/testing/coccinelle/" ||
+ exit 1
+ done &&
+ write_samples "$R2/samples.c" &&
+ ! (cd "$R2" && git add -A && sh "$S") >"$W/out" 2>"$W/err" &&
+ for r in $CERT_RULES; do
+ grep -q "^$r: samples.c:" "$W/err" || exit 1
+ done &&
+ grep -q "6 of 6 rules matched" "$W/err"
+'
+
test_expect_success 'the tree passes' '
(cd "$ROOT" && sh "$S") >"$W/out" 2>"$W/err" &&
grep -q "rules, no match" "$W/out"
diff --git a/testing/coccinelle/double_close.cocci b/testing/coccinelle/double_close.cocci
new file mode 100644
index 00000000..01d19c87
--- /dev/null
+++ b/testing/coccinelle/double_close.cocci
@@ -0,0 +1,31 @@
+// SPDX-License-Identifier: BSD-2-Clause
+// Copyright (c) 2026 Authors of shirudo
+//
+// A descriptor is not used again once it has been closed: its number may
+// already name another file the process opened since, which a second
+// close(), a read or a write then hits (CERT C FIO46-C).
+
+virtual report
+
+@r exists@
+expression fd, E;
+identifier f;
+position p1, p2;
+@@
+ close@p1(fd);
+ ... when != fd = E
+ when != &fd
+ when != _exit(...)
+ when != exit(...)
+ when != abort()
+ f@p2(..., fd, ...)
+
+@script:python depends on report@
+p1 << r.p1;
+p2 << r.p2;
+fd << r.fd;
+f << r.f;
+@@
+# An element closed in a loop is another one on the next turn.
+if "[" not in fd:
+ coccilib.report.print_report(p2[0], "%s() of %s, closed at line %s" % (f, fd, p1[0].line))
diff --git a/testing/coccinelle/errno_clobber.cocci b/testing/coccinelle/errno_clobber.cocci
new file mode 100644
index 00000000..aad9a78c
--- /dev/null
+++ b/testing/coccinelle/errno_clobber.cocci
@@ -0,0 +1,41 @@
+// SPDX-License-Identifier: BSD-2-Clause
+// Copyright (c) 2026 Authors of shirudo
+//
+// errno describes the last call that failed and is unspecified after one
+// that succeeded (CERT C ERR30-C): a cleanup call between a failure and
+// the read of its errno may change it, and the error reported, or the
+// one a test takes for harmless, is then another. Keep the errno, or the
+// return value that carries it, before the cleanup. The pr_*() functions
+// keep errno.
+
+virtual report
+
+@r exists@
+identifier g = {close, closedir, fclose, unlink, unlinkat, rmdir, munmap,
+ umount, umount2, rename, renameat, fsync, fflush, flock,
+ ftruncate, fchmod, chmod, write, syslog, fprintf, printf,
+ fputs, puts};
+identifier f;
+expression E, E1, X;
+position p1, p;
+@@
+ g@p1(...);
+ ... when != f(...)
+ when != errno = E
+(
+ return X@p;
+|
+ E1 = X@p;
+)
+
+@script:python depends on report@
+p1 << r.p1;
+p << r.p;
+g << r.g;
+X << r.X;
+@@
+import re
+m = re.search(r'\berrno\b', X)
+# A call before errno in the same expression set it: unlink(p) ? -errno : 0.
+if m and not re.search(r'\b[A-Za-z_]\w*\s*\(', X[:m.start()]):
+ coccilib.report.print_report(p[0], "errno read after %s() at line %s, which may have changed it" % (g, p1[0].line))
diff --git a/testing/coccinelle/fclose_unchecked.cocci b/testing/coccinelle/fclose_unchecked.cocci
new file mode 100644
index 00000000..b563b38e
--- /dev/null
+++ b/testing/coccinelle/fclose_unchecked.cocci
@@ -0,0 +1,32 @@
+// SPDX-License-Identifier: BSD-2-Clause
+// Copyright (c) 2026 Authors of shirudo
+//
+// fclose() of a stream written to writes what stdio still buffers and
+// reports a failure to; with its result ignored, a file that was not
+// written passes for one that was (CERT C ERR33-C).
+
+virtual report
+
+@r exists@
+expression F, A, M;
+identifier o = {fopen, fdopen};
+identifier f;
+type T;
+position p;
+@@
+(
+ F = o(A, M);
+ ...
+ fclose@p(F);
+|
+ T f = o(A, M);
+ ...
+ fclose@p(f);
+)
+
+@script:python depends on report@
+p << r.p;
+M << r.M;
+@@
+if any(c in M for c in "wa+"):
+ coccilib.report.print_report(p[0], "fclose() of a stream opened %s for writing, its result ignored" % M)
diff --git a/testing/coccinelle/positive_errno.cocci b/testing/coccinelle/positive_errno.cocci
new file mode 100644
index 00000000..cfc9c47d
--- /dev/null
+++ b/testing/coccinelle/positive_errno.cocci
@@ -0,0 +1,40 @@
+// SPDX-License-Identifier: BSD-2-Clause
+// Copyright (c) 2026 Authors of shirudo
+//
+// A function returns 0 or a negative error number, and its callers test
+// for a value below 0: a bare error number, or errno itself, returned or
+// put in ret, passes as success. errno kept in err for a message is
+// positive by design.
+
+virtual report
+
+@r@
+identifier E = {E2BIG, EACCES, EADDRINUSE, EADDRNOTAVAIL, EAFNOSUPPORT, EAGAIN,
+ EALREADY, EBADF, EBADMSG, EBUSY, ECANCELED, ECHILD, ECONNABORTED,
+ ECONNREFUSED, ECONNRESET, EDEADLK, EDESTADDRREQ, EDOM, EDQUOT,
+ EEXIST, EFAULT, EFBIG, EHOSTUNREACH, EIDRM, EILSEQ, EINPROGRESS,
+ EINTR, EINVAL, EIO, EISCONN, EISDIR, EKEYEXPIRED, EKEYREJECTED,
+ EKEYREVOKED, ELOOP, EMFILE, EMLINK, EMSGSIZE, ENAMETOOLONG,
+ ENETDOWN, ENETRESET, ENETUNREACH, ENFILE, ENOBUFS, ENODATA, ENODEV,
+ ENOENT, ENOEXEC, ENOKEY, ENOLCK, ENOMEM, ENOMSG, ENOPROTOOPT,
+ ENOSPC, ENOSYS, ENOTBLK, ENOTCONN, ENOTDIR, ENOTEMPTY, ENOTSOCK,
+ ENOTSUP, ENOTTY, ENXIO, EOPNOTSUPP, EOVERFLOW, EPERM, EPIPE, EPROTO,
+ EPROTONOSUPPORT, ERANGE, EROFS, ESPIPE, ESRCH, ESTALE, ETIME,
+ ETIMEDOUT, ETXTBSY, EUCLEAN, EWOULDBLOCK, EXDEV, EHWPOISON};
+identifier ret = {ret};
+position p;
+@@
+(
+ return E@p;
+|
+ ret = E@p
+|
+ return errno@p;
+|
+ ret = errno@p
+)
+
+@script:python depends on report@
+p << r.p;
+@@
+coccilib.report.print_report(p[0], "a positive error number where a negative one is returned")
diff --git a/testing/coccinelle/scaled_arith.cocci b/testing/coccinelle/scaled_arith.cocci
new file mode 100644
index 00000000..3cbe497c
--- /dev/null
+++ b/testing/coccinelle/scaled_arith.cocci
@@ -0,0 +1,39 @@
+// SPDX-License-Identifier: BSD-2-Clause
+// Copyright (c) 2026 Authors of shirudo
+//
+// Pointer arithmetic counts elements, not bytes: a sizeof added to a
+// pointer to anything wider than a byte moves it that many elements
+// (CERT C ARR39-C). Step through a byte pointer, or count elements.
+
+virtual report
+
+@r@
+type T, T2;
+T *ptr;
+expression E;
+position p;
+@@
+(
+ ptr + sizeof(E)@p
+|
+ ptr + sizeof(T2)@p
+|
+ ptr - sizeof(E)@p
+|
+ ptr - sizeof(T2)@p
+|
+ ptr += sizeof(E)@p
+|
+ ptr += sizeof(T2)@p
+|
+ ptr -= sizeof(E)@p
+|
+ ptr -= sizeof(T2)@p
+)
+
+@script:python depends on report@
+p << r.p;
+T << r.T;
+@@
+if T.replace("const ", "").strip() not in ("char", "unsigned char", "signed char", "__u8", "__s8", "void"):
+ coccilib.report.print_report(p[0], "a byte count added to a %s pointer" % T)
diff --git a/testing/coccinelle/wrong_test.cocci b/testing/coccinelle/wrong_test.cocci
new file mode 100644
index 00000000..38582956
--- /dev/null
+++ b/testing/coccinelle/wrong_test.cocci
@@ -0,0 +1,27 @@
+// SPDX-License-Identifier: BSD-2-Clause
+// Copyright (c) 2026 Authors of shirudo
+//
+// The test right after an assignment checks what was assigned: in
+// x = f(); if (y < 0) or if (y == NULL), the failure of f() goes through
+// untested. A y that f() fills in through an argument is meant.
+
+virtual report
+
+@r disable is_null, isnt_null1@
+identifier x, y, f;
+expression list es;
+position p;
+statement S;
+@@
+ x = f(es);
+ if (\(y@p == NULL\|y@p < 0\)) S
+
+@script:python depends on report@
+p << r.p;
+x << r.x;
+y << r.y;
+es << r.es;
+@@
+import re
+if x != y and not re.search(r'\b%s\b' % re.escape(y), str(es)):
+ coccilib.report.print_report(p[0], "%s is assigned and %s tested" % (x, y))