libdwfl: Don't try to convert too many dyns in dwfl_link_map_report

Message ID 20211209202642.514141-1-mark@klomp.org
State Committed
Headers
Series libdwfl: Don't try to convert too many dyns in dwfl_link_map_report |

Commit Message

Mark Wielaard Dec. 9, 2021, 8:26 p.m. UTC
  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  |  6 ++++++
 libdwfl/link_map.c | 14 +++++++++++++-
 2 files changed, 19 insertions(+), 1 deletion(-)
  

Patch

diff --git a/libdwfl/ChangeLog b/libdwfl/ChangeLog
index 1f593ac9..856bd335 100644
--- a/libdwfl/ChangeLog
+++ b/libdwfl/ChangeLog
@@ -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
diff --git a/libdwfl/link_map.c b/libdwfl/link_map.c
index 623b3062..ad93501e 100644
--- a/libdwfl/link_map.c
+++ b/libdwfl/link_map.c
@@ -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))