eBPF-based security platform
coccinelle: refuse a descriptor left open on a path out
Daniel Borkmann05a00dfd3cac
diff --git a/Documentation/contribute/code/developer-guide.rst b/Documentation/contribute/code/developer-guide.rstindex 06ee052d..7b127914 100644--- a/Documentation/contribute/code/developer-guide.rst+++ b/Documentation/contribute/code/developer-guide.rst@@ -566,6 +566,9 @@ can rewrite what it finds does so with ``-D patch``:* - ``va_end``- A ``va_start()`` or ``va_copy()`` without a ``va_end()`` on apath out.+ * - ``fd_leak``+ - A descriptor left open on a path out once its open succeeded,+ where it is not returned, stored or handed to what closes it.* - ``cloexec``- A descriptor or stream opened without close-on-exec.* - ``banned``diff --git a/testing/coccinelle/fd_leak.cocci b/testing/coccinelle/fd_leak.coccinew file mode 100644index 00000000..7c8562ca--- /dev/null+++ b/testing/coccinelle/fd_leak.cocci@@ -0,0 +1,91 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo+//+// A descriptor that was opened is closed, returned, stored or handed to+// what closes it (fdopen(), fdopendir(), a BIO with BIO_CLOSE) on every+// path out of the function once the open succeeded. A leak on an error+// path goes unnoticed in a one-shot command until a loop or a retry+// runs out of descriptors, and keeps open what it should not.++virtual report++@initialize:python@+@@+def leak(p1, p2):+ coccilib.report.print_report(p2[0], "returns without closing the descriptor opened on line %s" % p1[0].line)++@r exists@+local idexpression int fd;+expression E, E1, E2;+statement S, S1;+identifier opener = {open, openat, socket, accept4, dup, memfd_create,+ eventfd, epoll_create1, inotify_init1, timerfd_create,+ pidfd_open, bpf_obj_get};+position p1, p2;+@@+(+ fd = opener@p1(...);+|+ fd = fcntl@p1(E2, \(F_DUPFD\|F_DUPFD_CLOEXEC\), ...);+)+... when != fd = E1+if (\(fd < 0\|fd == -1\)) S+... when != close(fd)+ when != fd = E1+ when != E = fd+ when != if (fd >= 0) S1+ when != fdopen(fd, ...)+ when != fdopendir(fd)+ when != BIO_new_fd(fd, BIO_CLOSE)+ when != \(_exit\|exit\|abort\)(...)+(+ return fd;+|+ return <+... close(fd) ...+>;+|+ return@p2 ...;+)++@d exists@+identifier fd;+expression E, E1, E2;+statement S, S1;+identifier opener = {open, openat, socket, accept4, dup, memfd_create,+ eventfd, epoll_create1, inotify_init1, timerfd_create,+ pidfd_open, bpf_obj_get};+position p1, p2;+@@+(+ int fd = opener@p1(...);+|+ int fd = fcntl@p1(E2, \(F_DUPFD\|F_DUPFD_CLOEXEC\), ...);+)+... when != fd = E1+if (\(fd < 0\|fd == -1\)) S+... when != close(fd)+ when != fd = E1+ when != E = fd+ when != if (fd >= 0) S1+ when != fdopen(fd, ...)+ when != fdopendir(fd)+ when != BIO_new_fd(fd, BIO_CLOSE)+ when != \(_exit\|exit\|abort\)(...)+(+ return fd;+|+ return <+... close(fd) ...+>;+|+ return@p2 ...;+)++@script:python depends on report@+p1 << r.p1;+p2 << r.p2;+@@+leak(p1, p2)++@script:python depends on report@+p1 << d.p1;+p2 << d.p2;+@@+leak(p1, p2)