From d3af9b57d46cd5a7b0a4688c161b18b4b8d40a28 Mon Sep 17 00:00:00 2001 From: Chris Webb Date: Sun, 26 Nov 2023 18:12:52 +0000 Subject: [PATCH] Restore file ownership when editing with root privilege When a privileged :write is used with -method replace, it silently resets the ownership of files to root:root. Restore the original owner and group in the same way we restore the original permissions. Ownership needs to be restored before permissions to avoid setuid and setgid bits being set while the file is still owned by root, and to avoid them being subsequently lost again on chmod(2). --- src/file.cc | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/file.cc b/src/file.cc index 8fdb4831..a13e5c47 100644 --- a/src/file.cc +++ b/src/file.cc @@ -376,6 +376,8 @@ void write_buffer_to_file(Buffer& buffer, StringView filename, throw runtime_error("replacing file failed"); } + if (replace and geteuid() == 0 and ::chown(zfilename, st.st_uid, st.st_gid) < 0) + throw runtime_error(format("unable to restore file ownership: {}", strerror(errno))); if ((force or replace) and ::chmod(zfilename, st.st_mode) < 0) throw runtime_error(format("unable to restore file permissions: {}", strerror(errno)));