libdwfl: Don't try to convert too many dyns in dwfl_link_map_report
authorMark Wielaard <mark@klomp.org>
Thu, 9 Dec 2021 20:24:18 +0000 (21:24 +0100)
committerMark Wielaard <mark@klomp.org>
Fri, 10 Dec 2021 10:11:18 +0000 (11:11 +0100)
When trying to read (corrupt) dynamic entries from a core file we only
want to read and convert the entries we could read. Also make sure we
don't try to allocate too bug a buffer.

Signed-off-by: Mark Wielaard <mark@klomp.org>
libdwfl/ChangeLog
libdwfl/link_map.c

index 1f593ac..856bd33 100644 (file)
@@ -1,3 +1,9 @@
+2021-12-09  Mark Wielaard  <mark@klomp.org>
+
+       * link_map.c (dwfl_link_map_report): Limit dyn_filesz malloc size
+       to max possible. When converting make sure we don't exceed the number
+       of bytes available in either in.d_buf or out.d_buf.
+
 2021-12-08  Mark Wielaard  <mark@klomp.org>
 
        * dwfl_segment_report_module.c (dwfl_segment_report_module): Check
index 623b306..ad93501 100644 (file)
@@ -994,6 +994,17 @@ dwfl_link_map_report (Dwfl *dwfl, const void *auxv, size_t auxv_size,
          if ((*memory_callback) (dwfl, dyn_segndx, &in.d_buf, &in.d_size,
                                  dyn_vaddr, dyn_filesz, memory_callback_arg))
            {
+             size_t entsize = (elfclass == ELFCLASS32
+                               ? sizeof (Elf32_Dyn) : sizeof (Elf64_Dyn));
+             if (unlikely (dyn_filesz > SIZE_MAX / entsize))
+               {
+                 __libdwfl_seterrno (DWFL_E_NOMEM);
+                 return false;
+               }
+             /* We can only process as many bytes as there are in
+                in.d_size. The data might have been truncated.  */
+             if (dyn_filesz > in.d_size)
+               dyn_filesz = in.d_size;
              void *buf = malloc (dyn_filesz);
              Elf32_Dyn (*d32)[dyn_filesz / sizeof (Elf32_Dyn)] = buf;
              Elf64_Dyn (*d64)[dyn_filesz / sizeof (Elf64_Dyn)] = buf;
@@ -1009,7 +1020,8 @@ dwfl_link_map_report (Dwfl *dwfl, const void *auxv, size_t auxv_size,
                  .d_size = dyn_filesz,
                  .d_buf = buf
                };
-             in.d_size = out.d_size;
+             if (in.d_size > out.d_size)
+               in.d_size = out.d_size;
              if (likely ((elfclass == ELFCLASS32
                           ? elf32_xlatetom : elf64_xlatetom)
                          (&out, &in, elfdata) != NULL))