-
Notifications
You must be signed in to change notification settings - Fork 14
/
mitigate.py
2662 lines (2238 loc) · 110 KB
/
mitigate.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
#!/usr/bin/sudo python
import argparse
import collections
import contextlib
import ctypes
import ctypes.util
import dataclasses
import datetime
import enum
import errno
import io
import ipaddress
import json
import logging.handlers
import os
import pathlib
import random
import re
import signal
import socket
import struct
import sys
import time
import typing
import urllib.request
import math
import mmap
import select
import zlib
# region Miscellaneous constants and typedefs
ACTION_ID_AUTO_ATTACK = 0x0007
ACTION_ID_AUTO_ATTACK_MCH = 0x0008
AUTO_ATTACK_DELAY = 0.1
SO_ORIGINAL_DST = 80
OPCODE_DEFINITION_LIST_URL = "https://api.github.com/repos/Soreepeong/XivAlexander/contents/StaticData/OpcodeDefinition"
SCRIPT_DIRECTORY = os.path.dirname(os.path.abspath(__file__))
EXTRA_DELAY_HELP = """Server responses have been usually taking between 50ms and 100ms on below-1ms latency to server, so 75ms is a good average.
The server will do sanity check on the frequency of action use requests,
and it's very easy to identify whether you're trying to go below allowed minimum value.
This addon is already in gray area. Do NOT decrease this value. You've been warned.
Feel free to increase and see how does it feel like to play on high latency instead, though."""
T = typing.TypeVar("T")
ArgumentTuple = collections.namedtuple("ArgumentTuple", ("region", "extra_delay", "measure_ping", "update_opcodes"))
def clamp(v: T, min_: T, max_: T) -> T:
return max(min_, min(max_, v))
class InvalidDataException(ValueError):
pass
class RootRequiredError(RuntimeError):
pass
class TcpInfo(ctypes.Structure):
"""TCP_INFO struct in linux 4.2
see /usr/include/linux/tcp.h for details"""
__u8 = ctypes.c_uint8
__u32 = ctypes.c_uint32
__u64 = ctypes.c_uint64
_fields_ = [
("tcpi_state", __u8),
("tcpi_ca_state", __u8),
("tcpi_retransmits", __u8),
("tcpi_probes", __u8),
("tcpi_backoff", __u8),
("tcpi_options", __u8),
("tcpi_snd_wscale", __u8, 4), ("tcpi_rcv_wscale", __u8, 4),
("tcpi_rto", __u32),
("tcpi_ato", __u32),
("tcpi_snd_mss", __u32),
("tcpi_rcv_mss", __u32),
("tcpi_unacked", __u32),
("tcpi_sacked", __u32),
("tcpi_lost", __u32),
("tcpi_retrans", __u32),
("tcpi_fackets", __u32),
# Times
("tcpi_last_data_sent", __u32),
("tcpi_last_ack_sent", __u32),
("tcpi_last_data_recv", __u32),
("tcpi_last_ack_recv", __u32),
# Metrics
("tcpi_pmtu", __u32),
("tcpi_rcv_ssthresh", __u32),
("tcpi_rtt", __u32),
("tcpi_rttvar", __u32),
("tcpi_snd_ssthresh", __u32),
("tcpi_snd_cwnd", __u32),
("tcpi_advmss", __u32),
("tcpi_reordering", __u32),
("tcpi_rcv_rtt", __u32),
("tcpi_rcv_space", __u32),
("tcpi_total_retrans", __u32),
("tcpi_pacing_rate", __u64),
("tcpi_max_pacing_rate", __u64),
# RFC4898 tcpEStatsAppHCThruOctetsAcked
("tcpi_bytes_acked", __u64),
# RFC4898 tcpEStatsAppHCThruOctetsReceived
("tcpi_bytes_received", __u64),
# RFC4898 tcpEStatsPerfSegsOut
("tcpi_segs_out", __u32),
# RFC4898 tcpEStatsPerfSegsIn
("tcpi_segs_in", __u32),
]
del __u8, __u32, __u64
def __repr__(self):
keyval = ["{}={!r}".format(x[0], getattr(self, x[0]))
for x in self._fields_]
fields = ", ".join(keyval)
return "{}({})".format(self.__class__.__name__, fields)
@classmethod
def from_socket(cls, sock: socket.socket):
"""Takes a socket, and attempts to get TCP_INFO stats on it. Returns a
TcpInfo struct"""
# http://linuxgazette.net/136/pfeiffer.html
padsize = ctypes.sizeof(TcpInfo)
data = sock.getsockopt(socket.SOL_TCP, socket.TCP_INFO, padsize)
# On older kernels, we get fewer bytes, pad with null to fit
padded = data.ljust(padsize, b'\0')
return cls.from_buffer_copy(padded)
@classmethod
def get_latency(cls, sock: socket.socket) -> typing.Optional[float]:
info = cls.from_socket(sock)
if info.tcpi_rtt:
return info.tcpi_rtt / 1000000
else:
return None
# endregion
# region PE Structures
IMAGE_NUMBEROF_DIRECTORY_ENTRIES = 16
IMAGE_DIRECTORY_ENTRY_BASERELOC = 5
IMAGE_SIZEOF_SHORT_NAME = 8
class ImageDosHeader(ctypes.LittleEndianStructure):
_fields_ = (
("e_magic", ctypes.c_uint16),
("e_cblp", ctypes.c_uint16),
("e_cp", ctypes.c_uint16),
("e_crlc", ctypes.c_uint16),
("e_cparhdr", ctypes.c_uint16),
("e_minalloc", ctypes.c_uint16),
("e_maxalloc", ctypes.c_uint16),
("e_ss", ctypes.c_uint16),
("e_sp", ctypes.c_uint16),
("e_csum", ctypes.c_uint16),
("e_ip", ctypes.c_uint16),
("e_cs", ctypes.c_uint16),
("e_lfarlc", ctypes.c_uint16),
("e_ovno", ctypes.c_uint16),
("e_res", ctypes.c_uint16 * 4),
("e_oemid", ctypes.c_uint16),
("e_oeminfo", ctypes.c_uint16),
("e_res2", ctypes.c_uint16 * 10),
("e_lfanew", ctypes.c_uint32),
)
e_magic: typing.Union[int, ctypes.c_uint16]
e_cblp: typing.Union[int, ctypes.c_uint16]
e_cp: typing.Union[int, ctypes.c_uint16]
e_crlc: typing.Union[int, ctypes.c_uint16]
e_cparhdr: typing.Union[int, ctypes.c_uint16]
e_minalloc: typing.Union[int, ctypes.c_uint16]
e_maxalloc: typing.Union[int, ctypes.c_uint16]
e_ss: typing.Union[int, ctypes.c_uint16]
e_sp: typing.Union[int, ctypes.c_uint16]
e_csum: typing.Union[int, ctypes.c_uint16]
e_ip: typing.Union[int, ctypes.c_uint16]
e_cs: typing.Union[int, ctypes.c_uint16]
e_lfarlc: typing.Union[int, ctypes.c_uint16]
e_ovno: typing.Union[int, ctypes.c_uint16]
e_res: typing.Union[typing.Sequence[int], ctypes.c_uint16 * 4]
e_oemid: typing.Union[int, ctypes.c_uint16]
e_oeminfo: typing.Union[int, ctypes.c_uint16]
e_res2: typing.Union[typing.Sequence[int], ctypes.c_uint16 * 10]
e_lfanew: typing.Union[int, ctypes.c_uint32]
class ImageFileHeader(ctypes.LittleEndianStructure):
_fields_ = (
("Machine", ctypes.c_uint16),
("NumberOfSections", ctypes.c_uint16),
("TimeDateStamp", ctypes.c_uint32),
("PointerToSymbolTable", ctypes.c_uint32),
("NumberOfSymbols", ctypes.c_uint32),
("SizeOfOptionalHeader", ctypes.c_uint16),
("Characteristics", ctypes.c_uint16),
)
Machine: typing.Union[int, ctypes.c_uint16]
NumberOfSections: typing.Union[int, ctypes.c_uint16]
TimeDateStamp: typing.Union[int, ctypes.c_uint32]
PointerToSymbolTable: typing.Union[int, ctypes.c_uint32]
NumberOfSymbols: typing.Union[int, ctypes.c_uint32]
SizeOfOptionalHeader: typing.Union[int, ctypes.c_uint16]
Characteristics: typing.Union[int, ctypes.c_uint16]
class ImageDataDirectory(ctypes.LittleEndianStructure):
_fields_ = (
("VirtualAddress", ctypes.c_uint32),
("Size", ctypes.c_uint32),
)
VirtualAddress: typing.Union[int, ctypes.c_uint32]
Size: typing.Union[int, ctypes.c_uint32]
class ImageOptionalHeader32(ctypes.LittleEndianStructure):
_fields_ = (
("Magic", ctypes.c_uint16),
("MajorLinkerVersion", ctypes.c_uint8),
("MinorLinkerVersion", ctypes.c_uint8),
("SizeOfCode", ctypes.c_uint32),
("SizeOfInitializedData", ctypes.c_uint32),
("SizeOfUninitializedData", ctypes.c_uint32),
("AddressOfEntryPoint", ctypes.c_uint32),
("BaseOfCode", ctypes.c_uint32),
("BaseOfData", ctypes.c_uint32),
("ImageBase", ctypes.c_uint32),
("SectionAlignment", ctypes.c_uint32),
("FileAlignment", ctypes.c_uint32),
("MajorOperatingSystemVersion", ctypes.c_uint16),
("MinorOperatingSystemVersion", ctypes.c_uint16),
("MajorImageVersion", ctypes.c_uint16),
("MinorImageVersion", ctypes.c_uint16),
("MajorSubsystemVersion", ctypes.c_uint16),
("MinorSubsystemVersion", ctypes.c_uint16),
("Win32VersionValue", ctypes.c_uint32),
("SizeOfImage", ctypes.c_uint32),
("SizeOfHeaders", ctypes.c_uint32),
("CheckSum", ctypes.c_uint32),
("Subsystem", ctypes.c_uint16),
("DllCharacteristics", ctypes.c_uint16),
("SizeOfStackReserve", ctypes.c_uint32),
("SizeOfStackCommit", ctypes.c_uint32),
("SizeOfHeapReserve", ctypes.c_uint32),
("SizeOfHeapCommit", ctypes.c_uint32),
("LoaderFlags", ctypes.c_uint32),
("NumberOfRvaAndSizes", ctypes.c_uint32),
("DataDirectory", ImageDataDirectory * IMAGE_NUMBEROF_DIRECTORY_ENTRIES),
)
Magic: typing.Union[int, ctypes.c_uint16]
MajorLinkerVersion: typing.Union[int, ctypes.c_uint8]
MinorLinkerVersion: typing.Union[int, ctypes.c_uint8]
SizeOfCode: typing.Union[int, ctypes.c_uint32]
SizeOfInitializedData: typing.Union[int, ctypes.c_uint32]
SizeOfUninitializedData: typing.Union[int, ctypes.c_uint32]
AddressOfEntryPoint: typing.Union[int, ctypes.c_uint32]
BaseOfCode: typing.Union[int, ctypes.c_uint32]
BaseOfData: typing.Union[int, ctypes.c_uint32]
ImageBase: typing.Union[int, ctypes.c_uint32]
SectionAlignment: typing.Union[int, ctypes.c_uint32]
FileAlignment: typing.Union[int, ctypes.c_uint32]
MajorOperatingSystemVersion: typing.Union[int, ctypes.c_uint16]
MinorOperatingSystemVersion: typing.Union[int, ctypes.c_uint16]
MajorImageVersion: typing.Union[int, ctypes.c_uint16]
MinorImageVersion: typing.Union[int, ctypes.c_uint16]
MajorSubsystemVersion: typing.Union[int, ctypes.c_uint16]
MinorSubsystemVersion: typing.Union[int, ctypes.c_uint16]
Win32VersionValue: typing.Union[int, ctypes.c_uint32]
SizeOfImage: typing.Union[int, ctypes.c_uint32]
SizeOfHeaders: typing.Union[int, ctypes.c_uint32]
CheckSum: typing.Union[int, ctypes.c_uint32]
Subsystem: typing.Union[int, ctypes.c_uint16]
DllCharacteristics: typing.Union[int, ctypes.c_uint16]
SizeOfStackReserve: typing.Union[int, ctypes.c_uint32]
SizeOfStackCommit: typing.Union[int, ctypes.c_uint32]
SizeOfHeapReserve: typing.Union[int, ctypes.c_uint32]
SizeOfHeapCommit: typing.Union[int, ctypes.c_uint32]
LoaderFlags: typing.Union[int, ctypes.c_uint32]
NumberOfRvaAndSizes: typing.Union[int, ctypes.c_uint32]
DataDirectory: typing.Union[typing.Sequence[ImageDataDirectory], ImageDataDirectory * IMAGE_NUMBEROF_DIRECTORY_ENTRIES]
class ImageOptionalHeader64(ctypes.LittleEndianStructure):
_fields_ = (
("Magic", ctypes.c_uint16),
("MajorLinkerVersion", ctypes.c_uint8),
("MinorLinkerVersion", ctypes.c_uint8),
("SizeOfCode", ctypes.c_uint32),
("SizeOfInitializedData", ctypes.c_uint32),
("SizeOfUninitializedData", ctypes.c_uint32),
("AddressOfEntryPoint", ctypes.c_uint32),
("BaseOfCode", ctypes.c_uint32),
("ImageBase", ctypes.c_uint64),
("SectionAlignment", ctypes.c_uint32),
("FileAlignment", ctypes.c_uint32),
("MajorOperatingSystemVersion", ctypes.c_uint16),
("MinorOperatingSystemVersion", ctypes.c_uint16),
("MajorImageVersion", ctypes.c_uint16),
("MinorImageVersion", ctypes.c_uint16),
("MajorSubsystemVersion", ctypes.c_uint16),
("MinorSubsystemVersion", ctypes.c_uint16),
("Win32VersionValue", ctypes.c_uint32),
("SizeOfImage", ctypes.c_uint32),
("SizeOfHeaders", ctypes.c_uint32),
("CheckSum", ctypes.c_uint32),
("Subsystem", ctypes.c_uint16),
("DllCharacteristics", ctypes.c_uint16),
("SizeOfStackReserve", ctypes.c_uint64),
("SizeOfStackCommit", ctypes.c_uint64),
("SizeOfHeapReserve", ctypes.c_uint64),
("SizeOfHeapCommit", ctypes.c_uint64),
("LoaderFlags", ctypes.c_uint32),
("NumberOfRvaAndSizes", ctypes.c_uint32),
("DataDirectory", ImageDataDirectory * IMAGE_NUMBEROF_DIRECTORY_ENTRIES),
)
Magic: typing.Union[int, ctypes.c_uint16]
MajorLinkerVersion: typing.Union[int, ctypes.c_uint8]
MinorLinkerVersion: typing.Union[int, ctypes.c_uint8]
SizeOfCode: typing.Union[int, ctypes.c_uint32]
SizeOfInitializedData: typing.Union[int, ctypes.c_uint32]
SizeOfUninitializedData: typing.Union[int, ctypes.c_uint32]
AddressOfEntryPoint: typing.Union[int, ctypes.c_uint32]
BaseOfCode: typing.Union[int, ctypes.c_uint32]
ImageBase: typing.Union[int, ctypes.c_uint64]
SectionAlignment: typing.Union[int, ctypes.c_uint32]
FileAlignment: typing.Union[int, ctypes.c_uint32]
MajorOperatingSystemVersion: typing.Union[int, ctypes.c_uint16]
MinorOperatingSystemVersion: typing.Union[int, ctypes.c_uint16]
MajorImageVersion: typing.Union[int, ctypes.c_uint16]
MinorImageVersion: typing.Union[int, ctypes.c_uint16]
MajorSubsystemVersion: typing.Union[int, ctypes.c_uint16]
MinorSubsystemVersion: typing.Union[int, ctypes.c_uint16]
Win32VersionValue: typing.Union[int, ctypes.c_uint32]
SizeOfImage: typing.Union[int, ctypes.c_uint32]
SizeOfHeaders: typing.Union[int, ctypes.c_uint32]
CheckSum: typing.Union[int, ctypes.c_uint32]
Subsystem: typing.Union[int, ctypes.c_uint16]
DllCharacteristics: typing.Union[int, ctypes.c_uint16]
SizeOfStackReserve: typing.Union[int, ctypes.c_uint64]
SizeOfStackCommit: typing.Union[int, ctypes.c_uint64]
SizeOfHeapReserve: typing.Union[int, ctypes.c_uint64]
SizeOfHeapCommit: typing.Union[int, ctypes.c_uint64]
LoaderFlags: typing.Union[int, ctypes.c_uint32]
NumberOfRvaAndSizes: typing.Union[int, ctypes.c_uint32]
DataDirectory: typing.Union[typing.Sequence[ImageDataDirectory], ImageDataDirectory * IMAGE_NUMBEROF_DIRECTORY_ENTRIES]
class ImageNtHeaders32(ctypes.LittleEndianStructure):
_fields_ = (
("Signature", ctypes.c_uint32),
("FileHeader", ImageFileHeader),
("OptionalHeader", ImageOptionalHeader32),
)
Signature: typing.Union[int, ctypes.c_uint32]
FileHeader: ImageFileHeader
OptionalHeader: ImageOptionalHeader32
class ImageNtHeaders64(ctypes.LittleEndianStructure):
_fields_ = (
("Signature", ctypes.c_uint32),
("FileHeader", ImageFileHeader),
("OptionalHeader", ImageOptionalHeader64),
)
Signature: typing.Union[int, ctypes.c_uint32]
FileHeader: ImageFileHeader
OptionalHeader: ImageOptionalHeader64
class ImageSectionHeader(ctypes.LittleEndianStructure):
_fields_ = (
("Name", ctypes.c_char * IMAGE_SIZEOF_SHORT_NAME),
("VirtualSize", ctypes.c_uint32),
("VirtualAddress", ctypes.c_uint32),
("SizeOfRawData", ctypes.c_uint32),
("PointerToRawData", ctypes.c_uint32),
("PointerToRelocations", ctypes.c_uint32),
("PointerToLinenumbers", ctypes.c_uint32),
("NumberOfRelocations", ctypes.c_uint16),
("NumberOfLinenumbers", ctypes.c_uint16),
("Characteristics", ctypes.c_uint32),
)
Name: typing.Union[bytes, ctypes.c_char * IMAGE_SIZEOF_SHORT_NAME]
VirtualSize: typing.Union[int, ctypes.c_uint32]
VirtualAddress: typing.Union[int, ctypes.c_uint32]
SizeOfRawData: typing.Union[int, ctypes.c_uint32]
PointerToRawData: typing.Union[int, ctypes.c_uint32]
PointerToRelocations: typing.Union[int, ctypes.c_uint32]
PointerToLinenumbers: typing.Union[int, ctypes.c_uint32]
NumberOfRelocations: typing.Union[int, ctypes.c_uint16]
NumberOfLinenumbers: typing.Union[int, ctypes.c_uint16]
Characteristics: typing.Union[int, ctypes.c_uint32]
class ImageBaseRelocation(ctypes.LittleEndianStructure):
_fields_ = (
("VirtualAddress", ctypes.c_uint32),
("SizeOfBlock", ctypes.c_uint32),
)
VirtualAddress: typing.Union[int, ctypes.c_uint32]
SizeOfBlock: typing.Union[int, ctypes.c_uint32]
# endregion
# region x86/x64-specific system ffi definitions
POINTER_SIZE = ctypes.sizeof(ctypes.c_void_p)
if os.name == 'nt':
crt_malloc = ctypes.cdll.msvcrt.malloc
crt_free = ctypes.cdll.msvcrt.free
def allocate_executable_memory(length: int):
virtualalloc = ctypes.windll.kernel32.VirtualAlloc
virtualalloc.argtypes = (ctypes.c_void_p, ctypes.c_size_t, ctypes.c_uint32, ctypes.c_uint32)
virtualalloc.restype = ctypes.c_void_p
return ctypes.c_void_p(virtualalloc(0,
length,
0x3000, # MEM_RESERVE | MEM_COMMIT
0x40)) # PAGE_EXECUTE_READWRITE
def free_executable_memory(ptr: ctypes.c_void_p):
ctypes.windll.kernel32.VirtualFree(ptr, 0, 0x8000)
else:
libc = ctypes.CDLL(ctypes.util.find_library("c"))
crt_malloc = libc.malloc
crt_free = libc.free
# close enough definitions
libc.memalign.argtypes = ctypes.c_size_t, ctypes.c_size_t
libc.memalign.restype = ctypes.c_size_t
libc.mprotect.argtypes = ctypes.c_size_t, ctypes.c_size_t, ctypes.c_size_t
def allocate_executable_memory(length: int):
p = libc.memalign(mmap.PAGESIZE, length)
libc.mprotect(p, length, mmap.PROT_READ | mmap.PROT_WRITE | mmap.PROT_EXEC)
return ctypes.c_void_p(p)
def free_executable_memory(ptr: ctypes.c_void_p):
crt_free(ptr.value)
crt_malloc.argtypes = (ctypes.c_size_t,)
crt_malloc.restype = ctypes.c_size_t
crt_free.argtypes = (ctypes.c_size_t,)
PyMemoryView_FromMemory = ctypes.pythonapi.PyMemoryView_FromMemory
PyMemoryView_FromMemory.argtypes = (ctypes.c_void_p, ctypes.c_ssize_t, ctypes.c_int)
PyMemoryView_FromMemory.restype = ctypes.py_object
# endregion
# region budget windows stdcall <-> linux cdecl ABI converters
class PeImage:
def __init__(self, data: typing.Union[bytearray, bytes]):
self._data = data if isinstance(data, bytearray) else bytearray(data)
self.dos = ImageDosHeader.from_buffer(self._data, 0)
if self.dos.e_magic != 0x5a4d:
raise ValueError("bad dos header")
if POINTER_SIZE == 8:
self.nt = ImageNtHeaders64.from_buffer(self._data, self.dos.e_lfanew)
else:
self.nt = ImageNtHeaders32.from_buffer(self._data, self.dos.e_lfanew)
if self.nt.Signature != 0x4550:
raise ValueError("bad nt header")
self.sections: typing.Union[typing.Sequence[ImageSectionHeader], ctypes.Array[ImageSectionHeader]] = (
ImageSectionHeader * self.nt.FileHeader.NumberOfSections).from_buffer(
self._data, self.dos.e_lfanew + ctypes.sizeof(self.nt))
self.address: ctypes.c_void_p = allocate_executable_memory(self.nt.OptionalHeader.SizeOfImage)
self.view: memoryview = PyMemoryView_FromMemory(
self.address,
self.nt.OptionalHeader.SizeOfImage,
0x200, # Read/Write
)
self._map_headers_and_sections()
self._relocate()
def _map_headers_and_sections(self):
ctypes.memmove(self.address,
ctypes.addressof(ctypes.c_byte.from_buffer(self._data)),
self.nt.OptionalHeader.SizeOfHeaders)
for shdr in self.sections:
ctypes.memmove(ctypes.addressof(ctypes.c_byte.from_buffer(self.view, shdr.VirtualAddress)),
ctypes.addressof(ctypes.c_byte.from_buffer(self._data, shdr.PointerToRawData)),
min(shdr.SizeOfRawData, shdr.VirtualSize))
def _relocate(self):
rva = int(self.nt.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress)
rva_to = rva + int(self.nt.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].Size)
displacement = self.address.value - self.nt.OptionalHeader.ImageBase
while rva < rva_to:
page = ctypes.cast(ctypes.c_void_p(self.address.value + rva), ctypes.POINTER(ImageBaseRelocation)).contents
page_data = ctypes.cast(ctypes.c_void_p(self.address.value + rva + ctypes.sizeof(page)),
ctypes.POINTER(ctypes.c_uint16 * ((page.SizeOfBlock - ctypes.sizeof(page)) // 2))
).contents
for relo in page_data:
absptr_address = self.address.value + page.VirtualAddress + (relo & 0xFFF)
if relo >> 12 == 0:
pass
elif relo >> 12 == 3:
ptr = ctypes.cast(absptr_address, ctypes.POINTER(ctypes.c_uint32))
ctypes.memmove(absptr_address,
ctypes.addressof(ctypes.c_uint32(ptr.contents.value + displacement)), 4)
elif relo >> 12 == 10:
ptr = ctypes.cast(absptr_address, ctypes.POINTER(ctypes.c_uint64))
ctypes.memmove(absptr_address,
ctypes.addressof(ctypes.c_uint64(ptr.contents.value + displacement)), 8)
else:
raise RuntimeError("Unsupported relocation type")
rva += page.SizeOfBlock
def section_header(self, name: bytes):
try:
return next(s for s in self.sections if s.Name == name)
except StopIteration:
return KeyError
def section(self, section: typing.Union[bytes, ImageSectionHeader]) -> memoryview:
if not isinstance(section, ImageSectionHeader):
section = self.section_header(section)
return self.view[section.VirtualAddress:section.VirtualAddress + section.VirtualSize]
def resolve_rip_relative(self, addr: int):
if self.view[addr] in (0xE8, 0xE9):
return addr + 5 + int.from_bytes(self.view[addr + 1:addr + 5], "little", signed=True)
else:
raise NotImplementedError
class StdCallFunc32ByPythonFunction:
def __init__(self, pyctypefn, fn: callable, arglen: int, name: str):
self._inner = pyctypefn(fn)
self._fn = fn
self._name = name
inner_address = ctypes.cast(self._inner, ctypes.c_void_p)
codelen = 1 + arglen // 4 * 7 + 5 + 2 + 6 + 3
codeptr = allocate_executable_memory(codelen)
buf = (ctypes.c_uint8 * codelen).from_address(codeptr.value)
buf[0] = 0x90
i = 1
for j in range(0, arglen, 4):
buf[i] = 0xff
buf[i + 1] = 0xb4
buf[i + 2] = 0x24
ctypes.c_uint32.from_address(codeptr.value + i + 3).value = arglen
i += 7
buf[i] = 0xb8
ctypes.c_void_p.from_address(codeptr.value + i + 1).value = inner_address.value
i += 5
buf[i] = 0xff
buf[i + 1] = 0xd0
i += 2
buf[i + 0] = 0x81
buf[i + 1] = 0xc4
ctypes.c_uint32.from_address(codeptr.value + i + 2).value = arglen
i += 6
buf[i] = 0xc2
ctypes.c_uint16.from_address(codeptr.value + i + 1).value = arglen
self._address = codeptr
def address(self):
return self._address
def __call__(self, *args):
return self._fn(*args)
class StdCallFunc64ByPythonFunction:
def __init__(self, pyctypefn, fn: callable, arglen: int, name: str):
self._inner = pyctypefn(fn)
self._fn = fn
self._name = name
inner_address = ctypes.cast(self._inner, ctypes.c_void_p)
cmds = [
b"\x48\x83\xec\x38", # sub rsp, 0x38
b"\x57", # push rdi
b"\x56", # push rsi
b"\x48\x89\xCF", # mov rdi, rcx
b"\x48\x89\xD6", # mov rsi, rdx
b"\x4C\x89\xC2", # mov rdx, r8
b"\x4C\x89\xC9", # mov rcx, r9
b"\x48\xB8", inner_address.value.to_bytes(8, "little"), # movabs rax, 0x0
b"\xFF\xD0", # call rax
b"\x5E", # pop rsi
b"\x5F", # pop rdi
b"\x48\x83\xc4\x38", # add rsp, 0x38
b"\xC3", # ret
]
cmds = bytearray().join(cmds)
self._address = allocate_executable_memory(len(cmds))
ctypes.memmove(self._address.value,
ctypes.addressof((ctypes.c_uint8 * len(cmds)).from_buffer(cmds)),
len(cmds))
def address(self):
return self._address
def __call__(self, *args):
return self._fn(*args)
class StdCallFunc32ByFunctionPointer:
def __init__(self, ptr: int, argtypes, noargtypefn, name: str):
self._name = name
self._ptr = ptr
self._argtypes = argtypes
self._codelen = 1 + sum((ctypes.sizeof(argtype) + 3) // 4 * 5 for argtype in argtypes) + 8
self._noargtypefn = noargtypefn
self._codeptr = allocate_executable_memory(self._codelen)
def address(self):
return ctypes.c_void_p(self._ptr)
def __call__(self, *args):
buf = (ctypes.c_uint8 * self._codelen).from_address(self._codeptr.value)
buf[0] = 0x90
i = 1
for argtype, arg in zip(reversed(self._argtypes), reversed(args)):
arglen = ctypes.sizeof(argtype)
if not isinstance(arg, argtype):
arg = argtype(arg)
argb = (ctypes.c_uint8 * arglen).from_address(ctypes.addressof(arg))
j = 0
while j < arglen - 3:
buf[i] = 0x68
buf[i + 1] = argb[0]
buf[i + 2] = argb[1]
buf[i + 3] = argb[2]
buf[i + 4] = argb[3]
i += 5
j += 4
if j != arglen:
buf[i] = 0x68
buf[i + 1] = argb[0]
buf[i + 2] = argb[1] if j + 1 <= arglen else 0
buf[i + 3] = argb[2] if j + 2 <= arglen else 0
buf[i + 4] = argb[3] if j + 3 <= arglen else 0
i += 5
buf[i] = 0xb8
ctypes.c_uint32.from_address(self._codeptr.value + i + 1).value = self._ptr
buf[i + 5] = 0xff
buf[i + 6] = 0xd0
buf[i + 7] = 0xc3
res = self._noargtypefn(self._codeptr.value)()
return res
class StdCallFunc64ByFunctionPointer:
def __init__(self, ptr: int, argtypes, noargtypefn, name: str):
self._ptr = ptr
self._argtypes = argtypes
self._noargtypefn = noargtypefn
self._name = name
movabs_regs = (
b"\x48\xb9", # movabs rcx, imm
b"\x48\xba", # movabs rdx, imm
b"\x49\xb8", # movabs r8, imm
b"\x49\xb9", # movabs r9, imm
)
cmds = [
b"\x57", # push rdi
b"\x56", # push rsi
# sub rsp, imm
b"\x48\x83\xec",
(0x8 + (len(argtypes) + 1) // 2 * 2 * 8).to_bytes(1, "little"),
]
self._offsets = []
for i, argtype in enumerate(self._argtypes):
if i < len(movabs_regs):
cmds.append(movabs_regs[i])
self._offsets.append(sum(len(x) for x in cmds))
cmds.append(bytes(8))
else:
# movabs rax, imm
cmds.append(b"\x48\xb8")
self._offsets.append(sum(len(x) for x in cmds))
cmds.append(bytes(8))
# mov qword ptr [rsp + N], rax
cmds.append(b"\x48\x89\x44\x24")
cmds.append((i * 8).to_bytes(1, "little"))
# movabs rax, imm
cmds.append(b"\x48\xb8")
cmds.append(self._ptr.to_bytes(8, "little"))
cmds.append(b"\xff\xd0") # call rax
# add rsp, imm
cmds.append(b"\x48\x83\xc4" + (0x8 + (len(argtypes) + 1) // 2 * 2 * 8).to_bytes(1, "little"))
cmds.append(b"\x5e") # pop rsi
cmds.append(b"\x5f") # pop rdi
cmds.append(b"\xc3") # ret
self._template = bytearray().join(cmds)
self._codeptr = allocate_executable_memory(len(self._template))
ctypes.memmove(self._codeptr.value,
ctypes.addressof(ctypes.c_uint8.from_buffer(self._template)),
len(self._template))
def address(self):
return ctypes.c_void_p(self._ptr)
def __call__(self, *args):
for argtype, arg, offset in zip(self._argtypes, args, self._offsets):
arglen = ctypes.sizeof(argtype)
if not isinstance(arg, argtype):
arg = argtype(arg)
ctypes.memmove(self._codeptr.value + offset, ctypes.addressof(arg), arglen)
res = self._noargtypefn(self._codeptr.value)()
return res
class StdCallFunc32Type:
def __init__(self, restype, *argtypes, name: typing.Optional[str] = None):
self._name = name or ("(" + ", ".join(str(x) for x in (restype, *argtypes)) + ")")
self._restype = restype
self._argtypes = argtypes
self._arglen = sum((ctypes.sizeof(argtype) + 3) // 4 * 4 for argtype in self._argtypes)
self._noarg_type = ctypes.CFUNCTYPE(restype)
self._pytype = ctypes.CFUNCTYPE(restype, *argtypes)
def __call__(self, ptr):
if callable(ptr):
return StdCallFunc32ByPythonFunction(self._pytype, ptr, self._arglen, self._name)
elif isinstance(ptr, int):
return StdCallFunc32ByFunctionPointer(ptr, self._argtypes, self._noarg_type, self._name)
else:
raise TypeError
class StdCallFunc64Type:
def __init__(self, restype, *argtypes, name: typing.Optional[str] = None):
self._name = name or ("(" + ", ".join(str(x) for x in (restype, *argtypes)) + ")")
self._restype = restype
self._argtypes = argtypes
self._arglen = sum((ctypes.sizeof(argtype) + 3) // 4 * 4 for argtype in self._argtypes)
self._noarg_type = ctypes.CFUNCTYPE(restype)
self._pytype = ctypes.CFUNCTYPE(restype, *argtypes)
def __call__(self, ptr):
if callable(ptr):
return StdCallFunc64ByPythonFunction(self._pytype, ptr, self._arglen, self._name)
elif isinstance(ptr, int):
return StdCallFunc64ByFunctionPointer(ptr, self._argtypes, self._noarg_type, self._name)
else:
raise TypeError
if POINTER_SIZE == 4:
StdCallFuncType = StdCallFunc32Type
else:
StdCallFuncType = StdCallFunc64Type
# endregion
# region Oodle typedefs
OodleNetwork1_Shared_Size = StdCallFuncType(ctypes.c_int32, ctypes.c_int32, name="OodleNetwork1_Shared_Size")
OodleNetwork1_Shared_SetWindow = StdCallFuncType(None, ctypes.c_void_p, ctypes.c_int32, ctypes.c_void_p, ctypes.c_int32,
name="OodleNetwork1_Shared_SetWindow")
OodleNetwork1_Proto_Train = StdCallFuncType(None, ctypes.c_void_p, ctypes.c_void_p, ctypes.POINTER(ctypes.c_void_p),
ctypes.POINTER(ctypes.c_int32), ctypes.c_int32,
name="OodleNetwork1_Proto_Train")
OodleNetwork1_Proto_Decode = StdCallFuncType(ctypes.c_bool, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p,
ctypes.c_size_t, ctypes.c_void_p, ctypes.c_size_t,
name="OodleNetwork1_Proto_Decode")
OodleNetwork1_Proto_Encode = StdCallFuncType(ctypes.c_int32, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p,
ctypes.c_size_t, ctypes.c_void_p, name="OodleNetwork1_Proto_Encode")
OodleNetwork1_Proto_State_Size = StdCallFuncType(ctypes.c_int32, name="OodleNetwork1_Proto_State_Size")
Oodle_Malloc = StdCallFuncType(ctypes.c_size_t, ctypes.c_size_t, ctypes.c_int32, name="Oodle_Malloc")
Oodle_Free = StdCallFuncType(None, ctypes.c_size_t, name="Oodle_Free")
Oodle_SetMallocFree = StdCallFuncType(None, ctypes.c_void_p, ctypes.c_void_p, name="Oodle_SetMallocFree")
# endregion
# region ZiPatch typedefs
class ZiPatchHeader(ctypes.BigEndianStructure):
SIGNATURE = b"\x91\x5A\x49\x50\x41\x54\x43\x48\x0d\x0a\x1a\x0a"
_fields_ = (
("signature", ctypes.c_char * 12),
)
signature: typing.Union[int, ctypes.c_char * 12]
class ZiPatchChunkHeader(ctypes.BigEndianStructure):
_fields_ = (
("size", ctypes.c_uint32),
("type", ctypes.c_char * 4),
)
size: typing.Union[int, ctypes.c_uint32]
type: typing.Union[bytes, ctypes.c_char * 4]
class ZiPatchChunkFooter(ctypes.BigEndianStructure):
_fields_ = (
("crc32", ctypes.c_uint32),
)
crc32: typing.Union[int, ctypes.c_uint32]
class ZiPatchSqpackHeader(ctypes.BigEndianStructure):
_fields_ = (
("size", ctypes.c_uint32),
("command", ctypes.c_char * 4),
)
size: typing.Union[int, ctypes.c_uint32]
command: typing.Union[bytes, ctypes.c_char * 4]
class ZiPatchSqpackFileAddHeader(ctypes.BigEndianStructure):
COMMAND = b'FA'
_fields_ = (
("offset", ctypes.c_uint64),
("size", ctypes.c_uint64),
("path_size", ctypes.c_uint32),
("expac_id", ctypes.c_uint16),
("padding1", ctypes.c_uint16),
)
offset: typing.Union[int, ctypes.c_uint16]
size: typing.Union[int, ctypes.c_uint64]
path_size: typing.Union[int, ctypes.c_uint32]
expac_id: typing.Union[int, ctypes.c_uint16]
padding1: typing.Union[int, ctypes.c_uint16]
class ZiPatchSqpackFileDeleteHeader(ctypes.BigEndianStructure):
COMMAND = b'FD'
_fields_ = (
("offset", ctypes.c_uint64),
("size", ctypes.c_uint64),
("path_size", ctypes.c_uint32),
("expac_id", ctypes.c_uint16),
("padding1", ctypes.c_uint16),
)
offset: typing.Union[int, ctypes.c_uint16]
size: typing.Union[int, ctypes.c_uint64]
path_size: typing.Union[int, ctypes.c_uint32]
expac_id: typing.Union[int, ctypes.c_uint16]
padding1: typing.Union[int, ctypes.c_uint16]
class ZiPatchSqpackFileResolver(ctypes.BigEndianStructure):
_fields_ = (
("main_id", ctypes.c_uint16),
("sub_id", ctypes.c_uint16),
("file_id", ctypes.c_uint32),
)
main_id: typing.Union[int, ctypes.c_uint16]
sub_id: typing.Union[int, ctypes.c_uint16]
file_id: typing.Union[int, ctypes.c_uint32]
@property
def expac_id(self):
return self.sub_id >> 8
@property
def path(self):
if self.expac_id == 0:
return f"sqpack/ffxiv/{self.main_id:02x}{self.sub_id:04x}.win32"
else:
return f"sqpack/ex{self.expac_id}/{self.main_id:02x}{self.sub_id:04x}.win32"
class ZiPatchSqpackAddData(ZiPatchSqpackFileResolver):
COMMAND = b'A'
_fields_ = (
("block_offset_value", ctypes.c_uint32),
("block_size_value", ctypes.c_uint32),
("clear_size_value", ctypes.c_uint32),
)
@property
def block_offset(self):
return self.block_offset_value * 128
@property
def block_size(self):
return self.block_size_value * 128
@property
def clear_size(self):
return self.clear_size_value * 128
@property
def path(self):
return super().path + f".dat{self.file_id}"
class ZiPatchSqpackZeroData(ZiPatchSqpackFileResolver):
COMMANDS = {b'E', b'D'}
_fields_ = (
("block_offset_value", ctypes.c_uint32),
("block_size_value", ctypes.c_uint32),
)
@property
def block_offset(self):
return self.block_offset_value * 128
@property
def block_size(self):
return self.block_size_value * 128
@property
def path(self):
return super().path + f".dat{self.file_id}"
class BlockHeader(ctypes.LittleEndianStructure):
COMPRESSED_SIZE_NOT_COMPRESSED = 32000
_fields_ = (
("header_length", ctypes.c_uint32),
("version", ctypes.c_uint32),
("compressed_size", ctypes.c_uint32),
("decompressed_size", ctypes.c_uint32),
)
header_length: int
version: int
compressed_size: int
decompressed_size: int
data: typing.Optional[bytes] = None
def is_compressed(self):
return self.compressed_size != BlockHeader.COMPRESSED_SIZE_NOT_COMPRESSED and self.decompressed_size != 1
# endregion
# region Game network typedefs
class XivMessageIpcActionEffect(ctypes.LittleEndianStructure):
_fields_ = (
("animation_target_actor", ctypes.c_uint32),
("unknown_0x004", ctypes.c_uint32),
("action_id", ctypes.c_uint32),
("global_effect_counter", ctypes.c_uint32),
("animation_lock_duration", ctypes.c_float),
("unknown_target_id", ctypes.c_uint32),
("source_sequence", ctypes.c_uint16),
("rotation", ctypes.c_uint16),