Skip to contentSkip to conversation

contrib/elf2dmp: add ELF dump header checking

PATCH Superseded Viktor Prutyanov 2 participants 2 messages May 19, 2022

v1 of 2 Superseded Latest is v2 →

lore
Share & tools
lore
#0 lore raw

PATCH 1/1 contrib/elf2dmp: add ELF dump header checking

Add ELF header checking to prevent processing input file which is not QEMU guest memory dump or even not ELF.

Resolves: https://gitlab.com/qemu-project/qemu/-/issues/1013

---
 contrib/elf2dmp/qemu_elf.c | 38 ++++++++++++++++++++++++++++++++++++++
 1 file changed, 38 insertions(+)
contrib/elf2dmp/qemu_elf.c +38 -0
index b601b6d7ba..941b573f17 100644
@@ -118,6 +118,39 @@ static void exit_states(QEMU_Elf *qe)
     free(qe->state);
 }
 
+static bool check_ehdr(QEMU_Elf *qe)
+{
+    Elf64_Ehdr *ehdr = qe->map;
+
+    if (sizeof(Elf64_Ehdr) > qe->size) {
+        eprintf("Invalid input dump file size\n");
+        return false;
+    }
+
+    if (memcmp(ehdr->e_ident, ELFMAG, SELFMAG)) {
+        eprintf("Invalid ELF signature, input file is not ELF\n");
+        return false;
+    }
+
+    if (ehdr->e_ident[EI_CLASS] != ELFCLASS64 ||
+            ehdr->e_ident[EI_DATA] != ELFDATA2LSB) {
+        eprintf("Invalid ELF class or byte order, must be 64-bit LE\n");
+        return false;
+    }
+
+    if (ehdr->e_type != ET_CORE) {
+        eprintf("Invalid ELF type, must be core file\n");
+        return false;
+    }
+
+    if (!ehdr->e_phnum) {
+        eprintf("Invalid number of ELF program headers\n");
+        return false;
+    }
+
+    return true;
+}
+
 int QEMU_Elf_init(QEMU_Elf *qe, const char *filename)
 {
     GError *gerr = NULL;
@@ -133,6 +166,11 @@ int QEMU_Elf_init(QEMU_Elf *qe, const char *filename)
     qe->map = g_mapped_file_get_contents(qe->gmf);
     qe->size = g_mapped_file_get_length(qe->gmf);
 
+    if (!check_ehdr(qe)) {
+        err = 1;
+        goto out_unmap;
+    }
+
     if (init_states(qe)) {
         eprintf("Failed to extract QEMU CPU states\n");
         err = 1;
Signature · 1 line
2.35.1
#1 lore raw

contrib/elf2dmp/qemu_elf.c static void exit_states(QEMU_Elf *qe) · line 139

Quoted 5 lines · Viktor Prutyanov
contrib/elf2dmp/qemu_elf.c +5 -0
+    if (ehdr->e_ident[EI_CLASS] != ELFCLASS64 ||
+            ehdr->e_ident[EI_DATA] != ELFDATA2LSB) {
+        eprintf("Invalid ELF class or byte order, must be 64-bit LE\n");
+        return false;
+    }

You could check EI_VERSION == EV_CURRENT too.
You should check e_machine == EM_X86_64.

contrib/elf2dmp/qemu_elf.c static void exit_states(QEMU_Elf *qe) · line 149

Quoted 4 lines
contrib/elf2dmp/qemu_elf.c +4 -0
+    if (!ehdr->e_phnum) {
+        eprintf("Invalid number of ELF program headers\n");
+        return false;
+    }

In init_states(), you appear to assume this number is exactly 1.

r~