[PATCH] stapbpf: Open output file as invoking user
Mikhail Dmitrichenko
m.dmitrichenko222@gmail.com
Wed Nov 18 16:10:52 GMT 2026
stapbpf is installed setuid root and executable by members of the
stapusr group. Its -o option accepts a user-controlled path and
previously opened it with fopen(path, "w") while the effective user ID
was root. A member of stapusr could therefore create or truncate files
that the invoking user cannot write.
Temporarily switch the effective user ID to that of the invoking user
while opening the output file, then restore it before loading BPF
objects. Use O_CLOEXEC to prevent leaking the descriptor across exec.
Preserve the existing behavior of following symbolic links, subject to
the invoking user's file access permissions.
Found by Linux Verification Center (linuxtesting.org) with SVACE.
Signed-off-by: Mikhail Dmitrichenko <m.dmitrichenko222@gmail.com>
---
stapbpf/stapbpf.cxx | 45 ++++++++++++++++++++++++++++++++++++++++++++-
1 file changed, 44 insertions(+), 1 deletion(-)
diff --git a/stapbpf/stapbpf.cxx b/stapbpf/stapbpf.cxx
--- a/stapbpf/stapbpf.cxx
+++ b/stapbpf/stapbpf.cxx
@@ -299,6 +299,49 @@ fatal_elf()
fatal("%s\n", elf_errmsg(-1));
}
+static FILE *
+open_output_file(const char *path)
+{
+ uid_t real_uid = getuid();
+ uid_t saved_euid = geteuid();
+ bool drop_privileges = saved_euid == 0 && real_uid != 0;
+
+ // Open user-selected paths with the invoking user's permissions.
+ if (drop_privileges && seteuid(real_uid) < 0)
+ return NULL;
+
+ int fd = open(path, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0666);
+ int open_errno = fd < 0 ? errno : 0;
+
+ if (drop_privileges)
+ {
+ if (seteuid(saved_euid) < 0)
+ {
+ int restore_errno = errno;
+ if (fd >= 0)
+ close(fd);
+ fatal("failed to restore effective user ID: %s\n",
+ strerror(restore_errno));
+ }
+ }
+
+ if (fd < 0)
+ {
+ errno = open_errno;
+ return NULL;
+ }
+
+ FILE *output = fdopen(fd, "w");
+ if (output == NULL)
+ {
+ int fdopen_errno = errno;
+ close(fd);
+ errno = fdopen_errno;
+ }
+
+ return output;
+}
+
// XXX: based on get_online_cpus()/read_cpu_range()
// in bcc src/cc/common.cc
//
@@ -2202,7 +2245,7 @@ main(int argc, char **argv)
break;
case 'o':
- output_f = fopen(optarg, "w");
+ output_f = open_output_file(optarg);
if (output_f == NULL)
{
fprintf(stderr, "Error opening %s for output: %s\n",
--
2.43.0
More information about the Systemtap
mailing list