xref: /qemu/contrib/elf2dmp/main.c (revision 370ed600)
1 /*
2  * Copyright (c) 2018 Virtuozzo International GmbH
3  *
4  * This work is licensed under the terms of the GNU GPL, version 2 or later.
5  *
6  */
7 
8 #include "qemu/osdep.h"
9 
10 #include "err.h"
11 #include "addrspace.h"
12 #include "pe.h"
13 #include "pdb.h"
14 #include "kdbg.h"
15 #include "download.h"
16 #include "qemu/win_dump_defs.h"
17 
18 #define SYM_URL_BASE    "https://msdl.microsoft.com/download/symbols/"
19 #define PDB_NAME    "ntkrnlmp.pdb"
20 #define PE_NAME     "ntoskrnl.exe"
21 
22 #define INITIAL_MXCSR   0x1f80
23 
24 typedef struct idt_desc {
25     uint16_t offset1;   /* offset bits 0..15 */
26     uint16_t selector;
27     uint8_t ist;
28     uint8_t type_attr;
29     uint16_t offset2;   /* offset bits 16..31 */
30     uint32_t offset3;   /* offset bits 32..63 */
31     uint32_t rsrvd;
32 } __attribute__ ((packed)) idt_desc_t;
33 
34 static uint64_t idt_desc_addr(idt_desc_t desc)
35 {
36     return (uint64_t)desc.offset1 | ((uint64_t)desc.offset2 << 16) |
37           ((uint64_t)desc.offset3 << 32);
38 }
39 
40 static const uint64_t SharedUserData = 0xfffff78000000000;
41 
42 #define KUSD_OFFSET_SUITE_MASK 0x2d0
43 #define KUSD_OFFSET_PRODUCT_TYPE 0x264
44 
45 #define SYM_RESOLVE(base, r, s) ((s = pdb_resolve(base, r, #s)),\
46     s ? printf(#s" = 0x%016"PRIx64"\n", s) :\
47     eprintf("Failed to resolve "#s"\n"), s)
48 
49 static uint64_t rol(uint64_t x, uint64_t y)
50 {
51     return (x << y) | (x >> (64 - y));
52 }
53 
54 /*
55  * Decoding algorithm can be found in Volatility project
56  */
57 static void kdbg_decode(uint64_t *dst, uint64_t *src, size_t size,
58         uint64_t kwn, uint64_t kwa, uint64_t kdbe)
59 {
60     size_t i;
61     assert(size % sizeof(uint64_t) == 0);
62     for (i = 0; i < size / sizeof(uint64_t); i++) {
63         uint64_t block;
64 
65         block = src[i];
66         block = rol(block ^ kwn, (uint8_t)kwn);
67         block = __builtin_bswap64(block ^ kdbe) ^ kwa;
68         dst[i] = block;
69     }
70 }
71 
72 static KDDEBUGGER_DATA64 *get_kdbg(uint64_t KernBase, struct pdb_reader *pdb,
73         struct va_space *vs, uint64_t KdDebuggerDataBlock)
74 {
75     const char OwnerTag[4] = "KDBG";
76     KDDEBUGGER_DATA64 *kdbg = NULL;
77     DBGKD_DEBUG_DATA_HEADER64 kdbg_hdr;
78     bool decode = false;
79     uint64_t kwn, kwa, KdpDataBlockEncoded;
80 
81     if (va_space_rw(vs,
82                 KdDebuggerDataBlock + offsetof(KDDEBUGGER_DATA64, Header),
83                 &kdbg_hdr, sizeof(kdbg_hdr), 0)) {
84         eprintf("Failed to extract KDBG header\n");
85         return NULL;
86     }
87 
88     if (memcmp(&kdbg_hdr.OwnerTag, OwnerTag, sizeof(OwnerTag))) {
89         uint64_t KiWaitNever, KiWaitAlways;
90 
91         decode = true;
92 
93         if (!SYM_RESOLVE(KernBase, pdb, KiWaitNever) ||
94                 !SYM_RESOLVE(KernBase, pdb, KiWaitAlways) ||
95                 !SYM_RESOLVE(KernBase, pdb, KdpDataBlockEncoded)) {
96             return NULL;
97         }
98 
99         if (va_space_rw(vs, KiWaitNever, &kwn, sizeof(kwn), 0) ||
100                 va_space_rw(vs, KiWaitAlways, &kwa, sizeof(kwa), 0)) {
101             return NULL;
102         }
103 
104         printf("[KiWaitNever] = 0x%016"PRIx64"\n", kwn);
105         printf("[KiWaitAlways] = 0x%016"PRIx64"\n", kwa);
106 
107         /*
108          * If KDBG header can be decoded, KDBG size is available
109          * and entire KDBG can be decoded.
110          */
111         printf("Decoding KDBG header...\n");
112         kdbg_decode((uint64_t *)&kdbg_hdr, (uint64_t *)&kdbg_hdr,
113                 sizeof(kdbg_hdr), kwn, kwa, KdpDataBlockEncoded);
114 
115         printf("Owner tag is \'%.4s\'\n", (char *)&kdbg_hdr.OwnerTag);
116         if (memcmp(&kdbg_hdr.OwnerTag, OwnerTag, sizeof(OwnerTag))) {
117             eprintf("Failed to decode KDBG header\n");
118             return NULL;
119         }
120     }
121 
122     kdbg = malloc(kdbg_hdr.Size);
123     if (!kdbg) {
124         return NULL;
125     }
126 
127     if (va_space_rw(vs, KdDebuggerDataBlock, kdbg, kdbg_hdr.Size, 0)) {
128         eprintf("Failed to extract entire KDBG\n");
129         free(kdbg);
130         return NULL;
131     }
132 
133     if (!decode) {
134         return kdbg;
135     }
136 
137     printf("Decoding KdDebuggerDataBlock...\n");
138     kdbg_decode((uint64_t *)kdbg, (uint64_t *)kdbg, kdbg_hdr.Size,
139                 kwn, kwa, KdpDataBlockEncoded);
140 
141     va_space_rw(vs, KdDebuggerDataBlock, kdbg, kdbg_hdr.Size, 1);
142 
143     return kdbg;
144 }
145 
146 static void win_context_init_from_qemu_cpu_state(WinContext64 *ctx,
147         QEMUCPUState *s)
148 {
149     WinContext64 win_ctx = (WinContext64){
150         .ContextFlags = WIN_CTX_X64 | WIN_CTX_INT | WIN_CTX_SEG | WIN_CTX_CTL,
151         .MxCsr = INITIAL_MXCSR,
152 
153         .SegCs = s->cs.selector,
154         .SegSs = s->ss.selector,
155         .SegDs = s->ds.selector,
156         .SegEs = s->es.selector,
157         .SegFs = s->fs.selector,
158         .SegGs = s->gs.selector,
159         .EFlags = (uint32_t)s->rflags,
160 
161         .Rax = s->rax,
162         .Rbx = s->rbx,
163         .Rcx = s->rcx,
164         .Rdx = s->rdx,
165         .Rsp = s->rsp,
166         .Rbp = s->rbp,
167         .Rsi = s->rsi,
168         .Rdi = s->rdi,
169         .R8  = s->r8,
170         .R9  = s->r9,
171         .R10 = s->r10,
172         .R11 = s->r11,
173         .R12 = s->r12,
174         .R13 = s->r13,
175         .R14 = s->r14,
176         .R15 = s->r15,
177 
178         .Rip = s->rip,
179         .FltSave = {
180             .MxCsr = INITIAL_MXCSR,
181         },
182     };
183 
184     *ctx = win_ctx;
185 }
186 
187 /*
188  * Finds paging-structure hierarchy base,
189  * if previously set doesn't give access to kernel structures
190  */
191 static int fix_dtb(struct va_space *vs, QEMU_Elf *qe)
192 {
193     /*
194      * Firstly, test previously set DTB.
195      */
196     if (va_space_resolve(vs, SharedUserData)) {
197         return 0;
198     }
199 
200     /*
201      * Secondly, find CPU which run system task.
202      */
203     size_t i;
204     for (i = 0; i < qe->state_nr; i++) {
205         QEMUCPUState *s = qe->state[i];
206 
207         if (is_system(s)) {
208             va_space_set_dtb(vs, s->cr[3]);
209             printf("DTB 0x%016"PRIx64" has been found from CPU #%zu"
210                     " as system task CR3\n", vs->dtb, i);
211             return !(va_space_resolve(vs, SharedUserData));
212         }
213     }
214 
215     /*
216      * Thirdly, use KERNEL_GS_BASE from CPU #0 as PRCB address and
217      * CR3 as [Prcb+0x7000]
218      */
219     if (qe->has_kernel_gs_base) {
220         QEMUCPUState *s = qe->state[0];
221         uint64_t Prcb = s->kernel_gs_base;
222         uint64_t *cr3 = va_space_resolve(vs, Prcb + 0x7000);
223 
224         if (!cr3) {
225             return 1;
226         }
227 
228         va_space_set_dtb(vs, *cr3);
229         printf("DirectoryTableBase = 0x%016"PRIx64" has been found from CPU #0"
230                 " as interrupt handling CR3\n", vs->dtb);
231         return !(va_space_resolve(vs, SharedUserData));
232     }
233 
234     return 1;
235 }
236 
237 static int fill_header(WinDumpHeader64 *hdr, struct pa_space *ps,
238         struct va_space *vs, uint64_t KdDebuggerDataBlock,
239         KDDEBUGGER_DATA64 *kdbg, uint64_t KdVersionBlock, int nr_cpus)
240 {
241     uint32_t *suite_mask = va_space_resolve(vs, SharedUserData +
242             KUSD_OFFSET_SUITE_MASK);
243     int32_t *product_type = va_space_resolve(vs, SharedUserData +
244             KUSD_OFFSET_PRODUCT_TYPE);
245     DBGKD_GET_VERSION64 kvb;
246     WinDumpHeader64 h;
247     size_t i;
248 
249     QEMU_BUILD_BUG_ON(KUSD_OFFSET_SUITE_MASK >= ELF2DMP_PAGE_SIZE);
250     QEMU_BUILD_BUG_ON(KUSD_OFFSET_PRODUCT_TYPE >= ELF2DMP_PAGE_SIZE);
251 
252     if (!suite_mask || !product_type) {
253         return 1;
254     }
255 
256     if (va_space_rw(vs, KdVersionBlock, &kvb, sizeof(kvb), 0)) {
257         eprintf("Failed to extract KdVersionBlock\n");
258         return 1;
259     }
260 
261     h = (WinDumpHeader64) {
262         .Signature = "PAGE",
263         .ValidDump = "DU64",
264         .MajorVersion = kvb.MajorVersion,
265         .MinorVersion = kvb.MinorVersion,
266         .DirectoryTableBase = vs->dtb,
267         .PfnDatabase = kdbg->MmPfnDatabase,
268         .PsLoadedModuleList = kdbg->PsLoadedModuleList,
269         .PsActiveProcessHead = kdbg->PsActiveProcessHead,
270         .MachineImageType = kvb.MachineType,
271         .NumberProcessors = nr_cpus,
272         .BugcheckCode = LIVE_SYSTEM_DUMP,
273         .KdDebuggerDataBlock = KdDebuggerDataBlock,
274         .DumpType = 1,
275         .Comment = "Hello from elf2dmp!",
276         .SuiteMask = *suite_mask,
277         .ProductType = *product_type,
278         .SecondaryDataState = kvb.KdSecondaryVersion,
279         .PhysicalMemoryBlock = (WinDumpPhyMemDesc64) {
280             .NumberOfRuns = ps->block_nr,
281         },
282         .RequiredDumpSpace = sizeof(h),
283     };
284 
285     for (i = 0; i < ps->block_nr; i++) {
286         h.PhysicalMemoryBlock.NumberOfPages +=
287                 ps->block[i].size / ELF2DMP_PAGE_SIZE;
288         h.PhysicalMemoryBlock.Run[i] = (WinDumpPhyMemRun64) {
289             .BasePage = ps->block[i].paddr / ELF2DMP_PAGE_SIZE,
290             .PageCount = ps->block[i].size / ELF2DMP_PAGE_SIZE,
291         };
292     }
293 
294     h.RequiredDumpSpace +=
295             h.PhysicalMemoryBlock.NumberOfPages << ELF2DMP_PAGE_BITS;
296 
297     *hdr = h;
298 
299     return 0;
300 }
301 
302 static int fill_context(KDDEBUGGER_DATA64 *kdbg,
303         struct va_space *vs, QEMU_Elf *qe)
304 {
305     int i;
306 
307     for (i = 0; i < qe->state_nr; i++) {
308         uint64_t Prcb;
309         uint64_t Context;
310         WinContext64 ctx;
311         QEMUCPUState *s = qe->state[i];
312 
313         if (va_space_rw(vs, kdbg->KiProcessorBlock + sizeof(Prcb) * i,
314                     &Prcb, sizeof(Prcb), 0)) {
315             eprintf("Failed to read CPU #%d PRCB location\n", i);
316             return 1;
317         }
318 
319         if (va_space_rw(vs, Prcb + kdbg->OffsetPrcbContext,
320                     &Context, sizeof(Context), 0)) {
321             eprintf("Failed to read CPU #%d ContextFrame location\n", i);
322             return 1;
323         }
324 
325         printf("Filling context for CPU #%d...\n", i);
326         win_context_init_from_qemu_cpu_state(&ctx, s);
327 
328         if (va_space_rw(vs, Context, &ctx, sizeof(ctx), 1)) {
329             eprintf("Failed to fill CPU #%d context\n", i);
330             return 1;
331         }
332     }
333 
334     return 0;
335 }
336 
337 static int pe_get_data_dir_entry(uint64_t base, void *start_addr, int idx,
338         void *entry, size_t size, struct va_space *vs)
339 {
340     const char e_magic[2] = "MZ";
341     const char Signature[4] = "PE\0\0";
342     IMAGE_DOS_HEADER *dos_hdr = start_addr;
343     IMAGE_NT_HEADERS64 nt_hdrs;
344     IMAGE_FILE_HEADER *file_hdr = &nt_hdrs.FileHeader;
345     IMAGE_OPTIONAL_HEADER64 *opt_hdr = &nt_hdrs.OptionalHeader;
346     IMAGE_DATA_DIRECTORY *data_dir = nt_hdrs.OptionalHeader.DataDirectory;
347 
348     QEMU_BUILD_BUG_ON(sizeof(*dos_hdr) >= ELF2DMP_PAGE_SIZE);
349 
350     if (memcmp(&dos_hdr->e_magic, e_magic, sizeof(e_magic))) {
351         return 1;
352     }
353 
354     if (va_space_rw(vs, base + dos_hdr->e_lfanew,
355                 &nt_hdrs, sizeof(nt_hdrs), 0)) {
356         return 1;
357     }
358 
359     if (memcmp(&nt_hdrs.Signature, Signature, sizeof(Signature)) ||
360             file_hdr->Machine != 0x8664 || opt_hdr->Magic != 0x020b) {
361         return 1;
362     }
363 
364     if (va_space_rw(vs,
365                 base + data_dir[idx].VirtualAddress,
366                 entry, size, 0)) {
367         return 1;
368     }
369 
370     printf("Data directory entry #%d: RVA = 0x%08"PRIx32"\n", idx,
371             (uint32_t)data_dir[idx].VirtualAddress);
372 
373     return 0;
374 }
375 
376 static int write_dump(struct pa_space *ps,
377         WinDumpHeader64 *hdr, const char *name)
378 {
379     FILE *dmp_file = fopen(name, "wb");
380     size_t i;
381 
382     if (!dmp_file) {
383         eprintf("Failed to open output file \'%s\'\n", name);
384         return 1;
385     }
386 
387     printf("Writing header to file...\n");
388 
389     if (fwrite(hdr, sizeof(*hdr), 1, dmp_file) != 1) {
390         eprintf("Failed to write dump header\n");
391         fclose(dmp_file);
392         return 1;
393     }
394 
395     for (i = 0; i < ps->block_nr; i++) {
396         struct pa_block *b = &ps->block[i];
397 
398         printf("Writing block #%zu/%zu to file...\n", i, ps->block_nr);
399         if (fwrite(b->addr, b->size, 1, dmp_file) != 1) {
400             eprintf("Failed to write dump header\n");
401             fclose(dmp_file);
402             return 1;
403         }
404     }
405 
406     return fclose(dmp_file);
407 }
408 
409 static bool pe_check_export_name(uint64_t base, void *start_addr,
410         struct va_space *vs)
411 {
412     IMAGE_EXPORT_DIRECTORY export_dir;
413     const char *pe_name;
414 
415     if (pe_get_data_dir_entry(base, start_addr, IMAGE_FILE_EXPORT_DIRECTORY,
416                 &export_dir, sizeof(export_dir), vs)) {
417         return false;
418     }
419 
420     pe_name = va_space_resolve(vs, base + export_dir.Name);
421     if (!pe_name) {
422         return false;
423     }
424 
425     return !strcmp(pe_name, PE_NAME);
426 }
427 
428 static int pe_get_pdb_symstore_hash(uint64_t base, void *start_addr,
429         char *hash, struct va_space *vs)
430 {
431     const char sign_rsds[4] = "RSDS";
432     IMAGE_DEBUG_DIRECTORY debug_dir;
433     OMFSignatureRSDS rsds;
434     char *pdb_name;
435     size_t pdb_name_sz;
436     size_t i;
437 
438     if (pe_get_data_dir_entry(base, start_addr, IMAGE_FILE_DEBUG_DIRECTORY,
439                 &debug_dir, sizeof(debug_dir), vs)) {
440         eprintf("Failed to get Debug Directory\n");
441         return 1;
442     }
443 
444     if (debug_dir.Type != IMAGE_DEBUG_TYPE_CODEVIEW) {
445         return 1;
446     }
447 
448     if (va_space_rw(vs,
449                 base + debug_dir.AddressOfRawData,
450                 &rsds, sizeof(rsds), 0)) {
451         return 1;
452     }
453 
454     printf("CodeView signature is \'%.4s\'\n", rsds.Signature);
455 
456     if (memcmp(&rsds.Signature, sign_rsds, sizeof(sign_rsds))) {
457         return 1;
458     }
459 
460     pdb_name_sz = debug_dir.SizeOfData - sizeof(rsds);
461     pdb_name = malloc(pdb_name_sz);
462     if (!pdb_name) {
463         return 1;
464     }
465 
466     if (va_space_rw(vs, base + debug_dir.AddressOfRawData +
467                 offsetof(OMFSignatureRSDS, name), pdb_name, pdb_name_sz, 0)) {
468         free(pdb_name);
469         return 1;
470     }
471 
472     printf("PDB name is \'%s\', \'%s\' expected\n", pdb_name, PDB_NAME);
473 
474     if (strcmp(pdb_name, PDB_NAME)) {
475         eprintf("Unexpected PDB name, it seems the kernel isn't found\n");
476         free(pdb_name);
477         return 1;
478     }
479 
480     free(pdb_name);
481 
482     sprintf(hash, "%.08x%.04x%.04x%.02x%.02x", rsds.guid.a, rsds.guid.b,
483             rsds.guid.c, rsds.guid.d[0], rsds.guid.d[1]);
484     hash += 20;
485     for (i = 0; i < 6; i++, hash += 2) {
486         sprintf(hash, "%.02x", rsds.guid.e[i]);
487     }
488 
489     sprintf(hash, "%.01x", rsds.age);
490 
491     return 0;
492 }
493 
494 int main(int argc, char *argv[])
495 {
496     int err = 0;
497     QEMU_Elf qemu_elf;
498     struct pa_space ps;
499     struct va_space vs;
500     QEMUCPUState *state;
501     idt_desc_t first_idt_desc;
502     uint64_t KernBase;
503     void *nt_start_addr = NULL;
504     WinDumpHeader64 header;
505     char pdb_hash[34];
506     char pdb_url[] = SYM_URL_BASE PDB_NAME
507         "/0123456789ABCDEF0123456789ABCDEFx/" PDB_NAME;
508     struct pdb_reader pdb;
509     uint64_t KdDebuggerDataBlock;
510     KDDEBUGGER_DATA64 *kdbg;
511     uint64_t KdVersionBlock;
512     bool kernel_found = false;
513 
514     if (argc != 3) {
515         eprintf("usage:\n\t%s elf_file dmp_file\n", argv[0]);
516         return 1;
517     }
518 
519     if (QEMU_Elf_init(&qemu_elf, argv[1])) {
520         eprintf("Failed to initialize QEMU ELF dump\n");
521         return 1;
522     }
523 
524     if (pa_space_create(&ps, &qemu_elf)) {
525         eprintf("Failed to initialize physical address space\n");
526         err = 1;
527         goto out_elf;
528     }
529 
530     state = qemu_elf.state[0];
531     printf("CPU #0 CR3 is 0x%016"PRIx64"\n", state->cr[3]);
532 
533     va_space_create(&vs, &ps, state->cr[3]);
534     if (fix_dtb(&vs, &qemu_elf)) {
535         eprintf("Failed to find paging base\n");
536         err = 1;
537         goto out_elf;
538     }
539 
540     printf("CPU #0 IDT is at 0x%016"PRIx64"\n", state->idt.base);
541 
542     if (va_space_rw(&vs, state->idt.base,
543                 &first_idt_desc, sizeof(first_idt_desc), 0)) {
544         eprintf("Failed to get CPU #0 IDT[0]\n");
545         err = 1;
546         goto out_ps;
547     }
548     printf("CPU #0 IDT[0] -> 0x%016"PRIx64"\n", idt_desc_addr(first_idt_desc));
549 
550     KernBase = idt_desc_addr(first_idt_desc) & ~(ELF2DMP_PAGE_SIZE - 1);
551     printf("Searching kernel downwards from 0x%016"PRIx64"...\n", KernBase);
552 
553     for (; KernBase >= 0xfffff78000000000; KernBase -= ELF2DMP_PAGE_SIZE) {
554         nt_start_addr = va_space_resolve(&vs, KernBase);
555         if (!nt_start_addr) {
556             continue;
557         }
558 
559         if (*(uint16_t *)nt_start_addr == 0x5a4d) { /* MZ */
560             if (pe_check_export_name(KernBase, nt_start_addr, &vs)) {
561                 kernel_found = true;
562                 break;
563             }
564         }
565     }
566 
567     if (!kernel_found) {
568         eprintf("Failed to find NT kernel image\n");
569         err = 1;
570         goto out_ps;
571     }
572 
573     printf("KernBase = 0x%016"PRIx64", signature is \'%.2s\'\n", KernBase,
574             (char *)nt_start_addr);
575 
576     if (pe_get_pdb_symstore_hash(KernBase, nt_start_addr, pdb_hash, &vs)) {
577         eprintf("Failed to get PDB symbol store hash\n");
578         err = 1;
579         goto out_ps;
580     }
581 
582     sprintf(pdb_url, "%s%s/%s/%s", SYM_URL_BASE, PDB_NAME, pdb_hash, PDB_NAME);
583     printf("PDB URL is %s\n", pdb_url);
584 
585     if (download_url(PDB_NAME, pdb_url)) {
586         eprintf("Failed to download PDB file\n");
587         err = 1;
588         goto out_ps;
589     }
590 
591     if (pdb_init_from_file(PDB_NAME, &pdb)) {
592         eprintf("Failed to initialize PDB reader\n");
593         err = 1;
594         goto out_pdb_file;
595     }
596 
597     if (!SYM_RESOLVE(KernBase, &pdb, KdDebuggerDataBlock) ||
598             !SYM_RESOLVE(KernBase, &pdb, KdVersionBlock)) {
599         err = 1;
600         goto out_pdb;
601     }
602 
603     kdbg = get_kdbg(KernBase, &pdb, &vs, KdDebuggerDataBlock);
604     if (!kdbg) {
605         err = 1;
606         goto out_pdb;
607     }
608 
609     if (fill_header(&header, &ps, &vs, KdDebuggerDataBlock, kdbg,
610             KdVersionBlock, qemu_elf.state_nr)) {
611         err = 1;
612         goto out_kdbg;
613     }
614 
615     if (fill_context(kdbg, &vs, &qemu_elf)) {
616         err = 1;
617         goto out_kdbg;
618     }
619 
620     if (write_dump(&ps, &header, argv[2])) {
621         eprintf("Failed to save dump\n");
622         err = 1;
623         goto out_kdbg;
624     }
625 
626 out_kdbg:
627     free(kdbg);
628 out_pdb:
629     pdb_exit(&pdb);
630 out_pdb_file:
631     unlink(PDB_NAME);
632 out_ps:
633     pa_space_destroy(&ps);
634 out_elf:
635     QEMU_Elf_exit(&qemu_elf);
636 
637     return err;
638 }
639