handle_buildid_r_match stat()ed the DB-recorded archive path and then
let popen()/fopen() re-open it. A local writer in a scanned tree could
swap the file (or plant a symlink) between the check and the open, so
a remote buildid query could serve content that was never validated.

Open the archive once with O_NOFOLLOW, fstat that descriptor and
compare its mtime with the recorded one, and hand the validated
descriptor to the decoder or to fdopen() instead of re-opening the
path.

Signed-off-by: Mohammed Mustafa <[email protected]>
---
 debuginfod/debuginfod.cxx | 39 ++++++++++++++++++++++++++++++++++++---
 1 file changed, 36 insertions(+), 3 deletions(-)

diff --git a/debuginfod/debuginfod.cxx b/debuginfod/debuginfod.cxx
index 99b1f2b9..f23d42c0 100644
--- a/debuginfod/debuginfod.cxx
+++ b/debuginfod/debuginfod.cxx
@@ -1860,22 +1860,55 @@ handle_buildid_r_match (bool internal_req_p,
         archive_extension = arch.first;
         archive_decoder = arch.second;
       }
+  /* Do not let the decoder re-open a path that can be swapped between the
+     stat() above and the open below.  Open the archive once with O_NOFOLLOW,
+     validate the very descriptor we will read, and hand that descriptor to
+     the decoder (or to fdopen for the "cat" case).  */
+  int archive_flags = O_RDONLY;
+#ifdef O_NOFOLLOW
+  archive_flags |= O_NOFOLLOW;
+#endif
+  int archive_fd = open (b_source0.c_str(), archive_flags);
+  if (archive_fd < 0)
+    throw libc_exception (errno, string("open ") + b_source0);
+
+  struct stat archive_st;
+  if (fstat (archive_fd, &archive_st) != 0
+      || (int64_t) archive_st.st_mtime != b_mtime)
+    {
+      close (archive_fd);
+      return 0;
+    }
+
   FILE* fp;
   defer_dtor<FILE*,int>::dtor_fn dfn;
   if (archive_decoder != "cat")
     {
-      string popen_cmd = archive_decoder + " " + shell_escape(b_source0);
+#ifdef __linux__
+      /* popen() forks, so the child inherits archive_fd and /proc/self/fd/N
+        refers to the descriptor validated above in the child as well.  */
+      string archive_path = "/proc/self/fd/" + to_string (archive_fd);
+#else
+      string archive_path = b_source0;
+#endif
+      string popen_cmd = archive_decoder + " " + shell_escape(archive_path);
       fp = popen (popen_cmd.c_str(), "r"); // "e" O_CLOEXEC?
       dfn = pclose;
+      /* The child has its own copy of the descriptor; the parent is done
+        with its copy once popen has forked.  */
+      close (archive_fd);
       if (fp == NULL)
         throw libc_exception (errno, string("popen ") + popen_cmd);
     }
   else
     {
-      fp = fopen (b_source0.c_str(), "r");
+      fp = fdopen (archive_fd, "r");
       dfn = fclose;
       if (fp == NULL)
-        throw libc_exception (errno, string("fopen ") + b_source0);
+        {
+          close (archive_fd);
+          throw libc_exception (errno, string("fdopen ") + b_source0);
+        }
     }
   defer_dtor<FILE*,int> fp_closer (fp, dfn);

-- 
2.56.1

Reply via email to