From e5862f3d260f97b124a2ef9787b2df728014f623 Mon Sep 17 00:00:00 2001 From: fl0l0u Date: Sun, 15 Nov 2026 17:24:05 +0000 Subject: [PATCH] place: the profile's tmp name is created, never overwritten The stats file is written as ".tmp." and renamed, so a reader never sees half a file. But the name is built from the PID -- public -- and fopen("w") happily follows a symlink planted at that name and truncates whatever it points at. A local user who guessed the next PID had the serving process overwrite any file that user could name, as the serving user. The tmp file is now opened O_CREAT|O_EXCL|O_NOFOLLOW: no symlink, no reuse of an existing name. A stale tmp of a crashed run -- whose PID a reboot can reuse -- is unlinked and the create retried once, exclusive again; whoever else planted the name wins exactly a refusal. --- core/place/xstats.cpp | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/core/place/xstats.cpp b/core/place/xstats.cpp index acd04b8f..c3c3f57a 100644 --- a/core/place/xstats.cpp +++ b/core/place/xstats.cpp @@ -10,6 +10,7 @@ #include #include #include +#include #include #include @@ -347,9 +348,29 @@ std::string xs_json(const XsSnapshot& s) { int xs_write_atomic(const std::string& path, const std::string& text) { const std::string tmp = path + ".tmp." + std::to_string((long long)getpid()); - FILE* f = std::fopen(tmp.c_str(), "w"); + /* Created fresh, exclusive, never through a symlink. The name is predictable -- the PID + * is public -- and fopen("w") follows links and truncates: a local user pre-creating it + * as a symlink had the serving process overwrite whatever file the link named, as the + * serving user. An existing name, of any kind, is now a refusal. */ + int fd = ::open(tmp.c_str(), O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, 0600); + if (fd < 0 && errno == EEXIST) { + /* A crash can leave our own tmp name behind, and a reboot can reuse the PID; the + * name is then ours to clear, its contents nobody's to overwrite. The retry is + * exclusive again, so whoever else pre-created it wins only a refusal -- we never + * follow it, truncate it, or write through it. */ + ::unlink(tmp.c_str()); + fd = ::open(tmp.c_str(), O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, 0600); + } + if (fd < 0) { + RAD_WARN("--expert-stats: cannot create %s: %s", tmp.c_str(), std::strerror(errno)); + return RAD_E_IO; + } + FILE* f = ::fdopen(fd, "w"); if (!f) { - RAD_WARN("--expert-stats: cannot write %s: %s", tmp.c_str(), std::strerror(errno)); + const int err = errno; + ::close(fd); + ::unlink(tmp.c_str()); + RAD_WARN("--expert-stats: cannot open %s: %s", tmp.c_str(), std::strerror(err)); return RAD_E_IO; } const bool wrote = std::fwrite(text.data(), 1, text.size(), f) == text.size() &&