-
Notifications
You must be signed in to change notification settings - Fork 4
/
address_translators.py
1559 lines (1329 loc) · 61.2 KB
/
address_translators.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
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
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import logging
import numpy as np
from bitarray import bitarray
from mappings import (
IntervalsMappingOffsets,
IntervalsMappingOverlapping,
IntervalsMappingData
)
from memory_objects import ELFDump
from struct import iter_unpack
from tqdm import tqdm
from typing import Any, Callable
#################
# Typing #
#################
MappingType = dict[tuple[int, int, int], list[tuple[int, int, int, bool]]]
ReverseMappingType = dict[tuple[int, int, int], dict[tuple[int, int], list[int]]]
#################
# Base Class #
#################
class AddressTranslator:
# Attributes type hinting
wordsize: int
table_address:int
elf_dump: ELFDump
word_type: type
word_format: np.dtype
virtual_to_offset: IntervalsMappingOffsets
offset_to_virtual: IntervalsMappingOverlapping
permissions_mask: IntervalsMappingData
total_levels: int
table_sizes: list[int]
ignored_pages: list[int]
unpack_format: str
shifts: list[int]
mapping: MappingType
reverse_mapping: ReverseMappingType
memory_bitmap: bitarray
pointers: dict[int, int]
reverse_pointers: dict[int, list[int]]
strings: dict[int, str]
minimum_page: int
# Derived functions type hinting
_read_entry: Callable[[int, int, int], tuple[bool, list[list[bool]], int, int]]
_reconstruct_permissions: Callable[[list[list[bool]]], tuple[int, int, int]]
_finalize_virtual_address: Callable[[int, tuple[int, int, int]], int]
def __init__(self, table_address:int, elf_dump:ELFDump) -> None:
self.table_address = table_address
self.elf_dump = elf_dump
# Set machine specifics
if self.wordsize == 4:
self.word_type = np.uint32
if self.elf_dump.machine_data['Endianness'] == 'big':
self.word_format = np.dtype('>u4')
else:
self.word_format = np.dtype('<u4')
else:
self.word_type = np.uint64
if self.elf_dump.machine_data['Endianness'] == 'big':
self.word_format = np.dtype('>u8')
else:
self.word_format = np.dtype('<u8')
def _explore_radixtree(
self,
table_address:int,
mapping:MappingType,
reverse_mapping:ReverseMappingType,
level:int = 0,
prefix:int = 0,
user_permissions_mask:list[list[bool]] = [[]]
) -> tuple[MappingType, ReverseMappingType]:
"""
Explores the radix tree
Returns virtual <-> physical mappings
Returns:
- mapping
- reverse_mapping
"""
# Get table
i = '\t' * level
logging.debug(f'{i}{hex(table_address)} {level}/{self.total_levels - 1}')
table = self.elf_dump.get_data(table_address, self.table_sizes[level])
if not table:
print(f'Table {hex(table_address)} size:{self.table_sizes[level]} at level {level} not in RAM')
return mapping, reverse_mapping
# Ignore physical pages used as placeholders
if table_address in self.ignored_pages and level == self.total_levels - 1:
logging.debug(f'Ignoring {hex(table_address)}')
return mapping, reverse_mapping
for index, entry in enumerate(iter_unpack(self.unpack_format, table)):
is_valid, permissions_mask, physical_address, page_size = self._read_entry(index, entry[0], level)
if not is_valid:
continue
virtual_address = prefix | (index << self.shifts[level])
permissions_mask = user_permissions_mask + permissions_mask
if (level == 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.elf_dump.in_ram(physical_address, page_size)
in_memory_mapped_device = self.elf_dump.in_memory_mapped_device(physical_address, page_size)
if not in_ram and not in_memory_mapped_device:
continue
permissions = self._reconstruct_permissions(permissions_mask)
virtual_address = self._finalize_virtual_address(virtual_address, permissions)
if permissions not in mapping.keys():
mapping[permissions] = []
mapping[permissions].append((virtual_address, page_size, physical_address, in_memory_mapped_device))
# Add only RAM address to the reverse translation P2V
if in_ram and not in_memory_mapped_device:
if permissions not in reverse_mapping.keys():
reverse_mapping[permissions] = dict()
if (physical_address, page_size) not in reverse_mapping[permissions].keys():
reverse_mapping[permissions][(physical_address, page_size)] = []
reverse_mapping[permissions][(physical_address, page_size)].append(virtual_address)
else:
# Lower level entry
mapping, reverse_mapping = self._explore_radixtree(physical_address, mapping, reverse_mapping, level=level+1, prefix=virtual_address, user_permissions_mask=permissions_mask)
return mapping, reverse_mapping
def _compact_intervals_virt_offset(self, intervals:list[tuple[int, int, int, tuple[int, int, int]]]) -> list[tuple[int, tuple[int, int]]]:
"""
Compact intervals if virtual addresses and offsets values are
contiguous (virt -> offset)
"""
fused_intervals:list[tuple[int, tuple[int, int]]] = []
prev_begin = prev_end = prev_offset = -1
begin = end = physical = -1
for interval in intervals:
begin, end, physical, _ = interval
offset = self.elf_dump.physical_to_offset[physical]
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.elf_dump.physical_to_offset[physical]
if offset == -1:
print(f"ERROR!! {physical}")
else:
fused_intervals.append((begin, (end, offset)))
return fused_intervals[1:]
def _compact_intervals_permissions(self, intervals:list[tuple[int, int, int, tuple[int, int, int]]]) -> list[tuple[int, tuple[int, tuple[int, int, int]]]]:
"""
Compact intervals if virtual addresses are contigous and permissions are equals
"""
fused_intervals:list[tuple[int, tuple[int, tuple[int, int, int]]]] = []
prev_begin = prev_end = -1
begin = end = -1
permission_mask = prev_permission_mask = (0, 0, 0)
for interval in intervals:
begin, end, _, permission_mask = interval
if prev_end == begin and prev_permission_mask == permission_mask:
prev_end = end
else:
fused_intervals.append((prev_begin, (prev_end, prev_permission_mask)))
prev_begin = begin
prev_end = end
prev_permission_mask = permission_mask
if prev_begin != begin:
fused_intervals.append((prev_begin, (prev_end, prev_permission_mask)))
else:
fused_intervals.append((begin, (end, permission_mask)))
return fused_intervals[1:]
def _reconstruct_mappings(self, table_address:int, user_permissions_mask:list[list[bool]]) -> None:
# Explore the radix tree
mapping:MappingType = dict()
reverse_mapping:ReverseMappingType = dict()
mapping, reverse_mapping = self._explore_radixtree(
table_address,
mapping,
reverse_mapping,
user_permissions_mask=user_permissions_mask
)
# Needed for ELF virtual mapping reconstruction
self.reverse_mapping = reverse_mapping
self.mapping = mapping
# Collect all intervals (start, end+1, phy_page, pmask)
intervals:list[tuple[int, int, int, tuple[int, int, int]]] = []
for permissions_mask, mapped_values in mapping.items():
if permissions_mask[0] == 0: # Ignore user accessible pages
continue
intervals.extend([
(interval[0], interval[0] + interval[1], interval[2], permissions_mask)
for interval in mapped_values
if not interval[3]
]) # Ignore MMD
intervals.sort()
# Fuse intervals in order to reduce the number of elements to speed up
fused_intervals_virtual_to_offset = 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_offest_to_virtual:list[tuple[int, int, tuple[int, ...]]] = []
for permissions_mask, interval in reverse_mapping.items():
if permissions_mask[0] == 0: # Ignore user accessible pages
continue
for key, value in interval.items():
# We have to translate phy -> offset
offset = self.elf_dump.physical_to_offset[key[0]]
if offset == -1: # Ignore unresolvable pages
continue
intervals_offest_to_virtual.append((offset, key[1] + offset, tuple(value)))
intervals_offest_to_virtual.sort()
# Fill resolution objects
self.virtual_to_offset = IntervalsMappingOffsets(*list(zip(*fused_intervals_virtual_to_offset)))
self.offset_to_virtual = IntervalsMappingOverlapping(intervals_offest_to_virtual)
self.permissions_mask = IntervalsMappingData(*list(zip(*fused_intervals_permissions)))
def create_bitmap(self) -> None:
"""
Create a bitmap starting from the ELF file containing 0 if the byte
is 0, 1 otherwise
"""
print("Creating bitmap...")
self.memory_bitmap = bitarray()
self.memory_bitmap.pack(self.elf_dump.elf_buffer.tobytes())
def _find_pointers_align(self, alignment:int) -> dict[int, int]:
"""
For a fixed align retrieve all valid pointers in dump
"""
# Workaround for alignment
aligned_length = self.elf_dump.elf_buffer.shape[0] - (self.elf_dump.elf_buffer.shape[0] % self.wordsize)
if alignment == 0:
end = aligned_length
else:
end = aligned_length - (self.wordsize - alignment)
# Find all destination addresses which could be valid kernel addresses ignoring too
# little or too big ones (src -> dst)
word_array = self.elf_dump.elf_buffer[alignment:end].view(self.word_format)
min_virtual, max_virtual = self.virtual_to_offset.get_extremes()
logging.debug(f"Min virtual address: {hex(min_virtual)}, Max virtual address: {hex(max_virtual)}")
destinations_index = np.where((word_array >= min_virtual) & (word_array <= max_virtual))[0]
destinations = word_array[destinations_index]
sources_offsets = (destinations_index * self.wordsize) + alignment # This array contains the offset on the file of the dst candidates (the src of the pointer!)
pointers:dict[int,int] = {}
for index, destination in enumerate(tqdm(destinations)):
# Validate dsts
destination = int(destination) # All this conversion is due to a numpy "feature" https://github.com/numpy/numpy/issues/5745
if self.virtual_to_offset[destination] == -1:
continue
# Validate srcs
sources_list = self.offset_to_virtual[int(sources_offsets[index])]
if len(sources_list) > 0:
for source in sources_list:
pointers[source] = destination
return pointers
def retrieve_pointers(self) -> None:
print('Retrieving pointers...')
direct_map:dict[int, int] = dict() # virt1 -> virt2 location virt1 point to virt2 one-to-one
reverse_map:dict[int, list[int]] = dict() # virt2 -> [virt1, ...] location at virt2 is pointed by [virt1, ...] one-to-many
# Monothread not super optimized but it's fast :D (thanks Matteo)
pointers:dict[int, int] = dict()
for alignment in range(self.wordsize):
print(f'Look for pointers with alignement {alignment}...')
new_pointers = self._find_pointers_align(alignment)
print(f'Found {len(new_pointers)} new pointers')
pointers.update(new_pointers)
# Reconstruct dict
direct_map.update(pointers)
for source, destination in pointers.items():
if destination not in reverse_map.keys():
reverse_map[destination] = []
reverse_map[destination].append(source)
self.pointers = direct_map
self.reverse_pointers = reverse_map
def retrieve_strings(self, min_length:int = 3, max_symbols_threshold:float = 0.3) -> None:
# Get strings with physical addresses [(string, paddr), ...]
print("Retrieving strings...")
strings:dict[int, str] = dict()
strings_offsets = self.elf_dump.retrieve_strings_offsets(min_length)
# rw_strings = []
for string in strings_offsets:
value, offset = string
# Ignore strings which are not part of the memory dump (eg, ELF dump constants etc.)
virtual_addresses = self.offset_to_virtual[offset]
if not virtual_addresses:
continue
for virtual_address in virtual_addresses:
# HEURISTICS if there are more than max_symbol_threshold
# symbols ignore it
if sum(not char.isalnum() for char in value)/len(value) >= max_symbols_threshold:
continue
strings[virtual_address] = value
# Add substrings referenced by pointers
for i in range(1, len(value)):
substring_virtual_address = i + virtual_address
if substring_virtual_address in self.reverse_pointers:
# HEURISTICS if there are more than max_symbol_threshold
# symbols percentage ignore it
if sum(not char.isalnum() for char in value[i:])/len(value[i:]) >= max_symbols_threshold:
continue
strings[substring_virtual_address] = value[i:]
self.strings = strings
# self.rw_strings = set(rw_strings)
def export_virtual_memory_elf(
self,
elf_filename:str,
kernel:bool = True,
only_executable:bool = False,
ignore_empties:bool = True
) -> None:
"""
Create an ELF file containg the virtual address space of the kernel/process
"""
print('Converting dump to virtual addresses ELF...')
with open(elf_filename, 'wb') as elf_fd:
# Create the ELF header and write it on the file
machine_data = self.elf_dump.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:dict[int, list[tuple[int, int, int]]] = dict()
for permissions_mask, intervals_list in self.mapping.items():
if not(bool(permissions_mask[1]) ^ kernel): # Select only kernel/process mappings
continue
if kernel:
permission_mask = permissions_mask[0]
else:
permission_mask = permissions_mask[1]
if only_executable and not(bool(permission_mask & 0x1)): # Select only/all executable mappings
continue
if ignore_empties:
for interval in intervals_list:
if interval[3]: # Ignore MMD
continue
offset = self.virtual_to_offset[interval[0]]
if offset == -1:
continue
if not any(self.elf_dump.elf_buffer[offset:offset+interval[1]]): # Filter for empty pages
continue
if not permission_mask in intervals.keys():
intervals[permission_mask] = []
intervals[permission_mask].append((interval[0], interval[0]+interval[1], interval[2]))
else:
intervals[permission_mask].extend([
(interval[0], interval[0]+interval[1], interval[2])
for interval in intervals_list
if not interval[3]
]) # Ignore MMD
intervals[permission_mask].sort()
# Compact them
fused_intervals:list[tuple[int, int, int]] = []
prev_begin = prev_end = prev_offset = -1
begin = end = physical = -1
for interval in intervals[permission_mask]:
begin, end, physical = interval
offset = self.elf_dump.physical_to_offset[physical]
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.elf_dump.physical_to_offset[physical]
if offset == -1:
print(f"ERROR!! {physical}")
else:
fused_intervals.append((begin, end, offset))
intervals[permission_mask] = sorted(fused_intervals[1:], key=lambda x: x[1] - x[0], reverse=True)
# Write segments in the new file and fill the program header
physical_offset = len(elf_h)
offset_to_physical_offset:dict[int, int] = dict() # Slow but more easy to implement (best way: a tree sort structure able to be updated)
elf_physical_total = 0
new_intervals:dict[int, list[tuple[int, int, int, int]]] = dict()
for permission_mask, intervals_list in intervals.items():
elf_physical_total += len(intervals_list)
new_intervals_list:list[tuple[int, int, int, int]] = []
for interval in intervals_list:
begin, end, offset = interval
size = end - begin
if offset not in offset_to_physical_offset:
elf_fd.write(self.elf_dump.get_raw_data(offset, size))
if not self.elf_dump.get_raw_data(offset, size):
print(hex(offset), hex(size))
new_offset = physical_offset
physical_offset += size
for page_index in range(0, size, self.minimum_page):
offset_to_physical_offset[offset + page_index] = new_offset + page_index
else:
new_offset = offset_to_physical_offset[offset]
new_intervals_list.append((begin, end, offset, new_offset))
# Assign the new offset in the dest file
new_intervals[permission_mask] = new_intervals_list
# Create the program header containing all the segments (ignoring not in RAM pages)
e_phoff = elf_fd.tell()
p_header = bytes()
for permission_mask, intervals_list in new_intervals.items():
for begin, end, offset, physical_offset in intervals_list:
# Workaround Ghidra 32 bit
if end == 0xFFFFFFFF + 1 and e_machine == 0x03:
end = 0xFFFFFFFF
p_filesz = end - begin
segment_entry = bytearray(e_phentsize)
segment_entry[0x00:0x04] = 0x1.to_bytes(4, endianness) # p_type
segment_entry[0x04:0x08] = permission_mask.to_bytes(4, endianness) # p_flags
segment_entry[0x10:0x18] = begin.to_bytes(8, endianness) # p_vaddr
segment_entry[0x18:0x20] = offset.to_bytes(8, endianness) # p_paddr Original offset
segment_entry[0x28:0x30] = p_filesz.to_bytes(8, endianness) # p_memsz
segment_entry[0x08:0x10] = physical_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 elf_physical_total < 65536:
elf_fd.seek(0x38)
elf_fd.write(elf_physical_total.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] = elf_physical_total.to_bytes(4, endianness) # sh_info
elf_fd.seek(s_header_pos)
elf_fd.write(section_entry)
#########
# Intel #
#########
class IntelTranslator(AddressTranslator):
@staticmethod
def derive_mmu_settings(mmu_class:type, registers:dict[str, int], max_physical_address:int, ignored_pages:list[int]) -> dict[str, int|bool|list[int]]:
if mmu_class is IntelAMD64:
dtb = ((registers['cr3'] >> 12) & ((1 << (max_physical_address - 12)) - 1)) << 12
elif mmu_class is IntelPAE:
dtb = ((registers['cr3'] >> 5) & (1 << 27) - 1) << 5
elif mmu_class is IntelIA32:
dtb = ((registers['cr3'] >> 12) & (1 << 20) - 1) << 12
max_physical_address = min(max_physical_address, 40)
else:
raise NotImplementedError
return {
'table_address': dtb,
'wp': bool((registers['cr0'] >> 16) & 0x1),
'ac': bool((registers['eflags'] >> 18) & 0x1),
'nxe': bool((registers['efer'] >> 11) & 0x1),
'smep': bool((registers['cr4'] >> 20) & 0x1),
'smap': bool((registers['cr4'] >> 21) & 0x1),
'max_physical_address': max_physical_address,
'ignored_pages': ignored_pages
}
@staticmethod
def derive_translator_class(registers:dict[str, int]) -> type:
pg = bool((registers['cr0'] >> 31) & 0x1)
pae = bool((registers['cr4'] >> 5) & 0x1)
lme = bool((registers['efer'] >> 8) & 0x1)
if pg and pae and lme:
return IntelAMD64
elif pg and pae:
return IntelPAE
elif pg:
return IntelIA32
else:
raise NotImplementedError
def __init__(
self,
table_address:int,
elf_dump:ELFDump,
max_physical_address:int,
wp:bool = False,
ac:bool = False,
nxe:bool = False,
smap:bool = False,
smep:bool = False
) -> None:
super(IntelTranslator, self).__init__(table_address, elf_dump)
self.mphy = max_physical_address
self.wp = wp
self.ac = ac # UNUSED by Fossil
self.smap = smap
self.nxe = nxe
self.smep = smep
self.minimum_page = 0x1000
logging.debug(f"""
Type: {type(self)},
MAX_PHY: {self.mphy},
WP {self.wp},
AC {self.ac},
SMAP {self.smap},
SMEP {self.smep},
NXE {self.nxe},
DTB {hex(self.table_address)}
""")
print('Creating resolution trees...')
self._reconstruct_mappings(self.table_address, user_permissions_mask=[[False, True, True]])
def _finalize_virtual_address(self, virtual_address:int) -> int:
return virtual_address
class IntelIA32(IntelTranslator):
# Attributes type hinting
unpack_format:str
total_levels:int
prefix:int
table_sizes:list[int]
shifts:list[int]
wordsize:int
ignored_pages:list[int]
def __init__(
self,
table_address:int,
elf_dump:ELFDump,
max_physical_address: int,
wp:bool = True,
ac:bool = False,
nxe:bool = False,
smap:bool = False,
smep:bool = False,
ignored_pages:list[int] = []
) -> None:
self.unpack_format = '<I'
self.total_levels = 2
self.prefix = 0x0
self.table_sizes = [0x1000, 0x1000]
self.shifts = [22, 12]
self.wordsize = 4
self.ignored_pages = ignored_pages
super(IntelIA32, self).__init__(table_address, elf_dump, max_physical_address, wp, ac, nxe, smap, smep)
def _read_entry(self, index:int, entry:int, level:int) -> tuple[bool, list[list[bool]], int, int]:
# Return (is_Valid, Permissions flags, Table Address, Size)
# Empty entry
if not (entry & 0x1):
return False, [[]], 0, 0
else:
permission_flags = [[
not bool(entry & 0x4), # K
bool(entry & 0x2), # W
True # X
]]
# Upper tables pointers
if not(entry & 0x80) and (level == 0):
address = ((entry >> 12) & ((1 << 20) - 1)) << 12
return True, permission_flags, address, 0
# Leaf
else:
if level == 0:
address = (((entry >> 13) & ((1 << (self.mphy - 32)) - 1)) << 32) | (((entry >> 22) & ((1 << 10) - 1)) << 22)
else:
address = ((entry >> 12) & ((1 << 20) - 1)) << 12
return True, permission_flags, address, 1 << self.shifts[level]
def _reconstruct_permissions(self, permissions_mask:list[list[bool]]) -> tuple[int, int]:
kernel_flags, write_flags, _ = zip(*permissions_mask)
kernel_flags: tuple[bool, ...]
write_flags: tuple[bool, ...]
# Kernel page in kernel mode
if any(kernel_flags):
read = True
write = all(write_flags) if self.wp else True
execute = True
return read << 2 | write << 1 | int(execute), 0
# User page in kernel mode
else:
read = True if (not self.smap) or (self.smap and self.ac) else False
if not self.wp:
write = True if (not self.smap) or (self.smap and self.ac) else False
else:
write = all(write_flags) if (not self.smap) or (self.smap and self.ac) else False
execute = True
return 0, read << 2 | write << 1 | int(execute)
class IntelPAE(IntelTranslator):
def __init__(
self,
table_address:int,
elf_dump:ELFDump,
max_physical_address:int,
wp:bool = True,
ac:bool = False,
nxe:bool = True,
smap:bool = False,
smep:bool = False,
ignored_pages:list[int] = []
) -> None:
self.unpack_format = "<Q"
self.total_levels = 3
self.prefix = 0x0
self.table_sizes = [0x20, 0x1000, 0x1000]
self.shifts = [30, 21, 12]
self.wordsize = 4
self.ignored_pages = ignored_pages
super(IntelPAE, self).__init__(table_address, elf_dump, max_physical_address, wp, ac, nxe, smap, smep)
def _read_entry(self, index:int, entry:int, level:int) -> tuple[bool, list[list[bool]], int, int]:
# Return (is_Valid, Permissions flags, Table Address, Size)
# Empty entry
if not (entry & 0x1):
return False, [[]], 0, 0
else:
if level == 0:
permissions_flag = [[False, True, True]]
else:
permissions_flag = [[
not bool(entry & 0x4), # K
bool(entry & 0x2), # W
not bool(entry & 0x8000000000000000) # X
]]
# Upper tables pointers
if (not(entry & 0x80) and level < 2) or level == 0: # PDPTE does not have leaf
address = ((entry >> 12) & ((1 << (self.mphy - 12)) - 1)) << 12
return True, permissions_flag, address, 0
# Leaf
else:
address = ((entry >> self.shifts[level]) & ((1 << (self.mphy - self.shifts[level])) - 1)) << self.shifts[level]
return True, permissions_flag, address, 1 << self.shifts[level]
def _reconstruct_permissions(self, permissions_mask:list[list[bool]]) -> tuple[int, int]:
kernel_flags, write_flags, execute_flags = zip(*permissions_mask)
kernel_flags: tuple[bool, ...]
write_flags: tuple[bool, ...]
execute_flags: tuple[bool, ...]
# Kernel page in kernel mode
if any(kernel_flags):
read = True
write = all(write_flags) if self.wp else True
execute = all(execute_flags) if self.nxe else True
return read << 2 | write << 1 | int(execute), 0
# User page in kernel mode
else:
read = True if (not self.smap) or (self.smap and self.ac) else False
if not self.wp:
write = True if (not self.smap) or (self.smap and self.ac) else False
else:
write = all(write_flags) if (not self.smap) or (self.smap and self.ac) else False
if not self.smep:
execute = all(execute_flags) if self.nxe else True
else:
execute = False
return 0, read << 2 | write << 1 | int(execute)
class IntelAMD64(IntelTranslator):
def __init__(
self,
table_address:int,
elf_dump: ELFDump,
max_physical_address: int,
wp:bool = True,
ac:bool = False,
nxe:bool = True,
smap:bool = False,
smep:bool = False,
ignored_pages:list[int] = []
) -> None:
self.unpack_format = "<Q"
self.total_levels = 4
self.prefix = 0xFFFF800000000000
self.table_sizes = [0x1000] * 4
self.shifts = [39, 30, 21, 12]
self.wordsize = 8
self.ignored_pages = ignored_pages
super(IntelAMD64, self).__init__(table_address, elf_dump, max_physical_address, wp, ac, nxe, smap, smep)
def _read_entry(self, index:int, entry:int, level:int) -> tuple[bool, list[list[bool]], int, int]:
# Return (is_Valid, Permissions flags, Table Address, Size)
# Empty entry
if not (entry & 0x1):
return False, [[]], 0, 0
else:
permissions_flags = [[
not bool(entry & 0x4), # K
bool(entry & 0x2), # W
not bool(entry & 0x8000000000000000) # X
]]
# Upper tables pointers
if (not(entry & 0x80) and level < 3) or level == 0: # PTL4 does not have leaf
address = ((entry >> 12) & ((1 << (self.mphy - 12)) - 1)) << 12
return True, permissions_flags, address, 0
# Leaf
else:
address = ((entry >> self.shifts[level]) & ((1 << (self.mphy - self.shifts[level])) - 1)) << self.shifts[level]
return True, permissions_flags, address, 1 << self.shifts[level]
def _reconstruct_permissions(self, permissions_mask:list[list[bool]]) -> tuple[int, int]:
kernel_flags, write_flags, execute_flags = zip(*permissions_mask)
kernel_flags: tuple[bool, ...]
write_flags: tuple[bool, ...]
execute_flags: tuple[bool, ...]
# Kernel page in kernel mode
if any(kernel_flags):
read = True
write = all(write_flags) if self.wp else True
execute = all(execute_flags) if self.nxe else True
return read << 2 | write << 1 | int(execute), 0
# User page in kernel mode
else:
read = True if (not self.smap) or (self.smap and self.ac) else False
if not self.wp:
write = True if (not self.smap) or (self.smap and self.ac) else False
else:
write = all(write_flags) if (not self.smap) or (self.smap and self.ac) else False
if not self.smep:
execute = all(execute_flags) if self.nxe else True
else:
execute = False
return 0, read << 2 | write << 1 | int(execute)
def _finalize_virtual_address(self, virtual_address:int, permissions:tuple[int, int, int]) -> int:
# Canonical address form
if virtual_address & 0x800000000000:
return self.prefix | virtual_address
else:
return virtual_address
#########
# RISCV #
#########
class RISCVTranslator(AddressTranslator):
@staticmethod
def derive_mmu_settings(mmu_class:type, registers:dict[str, int], ignored_pages:list[int]) -> dict[str, int|bool|list[int]]:
if mmu_class is RISCVSV32:
dtb = (registers['satp'] & ((1 << 22) - 1)) << 12
elif mmu_class is RISCVSV39:
dtb = (registers['satp'] & ((1 << 44) - 1)) << 12
else:
raise NotImplementedError
return {
'table_address': dtb,
'Sum': bool((registers['sstatus'] >> 18) & 0x1),
'mxr': bool((registers['sstatus'] >> 19) & 0x1),
'ignored_pages': ignored_pages
}
@staticmethod
def derive_translator_class(registers:dict[str, int]) -> type:
satp = registers['satp']
mode32 = (satp >> 31) & 0x1
mode64 = (satp >> 60) & 0x0F
if mode64 == 8:
return RISCVSV39
elif mode64 > 0:
raise NotImplementedError
if not mode64 and mode32:
return RISCVSV32
else:
raise NotImplementedError
def __init__(self, table_address:int, elf_dump:ELFDump, Sum:bool = True, mxr:bool = True) -> None:
super(RISCVTranslator, self).__init__(table_address, elf_dump)
self.Sum = Sum
self.mxr = mxr
self.minimum_page = 0x1000
print('Creating resolution trees...')
self._reconstruct_mappings(self.table_address, user_permissions_mask=[[False, True, True, True]])
def _finalize_virtual_address(self, virtual_address:int) -> int:
return virtual_address
def _reconstruct_permissions(self, permissions_mask:list[list[bool]]) -> tuple[int, int]:
k_flag, r_flag, w_flag, x_flag = permissions_mask[-1] # No hierarchy
r = r_flag
if self.mxr:
r |= x_flag
w = w_flag
x = x_flag
# Kernel page in kernel mode
if k_flag:
return r << 2 | w << 1 | int(x), 0
# User page in kernel mode
else:
if not self.Sum:
r = w = x = False
return 0, r << 2 | w << 1 | int(x)
class RISCVSV32(RISCVTranslator):
def __init__(
self,
table_address:int,
elf_dump: ELFDump,
Sum:bool,
mxr:bool,
ignored_pages:list[int] = []
) -> None:
self.unpack_format = "<I"
self.total_levels = 2
self.prefix = 0x0
self.table_sizes = [0x1000, 0x1000]
self.shifts = [22, 12]
self.wordsize = 4
self.ignored_pages = ignored_pages
super(RISCVSV32, self).__init__(table_address, elf_dump, Sum, mxr)
def _read_entry(self, index:int, entry:int, level:int) -> tuple[bool, list[list[bool]], int, int]:
# Return (is_Valid, Permissions flags, Table Address, Size)
# Empty entry
if not (entry & 0x1):
return False, [[]], 0, 0
else:
kernel = not bool(entry & 0x10)
read = bool(entry & 0x2)
write = bool(entry & 0x4)
execute = bool(entry & 0x8)
permissions_flags = [[kernel, read, write, execute]]
address = ((entry >> 10) & ((1 << 22) - 1)) << 12
# Leaf
if read or write or execute or level == 1:
return True, permissions_flags, address, 1 << self.shifts[level]
else:
# Upper tables pointers
return True, permissions_flags, address, 0
class RISCVSV39(RISCVTranslator):
def __init__(
self,
table_address: int,
elf_dump: ELFDump,
Sum: bool,
mxr: bool,
ignored_pages: list[int] = []
) -> None:
self.unpack_format = "<Q"
self.total_levels = 3
self.prefix = 0x0
self.table_sizes = [0x1000, 0x1000, 0x1000]
self.shifts = [30, 21, 12]
self.wordsize = 8
self.ignored_pages = ignored_pages
super(RISCVSV39, self).__init__(table_address, elf_dump, Sum, mxr)