forked from nyaoouo/GBFR-ACT
-
Notifications
You must be signed in to change notification settings - Fork 0
/
injector.py
1962 lines (1644 loc) · 74.5 KB
/
injector.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 ctypes
import ctypes.wintypes
import ctypes.util
import functools
import io
import locale
import logging
import os
import tempfile
import msvcrt
import pathlib
import pickle
import re
import struct
import threading
import traceback
import types
import time
import sys
import typing
_NULL = type('NULL', (), {})
_T = typing.TypeVar('_T')
def _win_api(func, res_type: typing.Any = ctypes.c_void_p, arg_types=(), error_zero=False, error_nonzero=False, error_val: typing.Any = _NULL):
func.argtypes = arg_types
func.restype = res_type
if error_zero and error_nonzero: # pragma: no cover
raise ValueError("Cannot raise on both zero and non-zero")
if error_zero:
def wrapper(*args, **kwargs):
res = func(*args, **kwargs)
if not res:
raise ctypes.WinError()
return res
return wrapper
if error_nonzero:
def wrapper(*args, **kwargs):
res = func(*args, **kwargs)
if res: raise ctypes.WinError()
return res
return wrapper
if error_val is not _NULL:
def wrapper(*args, **kwargs):
res = func(*args, **kwargs)
if res == error_val: raise ctypes.WinError()
return res
return wrapper
return func
PYTHON_DLL = f"python{sys.version_info.major}{sys.version_info.minor}.dll"
INVALID_HANDLE_VALUE = 0xffffffffffffffff
DEFAULT_CODING = locale.getpreferredencoding()
class MEMORY_BASIC_INFORMATION(ctypes.Structure):
_fields_ = [
("BaseAddress", ctypes.c_ulonglong),
("AllocationBase", ctypes.c_ulonglong),
("AllocationProtect", ctypes.c_ulong),
("RegionSize", ctypes.c_ulonglong),
("State", ctypes.c_ulong),
("Protect", ctypes.c_ulong),
("Type", ctypes.c_ulong)
]
class LUID(ctypes.Structure):
_fields_ = [("LowPart", ctypes.c_ulong), ("HighPart", ctypes.c_long)]
class LUID_AND_ATTRIBUTES(ctypes.Structure):
_fields_ = [("Luid", LUID), ("Attributes", ctypes.c_ulong), ]
class TOKEN_PRIVILEGES(ctypes.Structure):
_fields_ = [("count", ctypes.c_ulong), ("Privileges", LUID_AND_ATTRIBUTES * 1)]
class LIST_ENTRY(ctypes.Structure):
_fields_ = [("Flink", ctypes.c_void_p), ("Blink", ctypes.c_void_p), ]
class UNICODE_STRING(ctypes.Structure):
_fields_ = [('Length', ctypes.c_ushort), ('MaximumLength', ctypes.c_ushort), ('Buffer', ctypes.c_size_t), ]
@classmethod
def from_str(cls, s: str):
length = len(s) * 2
_s = cls(length, length + 2, ctypes.addressof(_buf := ctypes.create_unicode_buffer(s)))
setattr(_s, '_buf', _buf)
return _s
@property
def value(self):
return ctypes.cast(self.Buffer, ctypes.c_wchar_p).value
def remote_value(self, process: 'Process'):
return process.read(self.Buffer, self.Length).decode('utf-16-le')
class LDR_DATA_TABLE_ENTRY(LIST_ENTRY):
_fields_ = [
("InLoadOrderLinks", LIST_ENTRY),
("InMemoryOrderLinks", LIST_ENTRY),
("InInitializationOrderLinks", LIST_ENTRY),
("DllBase", ctypes.c_void_p),
("EntryPoint", ctypes.c_void_p),
("SizeOfImage", ctypes.c_uint32),
("FullDllName", UNICODE_STRING),
("BaseDllName", UNICODE_STRING),
("Flags", ctypes.c_uint32),
("LoadCount", ctypes.c_uint16),
("TlsIndex", ctypes.c_uint16),
("HashLinks", LIST_ENTRY),
("SectionPointer", ctypes.c_void_p),
("CheckSum", ctypes.c_uint32),
("TimeDateStamp", ctypes.c_uint32),
("LoadedImports", ctypes.c_void_p),
("EntryPointActivationContext", ctypes.c_void_p),
("PatchInformation", ctypes.c_void_p),
]
class PEB_LDR_DATA(ctypes.Structure):
_fields_ = [
("Length", ctypes.c_uint32),
("Initialized", ctypes.c_uint8),
("SsHandle", ctypes.c_void_p),
("InLoadOrderModuleList", LIST_ENTRY),
("InMemoryOrderModuleList", LIST_ENTRY),
("InInitializationOrderModuleList", LIST_ENTRY),
("EntryInProgress", ctypes.c_void_p),
]
class PROCESS_BASIC_INFORMATION(ctypes.Structure):
_fields_ = [
("ExitStatus", ctypes.c_ulong),
("PebBaseAddress", ctypes.c_void_p),
("AffinityMask", ctypes.c_void_p),
("BasePriority", ctypes.c_void_p),
("UniqueProcessId", ctypes.c_void_p),
("InheritedFromUniqueProcessId", ctypes.c_void_p)
]
class PEB(ctypes.Structure):
_fields_ = [
("InheritedAddressSpace", ctypes.c_uint8),
("ReadImageFileExecOptions", ctypes.c_uint8),
("BeingDebugged", ctypes.c_uint8),
("SpareBool", ctypes.c_uint8),
("Mutant", ctypes.c_void_p),
("ImageBaseAddress", ctypes.c_void_p),
("Ldr", ctypes.c_void_p),
# ...
]
class OVERLAPPED(ctypes.Structure):
_fields_ = [
("Internal", ctypes.c_void_p),
("InternalHigh", ctypes.c_void_p),
("Offset", ctypes.c_ulong),
("OffsetHigh", ctypes.c_ulong),
("hEvent", ctypes.c_void_p)
]
class kernel32:
dll = ctypes.WinDLL('kernel32.dll')
GetCurrentProcess = _win_api(dll.GetCurrentProcess, ctypes.c_void_p, (), error_zero=True)
CreateToolhelp32Snapshot = _win_api(dll.CreateToolhelp32Snapshot, ctypes.c_void_p, (ctypes.c_ulong, ctypes.c_ulong), error_val=INVALID_HANDLE_VALUE)
Process32First = _win_api(dll.Process32First, ctypes.c_bool, (ctypes.c_void_p, ctypes.c_void_p), error_zero=True)
Process32Next = _win_api(dll.Process32Next, ctypes.c_bool, (ctypes.c_void_p, ctypes.c_void_p), error_zero=True)
CloseHandle = _win_api(dll.CloseHandle, ctypes.c_bool, (ctypes.c_void_p,), error_zero=True)
OpenProcess = _win_api(dll.OpenProcess, ctypes.c_void_p, (ctypes.c_ulong, ctypes.c_bool, ctypes.c_ulong), error_zero=True)
CreateRemoteThread = _win_api(dll.CreateRemoteThread, ctypes.c_void_p, (ctypes.c_void_p, ctypes.c_void_p, ctypes.c_size_t, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_ulong, ctypes.c_void_p), error_zero=True)
ReadProcessMemory = _win_api(dll.ReadProcessMemory, ctypes.c_bool, (ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_size_t, ctypes.c_void_p), error_zero=True)
WriteProcessMemory = _win_api(dll.WriteProcessMemory, ctypes.c_bool, (ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_size_t, ctypes.c_void_p), error_zero=True)
VirtualAllocEx = _win_api(dll.VirtualAllocEx, ctypes.c_void_p, (ctypes.c_void_p, ctypes.c_void_p, ctypes.c_size_t, ctypes.c_ulong, ctypes.c_ulong), error_val=0)
VirtualFreeEx = _win_api(dll.VirtualFreeEx, ctypes.c_bool, (ctypes.c_void_p, ctypes.c_void_p, ctypes.c_size_t, ctypes.c_ulong), error_zero=True)
VirtualProtectEx = _win_api(dll.VirtualProtectEx, ctypes.c_bool, (ctypes.c_void_p, ctypes.c_void_p, ctypes.c_size_t, ctypes.c_ulong, ctypes.c_void_p), error_zero=True)
VirtualQueryEx = _win_api(dll.VirtualQueryEx, ctypes.c_size_t, (ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_size_t), error_zero=True)
GetProcAddress = _win_api(dll.GetProcAddress, ctypes.c_void_p, (ctypes.c_void_p, ctypes.c_char_p), error_zero=True)
GetModuleHandle = _win_api(dll.GetModuleHandleW, ctypes.c_size_t, (ctypes.c_wchar_p,), error_val=0)
GetCurrentProcessId = _win_api(dll.GetCurrentProcessId, ctypes.c_ulong, (), error_zero=True)
WaitForSingleObject = _win_api(dll.WaitForSingleObject, ctypes.c_ulong, (ctypes.c_void_p, ctypes.c_ulong), error_val=0xFFFFFFFF)
CreateEvent = _win_api(dll.CreateEventW, ctypes.c_void_p, (ctypes.c_void_p, ctypes.c_bool, ctypes.c_bool, ctypes.c_wchar_p), error_val=INVALID_HANDLE_VALUE)
WriteFile = _win_api(dll.WriteFile, ctypes.c_bool, (ctypes.c_void_p, ctypes.c_char_p, ctypes.c_ulong, ctypes.c_void_p, ctypes.c_void_p), error_zero=True)
ReadFile = _win_api(dll.ReadFile, ctypes.c_bool, (ctypes.c_void_p, ctypes.c_void_p, ctypes.c_ulong, ctypes.c_void_p, ctypes.c_void_p), error_zero=True)
GetOverlappedResult = _win_api(dll.GetOverlappedResult, ctypes.c_bool, (ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_bool), error_zero=True)
CreateNamedPipe = _win_api(dll.CreateNamedPipeW, ctypes.c_void_p, (ctypes.c_wchar_p, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_void_p), error_val=INVALID_HANDLE_VALUE)
ConnectNamedPipe = _win_api(dll.ConnectNamedPipe, ctypes.c_bool, (ctypes.c_void_p, ctypes.c_void_p), error_zero=True)
CreateFile = _win_api(dll.CreateFileW, ctypes.c_void_p, (ctypes.c_wchar_p, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_void_p, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_void_p), error_val=INVALID_HANDLE_VALUE)
SetNamedPipeHandleState = _win_api(dll.SetNamedPipeHandleState, ctypes.c_bool, (ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p), error_zero=True)
class advapi32:
dll = ctypes.WinDLL('advapi32.dll')
OpenProcessToken = _win_api(dll.OpenProcessToken, ctypes.c_long, (ctypes.c_void_p, ctypes.c_ulong, ctypes.c_void_p), error_zero=True)
LookupPrivilegeName = _win_api(dll.LookupPrivilegeNameW, ctypes.c_long, (ctypes.c_wchar_p, ctypes.c_void_p, ctypes.c_wchar_p, ctypes.c_void_p), error_zero=True)
LookupPrivilegeValue = _win_api(dll.LookupPrivilegeValueW, ctypes.c_long, (ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_void_p), error_zero=True)
AdjustTokenPrivileges = _win_api(dll.AdjustTokenPrivileges, ctypes.c_long, (ctypes.c_void_p, ctypes.c_long, ctypes.c_void_p, ctypes.c_ulong, ctypes.c_void_p, ctypes.c_void_p), error_zero=True)
class ntdll:
dll = ctypes.WinDLL('ntdll.dll')
NtQueryInformationProcess = _win_api(dll.NtQueryInformationProcess, ctypes.c_long, (ctypes.c_void_p, ctypes.c_ulong, ctypes.c_void_p, ctypes.c_ulong, ctypes.c_void_p), error_nonzero=True)
def pid_by_executable(executable_name: bytes | str):
if isinstance(executable_name, str):
executable_name = executable_name.encode(DEFAULT_CODING)
def _iter_processes():
class ProcessEntry32(ctypes.Structure):
_fields_ = [
('dwSize', ctypes.c_ulong),
('cntUsage', ctypes.c_ulong),
('th32ProcessID', ctypes.c_ulong),
('th32DefaultHeapID', ctypes.POINTER(ctypes.c_ulong)),
('th32ModuleID', ctypes.c_ulong),
('cntThreads', ctypes.c_ulong),
('th32ParentProcessID', ctypes.c_ulong),
('pcPriClassBase', ctypes.c_ulong),
('dwFlags', ctypes.c_ulong),
('szExeFile', ctypes.c_char * ctypes.wintypes.MAX_PATH)
]
hSnap = kernel32.CreateToolhelp32Snapshot(0x00000002, 0) # SNAPPROCESS
process_entry = ProcessEntry32()
process_entry.dwSize = ctypes.sizeof(process_entry)
kernel32.Process32First(hSnap, ctypes.byref(process_entry))
try:
yield process_entry
while 1:
yield process_entry
kernel32.Process32Next(hSnap, ctypes.byref(process_entry))
except WindowsError as e:
if e.winerror != 18:
raise
finally:
kernel32.CloseHandle(hSnap)
for process in _iter_processes():
if process.szExeFile == executable_name:
yield process.th32ProcessID
def enable_privilege():
hProcess = ctypes.c_void_p(kernel32.GetCurrentProcess())
if advapi32.OpenProcessToken(hProcess, 32, ctypes.byref(hProcess)):
tkp = TOKEN_PRIVILEGES()
advapi32.LookupPrivilegeValue(None, "SeDebugPrivilege", ctypes.byref(tkp.Privileges[0].Luid))
tkp.count = 1
tkp.Privileges[0].Attributes = 2
advapi32.AdjustTokenPrivileges(hProcess, 0, ctypes.byref(tkp), 0, None, None)
_aligned4 = lambda v: (v + 0x3) & (~0x3)
_aligned16 = lambda v: (v + 0xf) & (~0xf)
class _Pattern:
fl_is_ref = 1 << 0
fl_is_byes = 1 << 1
fl_store = 1 << 2
hex_chars = set(b'0123456789abcdefABCDEF')
dec_chars = set(b'0123456789')
special_chars_map = {i for i in b'()[]{}?*+-|^$\\.&~# \t\n\r\v\f'}
@classmethod
def take_dec_number(cls, pattern: str, i: int):
assert i < len(pattern) and ord(pattern[i]) in cls.dec_chars
j = i + 1
while j < len(pattern) and ord(pattern[j]) in cls.dec_chars:
j += 1
return int(pattern[i:j]), j
@classmethod
def take_cnt(cls, pattern: str, i: int, regex_pattern: bytearray):
if i < len(pattern) and pattern[i] == '{':
regex_pattern.append(123) # {
n1, i = cls.take_dec_number(pattern, i + 1)
regex_pattern.extend(str(n1).encode())
if pattern[i] == ':':
n2, i = cls.take_dec_number(pattern, i + 1)
assert n1 <= n2
regex_pattern.append(44) # ,
regex_pattern.extend(str(n2).encode())
assert pattern[i] == '}'
regex_pattern.append(125) # }
i += 1
return i
@classmethod
def take_byte(cls, pattern: str, i: int, regex_pattern: bytearray):
assert i + 2 <= len(pattern)
next_byte = int(pattern[i:i + 2], 16)
if next_byte in cls.special_chars_map:
regex_pattern.append(92) # \
regex_pattern.append(next_byte)
return i + 2
@classmethod
def _take_unk(cls, pattern: str, i: int):
start_chr = pattern[i]
assert start_chr in ('?', '*', '^')
if i + 1 < len(pattern) and pattern[i + 1] == start_chr:
i += 1
return start_chr, i + 1
@classmethod
def take_unk(cls, pattern: str, i: int, regex_pattern: bytearray):
start_unk, i = cls._take_unk(pattern, i)
regex_pattern.append(46)
i = cls.take_cnt(pattern, i, regex_pattern)
while i < len(pattern):
match pattern[i]:
case ' ':
i += 1
case c if c == start_unk:
start_unk, i = cls._take_unk(pattern, i)
regex_pattern.append(46)
i = cls.take_cnt(pattern, i, regex_pattern)
case _:
break
return start_unk, i
@classmethod
def _compile_pattern(cls, pattern: str, i=0, ret_at=None):
_i = i
regex_pattern = bytearray()
sub_matches = []
group_flags = []
while i < len(pattern):
match pattern[i]:
case ' ':
i += 1
case '[':
regex_pattern.append(91) # [
i += 1
i = cls.take_byte(pattern, i, regex_pattern)
while True:
match pattern[i]:
case ' ':
i += 1
case ']':
regex_pattern.append(93) # ]
i += 1
break
case '|':
i = cls.take_byte(pattern, i + 1, regex_pattern)
case ':':
regex_pattern.append(45) # -
i = cls.take_byte(pattern, i + 1, regex_pattern)
case c:
raise ValueError(f'Invalid character {c} in pattern {pattern!r} at {i}')
case '(':
base_flag = 0 # not fl_store
regex_pattern.append(40) # (
unk_type, i = cls.take_unk(pattern, i + 1, regex_pattern)
if unk_type == '*':
base_flag |= cls.fl_is_ref
elif unk_type == '^':
base_flag |= cls.fl_is_byes
sub_pattern = None
while True:
match pattern[i]:
case ' ':
i += 1
case ')':
regex_pattern.append(41) # )
i += 1
break
case ':':
sub_pattern, i = cls._compile_pattern(pattern, i + 1, ret_at=')')
assert pattern[i] == ')', f'Expected ) get {pattern[i]} at {i} in pattern {pattern!r}'
regex_pattern.append(41)
i += 1
break
case c:
raise ValueError(f'Invalid character {c} in pattern {pattern!r} at {i}')
group_flags.append(base_flag)
sub_matches.append(sub_pattern)
case '<':
base_flag = cls.fl_store
regex_pattern.append(40)
unk_type, i = cls.take_unk(pattern, i + 1, regex_pattern)
if unk_type == '*':
base_flag |= cls.fl_is_ref
elif unk_type == '^':
base_flag |= cls.fl_is_byes
sub_pattern = None
while True:
match pattern[i]:
case ' ':
i += 1
case '>':
regex_pattern.append(41)
i += 1
break
case ':':
sub_pattern, i = cls._compile_pattern(pattern, i + 1, ret_at='>')
assert pattern[i] == '>', f'Expected > get {pattern[i]} at {i} in pattern {pattern!r}'
regex_pattern.append(41)
i += 1
break
case c:
raise ValueError(f'Invalid character {c} in pattern {pattern!r} at {i}')
group_flags.append(base_flag)
sub_matches.append(sub_pattern)
case '?' | '*' | '^' as c:
regex_pattern.append(40)
unk_type, i = cls.take_unk(pattern, i, regex_pattern)
regex_pattern.append(41)
if c == '?':
group_flags.append(0)
elif c == '*':
group_flags.append(cls.fl_is_ref | cls.fl_store)
elif c == '^':
group_flags.append(cls.fl_is_byes | cls.fl_store)
else:
raise ValueError(f'Invalid character {c} in pattern {pattern!r} at {i}')
sub_matches.append(None)
case c if ord(c) in cls.hex_chars:
i = cls.take_byte(pattern, i, regex_pattern)
i = cls.take_cnt(pattern, i, regex_pattern)
case c if c == ret_at:
break
case c:
fmt_pattern = pattern[:i] + '_' + pattern[i] + '_' + pattern[i + 1:]
raise ValueError(f'Invalid character {c} in pattern {fmt_pattern!r} at {i} (ret_at={ret_at})')
try:
regex = re.compile(bytes(regex_pattern), re.DOTALL)
except re.error as e:
raise ValueError(f'{e}: ({pattern!r}, {_i}, {ret_at!r}) -> {bytes(regex_pattern)}')
return Pattern(regex, sub_matches, group_flags, pattern), i
@classmethod
def compile_pattern(cls, pattern: str):
return cls._compile_pattern(pattern)[0]
@classmethod
def fmt_bytes_regex_pattern(cls, pat: bytes):
s = ''
is_escape = False
is_in_bracket = 0
for b in pat:
if is_escape:
is_escape = False
s += f'\\x{b:02x}'
elif b == 92: # \
is_escape = True
elif b in cls.special_chars_map:
if b == 123: # {
is_in_bracket += 1
elif b == 125: # }
is_in_bracket -= 1
s += chr(b)
elif is_in_bracket:
s += chr(b)
else:
s += f'\\x{b:02x}'
return s
class Pattern:
def __init__(self, regex: re.Pattern, sub_matches: 'typing.List[None | Pattern]', group_flags, pattern: str):
self.regex = regex
self.sub_matches = sub_matches
self.group_flags = group_flags
self.pattern = pattern
self.res_is_ref = []
for i, (sub, flag) in enumerate(zip(sub_matches, group_flags)):
if flag & _Pattern.fl_store:
self.res_is_ref.append(flag & _Pattern.fl_is_ref)
if sub is not None:
self.res_is_ref.extend(sub.res_is_ref)
def finditer(self, _data: bytes | bytearray | memoryview, ref_base=0):
data = _data if isinstance(_data, memoryview) else memoryview(_data)
for match in self.regex.finditer(data):
res = []
if self._parse_match(data, match, res, ref_base):
yield match.start(0), res
def _parse_match(self, data: memoryview, match: re.Match, res: list, ref_base=0):
for i, (sub_match, flag) in enumerate(zip(self.sub_matches, self.group_flags)):
if flag & _Pattern.fl_is_byes:
res.append(match.group(i + 1))
else:
val = int.from_bytes(match.group(i + 1), 'little', signed=True)
if flag & _Pattern.fl_is_ref:
val += match.end(i + 1)
if flag & _Pattern.fl_store:
res.append(val)
if sub_match is not None:
start = val if flag & _Pattern.fl_is_ref else val - ref_base
if start < 0 or start >= len(data):
return False
if not sub_match._match(data, start, res, ref_base):
return False
return True
def _match(self, _data: memoryview, start_at: int, res: list, ref_base=0):
if not (match := self.regex.match(_data, start_at)): return False
return self._parse_match(_data, match, res, ref_base)
def fmt(self, ind: str | int = ' ', _ind=0):
if isinstance(ind, int): ind = ' ' * ind
s = io.StringIO()
s.write(ind * _ind)
s.write(_Pattern.fmt_bytes_regex_pattern(self.regex.pattern))
s.write('\n')
s.write(ind * _ind)
s.write('res is ref:')
for flag in self.res_is_ref:
s.write(' ref' if flag else ' val')
s.write('\n')
for i, (sub, flag) in enumerate(zip(self.sub_matches, self.group_flags)):
s.write(ind * _ind)
s.write(f'{i}:{"ref" if flag & _Pattern.fl_is_ref else "val"}{" store" if flag & _Pattern.fl_store else ""}\n')
if sub is not None:
s.write(sub.fmt(ind, _ind + 1))
s.write('\n')
return s.getvalue().rstrip()
class IPatternScanner:
def search(self, pattern: str | Pattern) -> typing.Generator[tuple[int, list[int]], None, None]:
raise NotImplementedError
def search_unique(self, pattern: str | Pattern) -> tuple[int, list[int]]:
s = self.search(pattern)
try:
res = next(s)
except StopIteration:
raise KeyError('pattern not found')
try:
next(s)
except StopIteration:
return res
raise KeyError('pattern is not unique, at least 2 is found')
def find_addresses(self, pattern: str | Pattern):
for address, _ in self.search(pattern):
yield address
def find_vals(self, pattern: str | Pattern):
for address, args in self.search(pattern):
yield args
def find_address(self, pattern: str | Pattern):
return self.search_unique(pattern)[0]
def find_val(self, pattern: str | Pattern):
return self.search_unique(pattern)[1]
try:
import win32file, win32pipe, win32event
except ImportError:
has_win32 = False
else:
has_win32 = True
class PipeHandlerBase:
active_pipe_handler = {}
buf_size = 64 * 1024
handle = None
period = .001
def __init__(self):
self.serve_thread = threading.Thread(target=self.serve, daemon=True)
self.work = False
self.is_connected = threading.Event()
if has_win32:
def send(self, s: bytes):
win32file.WriteFile(self.handle, s, win32file.OVERLAPPED())
def _serve(self):
tid = threading.get_ident()
PipeHandlerBase.active_pipe_handler[tid] = self
try:
self.is_connected.set()
self.work = True
overlapped = win32file.OVERLAPPED()
overlapped.hEvent = win32event.CreateEvent(None, True, False, None)
while self.work:
err, buf = win32file.ReadFile(self.handle, self.buf_size, overlapped)
num_read = win32file.GetOverlappedResult(self.handle, overlapped, True)
self.on_data_received(bytes(buf[:num_read]))
finally:
if PipeHandlerBase.active_pipe_handler[tid] is self:
PipeHandlerBase.active_pipe_handler.pop(tid, None)
else:
def send(self, s: bytes):
kernel32.WriteFile(self.handle, s, len(s), None, ctypes.byref(OVERLAPPED()))
def _serve(self):
tid = threading.get_ident()
PipeHandlerBase.active_pipe_handler[tid] = self
try:
self.is_connected.set()
self.work = True
buf = ctypes.create_string_buffer(self.buf_size + 0x10)
size = ctypes.c_ulong()
overlapped = OVERLAPPED()
overlapped.hEvent = kernel32.CreateEvent(None, True, False, None)
while self.work:
try:
kernel32.ReadFile(self.handle, buf, self.buf_size, 0, ctypes.byref(overlapped))
except WindowsError as e:
if e.winerror != 997: raise
kernel32.WaitForSingleObject(overlapped.hEvent, -1)
kernel32.GetOverlappedResult(self.handle, ctypes.byref(overlapped), ctypes.byref(size), True)
self.on_data_received(bytes(buf[:size.value]))
finally:
if PipeHandlerBase.active_pipe_handler[tid] is self:
PipeHandlerBase.active_pipe_handler.pop(tid, None)
def serve(self):
try:
self.on_connect()
self._serve()
except Exception as e:
self.on_close(e)
else:
self.on_close(None)
finally:
try:
kernel32.CloseHandle(self.handle)
except Exception:
pass
def close(self, block=True):
self.work = False
kernel32.CloseHandle(self.handle)
if block: self.serve_thread.join()
def on_connect(self):
pass
def on_close(self, e: Exception | None):
pass
def on_data_received(self, data: bytes):
pass
class PipeServerHandler(PipeHandlerBase):
def __init__(self, server: 'PipeServer', handle, client_id):
self.server = server
self.handle = handle
self.client_id = client_id
self.buf_size = server.buf_size
super().__init__()
def serve(self):
self.server.handlers[self.client_id] = self
super().serve()
self.server.handlers.pop(self.client_id, None)
class PipeServer(typing.Generic[_T]):
handlers: typing.Dict[int, _T]
def __init__(self, name, buf_size=64 * 1024, handler_class=PipeServerHandler):
self.name = name
self.buf_size = buf_size
self.handler_class = handler_class
self.serve_thread = threading.Thread(target=self.serve)
self.client_counter = 0
self.handlers = {}
self.work = False
def serve(self):
self.work = True
while self.work:
handle = kernel32.CreateNamedPipe(
self.name,
0x3 | 0x40000000, # PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED
0x4 | 0x2 | 0x0, # PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT
255, # PIPE_UNLIMITED_INSTANCES
self.buf_size, self.buf_size, 0, None
)
kernel32.ConnectNamedPipe(handle, None)
c = self.handler_class(self, handle, self.client_counter)
c.buf_size = self.buf_size
c.serve_thread.start()
self.client_counter += 1
def close(self):
self.work = False
while self.handlers:
next_key = next(iter(self.handlers.keys()))
self.handlers.pop(next_key).close(False)
try:
_FlushClient(self.name, timeout=1).serve()
except TimeoutError:
pass
def send_all(self, s):
for c in self.handlers.values():
c.send(s)
class PipeClient(PipeHandlerBase):
def __init__(self, name: str, buf_size=64 * 1024, timeout=0):
self.name = name
self.buf_size = buf_size
self.timeout = timeout
super().__init__()
def _connect(self):
start = time.perf_counter()
while True:
if self.timeout and time.perf_counter() - start > self.timeout:
raise TimeoutError()
try:
self.handle = kernel32.CreateFile(
self.name,
0x80000000 | 0x40000000, # GENERIC_READ | GENERIC_WRITE
0, # 0x1 | 0x2, # FILE_SHARE_READ | FILE_SHARE_WRITE
None,
0x3, # OPEN_EXISTING
0x40000000, # FILE_FLAG_OVERLAPPED
None
)
except WindowsError as e:
if e.winerror == 0xe7: # ERROR_PIPE_BUSY
time.sleep(1)
continue
if e.winerror == 0x2: # ERROR_FILE_NOT_FOUND
time.sleep(1)
continue
raise
else:
break
mode = ctypes.c_ulong(0x2) # PIPE_READMODE_MESSAGE
kernel32.SetNamedPipeHandleState(self.handle, ctypes.byref(mode), None, None)
def serve(self):
self._connect()
super().serve()
def connect(self):
self.serve_thread.start()
self.is_connected.wait()
def __enter__(self):
if not self.is_connected.is_set():
self.connect()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.close()
class _FlushClient(PipeClient):
def on_connect(self):
self.close()
class _Rpc:
CLIENT_CALL = 0
CLIENT_SUBSCRIBE = 1
CLIENT_UNSUBSCRIBE = 2
SERVER_RETURN = 0
SERVER_EVENT = 1
RETURN_NORMAL = 0
RETURN_EXCEPTION = 1
RETURN_GENERATOR = 2
RETURN_GENERATOR_END = 3
REMOTE_TRACE_KEY = '_remote_trace'
@classmethod
def format_exc(cls, e):
return getattr(e, cls.REMOTE_TRACE_KEY, None) or traceback.format_exc()
@classmethod
def set_exc(cls, e, tb):
setattr(e, cls.REMOTE_TRACE_KEY, tb)
return e
class RpcHandler(PipeServerHandler):
server: 'RpcServer'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.subscribed = set()
def on_data_received(self, data: bytes):
cmd, *arg = pickle.loads(data)
if cmd == _Rpc.CLIENT_CALL: # call
threading.Thread(target=self.handle_call, args=arg).start()
elif cmd == _Rpc.CLIENT_SUBSCRIBE: # subscribe
key, = arg
if key not in self.subscribed:
self.subscribed.add(key)
self.server.add_subscribe(key, self.client_id)
elif cmd == _Rpc.CLIENT_UNSUBSCRIBE: # unsubscribe
key, = arg
if key in self.subscribed:
self.subscribed.remove(key)
self.server.remove_subscribe(key, self.client_id)
def on_close(self, e: Exception | None):
for k in self.subscribed:
self.server.remove_subscribe(k, self.client_id)
def handle_call(self, reply_id, key, arg, kwargs):
try:
res = self.server.call_map[key](*arg, *kwargs)
except Exception as e:
self.reply_call_exc(reply_id, e)
else:
if isinstance(res, types.GeneratorType):
self.reply_call_gen(reply_id, res)
else:
self.reply_call_normal(reply_id, res)
def reply_call_normal(self, reply_id, res):
self.send(pickle.dumps((_Rpc.SERVER_RETURN, reply_id, _Rpc.RETURN_NORMAL, res)))
def reply_call_exc(self, reply_id, exc):
self.send(pickle.dumps((_Rpc.SERVER_RETURN, reply_id, _Rpc.RETURN_EXCEPTION, (exc, traceback.format_exc()))))
def reply_call_gen(self, reply_id, gen):
try:
for res in gen:
self.send(pickle.dumps((_Rpc.SERVER_RETURN, reply_id, _Rpc.RETURN_GENERATOR, res)))
self.send(pickle.dumps((_Rpc.SERVER_RETURN, reply_id, _Rpc.RETURN_GENERATOR_END, None)))
except Exception as e:
self.reply_call_exc(reply_id, e)
def send_event(self, event_id, event):
self.send(pickle.dumps((_Rpc.SERVER_EVENT, event_id, event)))
class RpcServer(PipeServer[RpcHandler]):
def __init__(self, name, call_map, *args, **kwargs):
super().__init__(name, *args, handler_class=RpcHandler, **kwargs)
self.subscribe_map = {}
if isinstance(call_map, (tuple, list,)):
call_map = {i.__name__: i for i in call_map}
self.call_map = call_map
def push_event(self, event_id, data):
cids = self.subscribe_map.get(event_id, set())
for cid in list(cids):
if client := self.handlers.get(cid):
client.send_event(event_id, data)
else:
try:
cids.remove(cid)
except KeyError:
pass
def add_subscribe(self, key, cid):
if not (s := self.subscribe_map.get(key)):
self.subscribe_map[key] = s = set()
s.add(cid)
def remove_subscribe(self, key, cid):
if s := self.subscribe_map.get(key):
try:
s.remove(cid)
except KeyError:
pass
if not s:
self.subscribe_map.pop(key, None)
class Counter:
def __init__(self, start=0):
self.value = start
self.lock = threading.Lock()
def get(self):
with self.lock:
self.value += 1
return self.value
class RpcClient(PipeClient):
class ResEventList(typing.Generic[_T]):
class ResEvent(threading.Event, typing.Generic[_T]):
def __init__(self):
super().__init__()
self.res = None
self.is_exc = False
self.is_waiting = False
def set(self, data: _T = None) -> None:
assert not self.is_set()
self.res = data
self.is_exc = False
super().set()
def set_exception(self, exc) -> None:
assert not self.is_set()
self.res = exc
self.is_exc = True
super().set()
def wait(self, timeout: float | None = None) -> _T:
self.is_waiting = True
try:
if super().wait(timeout):
if self.is_exc:
raise self.res
else:
return self.res
else:
raise TimeoutError()
finally:
self.is_waiting = False
queue: typing.List[ResEvent[_T]]
def __init__(self):
self.queue = [self.ResEvent()]
self.lock = threading.Lock()
def put(self, data: _T):
with self.lock:
if not self.queue or self.queue[-1].is_set():
self.queue.append(self.ResEvent())
self.queue[-1].set(data)
def get(self) -> _T:
with self.lock:
if not self.queue:
self.queue.append(self.ResEvent())
evt = self.queue[0]
res = evt.wait()
with self.lock:
if self.queue and self.queue[0] is evt:
self.queue.pop(0)
return res
reply_map: typing.Dict[int, ResEventList]
logger = logging.getLogger('RpcClient')
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.reply_map = {}
self.subscribe_map = {}
self.counter = Counter()
class Rpc:
def __getattr__(_self, item):
def func(*_args, **_kwargs):
return self.remote_call(item, _args, _kwargs)
func.__name__ = item
return func
self.rpc = Rpc()
def on_data_received(self, data: bytes):
cmd, *args = pickle.loads(data)
if cmd == _Rpc.SERVER_RETURN:
reply_id, reply_type, res = args
if l := self.reply_map.get(reply_id):
l.put((reply_type, res))
elif cmd == _Rpc.SERVER_EVENT:
key, data = args
s = self.subscribe_map.get(key, set())
if s:
for c in s:
try:
c(key, data)
except Exception as e: