Blob Blame History Raw
From 688fb0e85551eb6f05e54c3df20ae325f4b88224 Mon Sep 17 00:00:00 2001
From: Jakub Filak <jfilak@redhat.com>
Date: Thu, 16 Apr 2015 11:17:20 +0200
Subject: [PATCH] lib: make the dump proc data functions more robust

dump_fd_info and dump_proc_diff are being called from processes running
under root permissions, so these functions must allow callers to
atomically created the destination file and update the ownership of that
file.

Related: #1211835

Signed-off-by: Jakub Filak <jfilak@redhat.com>
---
 src/include/internal_libreport.h |  2 ++
 src/lib/get_cmdline.c            | 29 ++++++++++++++++++++++++++---
 2 files changed, 28 insertions(+), 3 deletions(-)

diff --git a/src/include/internal_libreport.h b/src/include/internal_libreport.h
index 11c18d9..99f2fe1 100644
--- a/src/include/internal_libreport.h
+++ b/src/include/internal_libreport.h
@@ -641,6 +641,8 @@ char* get_cwd(pid_t pid);
 char* get_rootdir(pid_t pid);
 #define get_fsuid libreport_get_fsuid
 int get_fsuid(const char *proc_pid_status);
+#define dump_fd_info_ext libreport_dump_fd_info_ext
+int dump_fd_info_ext(const char *dest_filename, const char *proc_pid_fd_path, uid_t uid, gid_t gid);
 #define dump_fd_info libreport_dump_fd_info
 int dump_fd_info(const char *dest_filename, const char *proc_pid_fd_path);
 
diff --git a/src/lib/get_cmdline.c b/src/lib/get_cmdline.c
index 2e362c5..c55de30 100644
--- a/src/lib/get_cmdline.c
+++ b/src/lib/get_cmdline.c
@@ -213,7 +213,7 @@ int get_fsuid(const char *proc_pid_status)
     return fs_uid;
 }
 
-int dump_fd_info(const char *dest_filename, const char *proc_pid_fd_path)
+int dump_fd_info_ext(const char *dest_filename, const char *proc_pid_fd_path, uid_t uid, gid_t gid)
 {
     DIR *proc_fd_dir = NULL;
     int proc_fdinfo_fd = -1;
@@ -237,7 +237,7 @@ int dump_fd_info(const char *dest_filename, const char *proc_pid_fd_path)
         goto dumpfd_cleanup;
     }
 
-    stream = fopen(dest_filename, "w");
+    stream = fopen(dest_filename, "wex");
     if (!stream)
     {
         r = -ENOMEM;
@@ -295,7 +295,25 @@ dumpfd_next_fd:
 
 dumpfd_cleanup:
     errno = 0;
-    fclose(stream);
+
+    if (stream != NULL)
+    {
+        if (uid != (uid_t)-1L)
+        {
+            const int stream_fd = fileno(stream);
+            r = fchown(stream_fd, uid, gid);
+            if (r < 0)
+            {
+                perror_msg("Can't change '%s' ownership to %lu:%lu", dest_filename, (long)uid, (long)gid);
+                fclose(stream);
+                unlink(dest_filename);
+                stream = NULL;
+            }
+        }
+
+        if (stream != NULL)
+            fclose(stream);
+    }
 
     if (r == 0 && errno != 0)
         r = -errno;
@@ -306,3 +324,8 @@ dumpfd_cleanup:
 
     return r;
 }
+
+int dump_fd_info(const char *dest_filename, const char *proc_pid_fd_path)
+{
+    return dump_fd_info_ext(dest_filename, proc_pid_fd_path, /*UID*/-1, /*GID*/-1);
+}
-- 
2.1.0