379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755 | class AddressTranslator:
def __init__(self, dtb, phy):
self.dtb = dtb
self.phy = phy
# Set machine specifics
if self.wordsize == 4:
self.word_type = np.uint32
if self.phy.machine_data["Endianness"] == "big":
self.word_fmt = ">u4"
else:
self.word_fmt = "<u4"
else:
self.word_type = np.uint64
if self.phy.machine_data["Endianness"] == "big":
self.word_fmt = ">u8"
else:
self.word_fmt = "<u8"
self.v2o = None
self.o2v = None
self.pmasks = None
self.minimum_page = 0
def _read_entry(self, idx, entry, lvl):
"""Decode radix tree entry"""
raise NotImplementedError
def _reconstruct_permissions(self, pmask):
"""Reconstruct permission masks from radix tree entry"""
raise NotImplementedError
def _finalize_virt_addr(self, virt_addr, permissions):
"""Apply architecture specific virtual address modifications"""
raise NotImplementedError
def get_data_virt(self, vaddr, size=1):
"""Return data starting from a virtual address"""
size_available, intervals = self.v2o.contains(vaddr, size)
if size_available != size:
return bytes()
ret = bytearray()
for interval in intervals:
_, interval_size, offset = interval
ret.extend(self.elf_buf[offset : offset + interval_size].tobytes())
return ret
def get_data_phy(self, paddr, size):
"""Return data starting from a physical address"""
return self.phy.get_data(paddr, size)
def get_data_raw(self, offset, size):
"""Return data starting from an ELF offset"""
return self.phy.get_data_raw(offset, size)
def _explore_radixtree(
self, table_addr, mapping, reverse_mapping, lvl=0, prefix=0, upmask=list()
):
"""Explore the radix tree returning virtual <-> physical mappings"""
table = self.phy.get_data(table_addr, self.table_sizes[lvl])
if not table:
print(
f"Table {hex(table_addr)} size:{self.table_sizes[lvl]} at level {lvl} not in RAM"
)
return
for index, entry in enumerate(iter_unpack(self.unpack_fmt, table)):
is_valid, pmask, phy_addr, page_size = self._read_entry(
index, entry[0], lvl
)
if not is_valid:
continue
virt_addr = prefix | (index << self.shifts[lvl])
pmask = upmask + pmask
if (lvl == self.total_levels - 1) or page_size: # Last radix level or Leaf
# Ignore pages not in RAM (some OSs map more RAM than available) and not memory mapped devices
in_ram = self.phy.in_ram(phy_addr, page_size)
in_mmd = self.phy.in_mmd(phy_addr, page_size)
if not in_ram and not in_mmd:
continue
permissions = self._reconstruct_permissions(pmask)
virt_addr = self._finalize_virt_addr(virt_addr, permissions)
mapping[permissions].append((virt_addr, page_size, phy_addr, in_mmd))
# Add only RAM address to the reverse translation P2V
if in_ram and not in_mmd:
if permissions not in reverse_mapping:
reverse_mapping[permissions] = defaultdict(list)
reverse_mapping[permissions][(phy_addr, page_size)].append(
virt_addr
)
else:
# Lower level entry
self._explore_radixtree(
phy_addr,
mapping,
reverse_mapping,
lvl=lvl + 1,
prefix=virt_addr,
upmask=pmask,
)
def _compact_intervals_virt_offset(self, intervals):
"""Compact intervals if virtual addresses and offsets values are
contigous (virt -> offset)"""
fused_intervals = []
prev_begin = prev_end = prev_offset = -1
for interval in intervals:
begin, end, phy, _ = interval
offset = self.phy.p2o[phy]
if offset == -1:
continue
if prev_end == begin and prev_offset + (prev_end - prev_begin) == offset:
prev_end = end
else:
fused_intervals.append((prev_begin, (prev_end, prev_offset)))
prev_begin = begin
prev_end = end
prev_offset = offset
if prev_begin != begin:
fused_intervals.append((prev_begin, (prev_end, prev_offset)))
else:
offset = self.phy.p2o[phy]
if offset == -1:
print(f"ERROR!! {phy}")
else:
fused_intervals.append((begin, (end, offset)))
return fused_intervals[1:]
def _compact_intervals_permissions(self, intervals):
"""Compact intervals if virtual addresses are contigous and permissions are equals"""
fused_intervals = []
prev_begin = prev_end = -1
prev_pmask = (0, 0)
for interval in intervals:
begin, end, _, pmask = interval
if prev_end == begin and prev_pmask == pmask:
prev_end = end
else:
fused_intervals.append((prev_begin, (prev_end, prev_pmask)))
prev_begin = begin
prev_end = end
prev_pmask = pmask
if prev_begin != begin:
fused_intervals.append((prev_begin, (prev_end, prev_pmask)))
else:
fused_intervals.append((begin, (end, pmask)))
return fused_intervals[1:]
def _reconstruct_mappings(self, table_addr, upmask):
# Explore the radix tree
mapping = defaultdict(list)
reverse_mapping = {}
self._explore_radixtree(table_addr, mapping, reverse_mapping, upmask=upmask)
# Needed for ELF virtual mapping reconstruction
self.reverse_mapping = reverse_mapping
self.mapping = mapping
# Collect all intervals (start, end+1, phy_page, pmask)
intervals = []
for pmask, mapping_p in mapping.items():
if pmask[1] == 0: # Ignore user not accessible pages
print(pmask)
continue
intervals.extend(
[(x[0], x[0] + x[1], x[2], pmask) for x in mapping_p if not x[3]]
) # Ignore MMD
intervals.sort()
if not intervals:
raise Exception
# Fuse intervals in order to reduce the number of elements to speed up
fused_intervals_v2o = self._compact_intervals_virt_offset(intervals)
fused_intervals_permissions = self._compact_intervals_permissions(intervals)
# Offset to virtual is impossible to compact in a easy way due to the
# multiple-to-one mapping. We order the array and use bisection to find
# the possible results and a partial
intervals_o2v = []
for pmasks, d in reverse_mapping.items():
if pmasks[1] != 0: # Ignore user accessible pages
continue
for k, v in d.items():
# We have to translate phy -> offset
offset = self.phy.p2o[k[0]]
if offset == -1: # Ignore unresolvable pages
continue
intervals_o2v.append((offset, k[1] + offset, tuple(v)))
intervals_o2v.sort()
# Fill resolution objects
self.v2o = IMOffsets(*list(zip(*fused_intervals_v2o)))
self.o2v = IMOverlapping(intervals_o2v)
self.pmasks = IMData(*list(zip(*fused_intervals_permissions)))
def export_virtual_memory_elf(self, elf_filename):
"""Create an ELF file containg the virtual address space of the process"""
with open(elf_filename, "wb") as elf_fd:
# Create the ELF header and write it on the file
machine_data = self.phy.get_machine_data()
endianness = machine_data["Endianness"]
machine = machine_data["Architecture"].lower()
# Create ELF main header
if "aarch64" in machine:
e_machine = 0xB7
elif "arm" in machine:
e_machine = 0x28
elif "riscv" in machine:
e_machine = 0xF3
elif "x86_64" in machine:
e_machine = 0x3E
elif "386" in machine:
e_machine = 0x03
else:
raise Exception("Unknown architecture")
e_ehsize = 0x40
e_phentsize = 0x38
elf_h = bytearray(e_ehsize)
elf_h[0x00:0x04] = b"\x7fELF" # Magic
elf_h[0x04] = 2 # Elf type
elf_h[0x05] = 1 if endianness == "little" else 2 # Endianness
elf_h[0x06] = 1 # Version
elf_h[0x10:0x12] = 0x4.to_bytes(2, endianness) # e_type
elf_h[0x12:0x14] = e_machine.to_bytes(2, endianness) # e_machine
elf_h[0x14:0x18] = 0x1.to_bytes(4, endianness) # e_version
elf_h[0x34:0x36] = e_ehsize.to_bytes(2, endianness) # e_ehsize
elf_h[0x36:0x38] = e_phentsize.to_bytes(2, endianness) # e_phentsize
elf_fd.write(elf_h)
# For each pmask try to compact intervals in order to reduce the number of segments
intervals = defaultdict(list)
for (kpmask, pmask), intervals_list in self.mapping.items():
print(kpmask, pmask)
if pmask == 0: # Ignore pages not accessible by the process
continue
intervals[pmask].extend(
[(x[0], x[0] + x[1], x[2]) for x in intervals_list if not x[3]]
) # Ignore MMD
intervals[pmask].sort()
if len(intervals[pmask]) == 0:
intervals.pop(pmask)
continue
# Compact them
fused_intervals = []
prev_begin = prev_end = prev_offset = -1
for interval in intervals[pmask]:
begin, end, phy = interval
offset = self.phy.p2o[phy]
if offset == -1:
continue
if (
prev_end == begin
and prev_offset + (prev_end - prev_begin) == offset
):
prev_end = end
else:
fused_intervals.append([prev_begin, prev_end, prev_offset])
prev_begin = begin
prev_end = end
prev_offset = offset
if prev_begin != begin:
fused_intervals.append([prev_begin, prev_end, prev_offset])
else:
offset = self.phy.p2o[phy]
if offset == -1:
print(f"ERROR!! {phy}")
else:
fused_intervals.append([begin, end, offset])
intervals[pmask] = sorted(
fused_intervals[1:], key=lambda x: x[1] - x[0], reverse=True
)
# Write segments in the new file and fill the program header
p_offset = len(elf_h)
offset2p_offset = (
{}
) # Slow but more easy to implement (best way: a tree sort structure able to be updated)
e_phnum = 0
for pmask, interval_list in intervals.items():
e_phnum += len(interval_list)
for idx, interval in enumerate(interval_list):
begin, end, offset = interval
size = end - begin
if offset not in offset2p_offset:
elf_fd.write(self.phy.get_data_raw(offset, size))
if not self.phy.get_data_raw(offset, size):
print(hex(offset), hex(size))
new_offset = p_offset
p_offset += size
for page_idx in range(0, size, self.minimum_page):
offset2p_offset[offset + page_idx] = new_offset + page_idx
else:
new_offset = offset2p_offset[offset]
interval_list[idx].append(
new_offset
) # Assign the new offset in the dest file
# Create the program header containing all the segments (ignoring not in RAM pages)
e_phoff = elf_fd.tell()
p_header = bytes()
for pmask, interval_list in intervals.items():
for begin, end, offset, p_offset in interval_list:
p_filesz = end - begin
# Back convert offset to physical page
p_addr = self.phy.o2p[offset]
assert p_addr != -1
segment_entry = bytearray(e_phentsize)
segment_entry[0x00:0x04] = 0x1.to_bytes(4, endianness) # p_type
segment_entry[0x04:0x08] = pmask.to_bytes(4, endianness) # p_flags
segment_entry[0x10:0x18] = begin.to_bytes(8, endianness) # p_vaddr
segment_entry[0x18:0x20] = p_addr.to_bytes(
8, endianness
) # p_paddr Original physical address
segment_entry[0x28:0x30] = p_filesz.to_bytes(
8, endianness
) # p_memsz
segment_entry[0x08:0x10] = p_offset.to_bytes(
8, endianness
) # p_offset
segment_entry[0x20:0x28] = p_filesz.to_bytes(
8, endianness
) # p_filesz
p_header += segment_entry
# Write the segment header
elf_fd.write(p_header)
s_header_pos = (
elf_fd.tell()
) # Last position written (used if we need to write segment header)
# Modify the ELF header to point to program header
elf_fd.seek(0x20)
elf_fd.write(e_phoff.to_bytes(8, endianness)) # e_phoff
# If we have more than 65535 segments we have create a special Section entry contains the
# number of program entry (as specified in ELF64 specifications)
if e_phnum < 65536:
elf_fd.seek(0x38)
elf_fd.write(e_phnum.to_bytes(2, endianness)) # e_phnum
else:
elf_fd.seek(0x28)
elf_fd.write(s_header_pos.to_bytes(8, endianness)) # e_shoff
elf_fd.seek(0x38)
elf_fd.write(0xFFFF.to_bytes(2, endianness)) # e_phnum
elf_fd.write(0x40.to_bytes(2, endianness)) # e_shentsize
elf_fd.write(0x1.to_bytes(2, endianness)) # e_shnum
section_entry = bytearray(0x40)
section_entry[0x2C:0x30] = e_phnum.to_bytes(4, endianness) # sh_info
elf_fd.seek(s_header_pos)
elf_fd.write(section_entry)
|