Repository navigation
Expand file tree
/
Copy patha3x.py
More file actions
904 lines (856 loc) · 23.5 KB
/
Copy patha3x.py
File metadata and controls
904 lines (856 loc) · 23.5 KB
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
from __future__ import annotations
import codecs
import io
import math
import struct
from enum import Enum
from typing import Generator, Iterable, NamedTuple
from refinery.lib.dt import filetime
from refinery.lib.fast.a3x import a3x_decompress, a3x_decrypt
from refinery.lib.id import buffer_contains
from refinery.lib.structures import MemoryFile, Struct, StructReader
from refinery.units.formats import PathExtractorUnit, UnpackResult
A3X_KEYWORDS = [
'',
'And',
'Or',
'Not',
'If',
'Then',
'Else',
'ElseIf',
'EndIf',
'While',
'Wend',
'Do',
'Until',
'For',
'Next',
'To',
'Step',
'In',
'ExitLoop',
'ContinueLoop',
'Select',
'Case',
'EndSelect',
'Switch',
'EndSwitch',
'ContinueCase',
'Dim',
'ReDim',
'Local',
'Global',
'Const',
'Static',
'Func',
'EndFunc',
'Return',
'Exit',
'ByRef',
'With',
'EndWith',
'True',
'False',
'Default',
'Null',
'Volatile',
'Enum',
]
A3X_APICALLS = [
'Abs',
'Acos',
'AdlibRegister',
'AdlibUnRegister',
'Asc',
'AscW',
'ASin',
'Assign',
'ATan',
'AutoItSetOption',
'AutoItWinGetTitle',
'AutoItWinSetTitle',
'Beep',
'Binary',
'BinaryLen',
'BinaryMid',
'BinaryToString',
'BitAnd',
'BitNot',
'BitOR',
'BitRotate',
'BitShift',
'BitXOR',
'BlockInput',
'Break',
'Call',
'CDTray',
'Ceiling',
'Chr',
'ChrW',
'ClipGet',
'ClipPut',
'ConsoleRead',
'ConsoleWrite',
'ConsoleWriteError',
'ControlClick',
'ControlCommand',
'ControlDisable',
'ControlEnable',
'ControlFocus',
'ControlGetFocus',
'ControlGetHandle',
'ControlGetPos',
'ControlGetText',
'ControlHide',
'ControlListView',
'ControlMove',
'ControlSend',
'ControlSetText',
'ControlShow',
'ControlTreeView',
'Cos',
'Dec',
'DirCopy',
'DirCreate',
'DirGetSize',
'DirMove',
'DirRemove',
'DllCall',
'DllCallAddress',
'DllCallbackFree',
'DllCallbackGetPtr',
'DllCallbackRegister',
'DllClose',
'DllOpen',
'DllStructCreate',
'DllStructGetData',
'DllStructGetPtr',
'DllStructGetSize',
'DllStructSetData',
'DriveGetDrive',
'DriveGetFilesystem',
'DriveGetLabel',
'DriveGetSerial',
'DriveGetType',
'DriveMapAdd',
'DriveMapDel',
'DriveMapGet',
'DriveSetLabel',
'DriveSpaceFree',
'DriveSpaceTotal',
'DriveStatus',
'DummySpeedTest',
'EnvGet',
'EnvSet',
'EnvUpdate',
'Eval',
'Execute',
'Exp',
'FileChangeDir',
'FileClose',
'FileCopy',
'FileCreateNTFSLink',
'FileCreateShortcut',
'FileDelete',
'FileExists',
'FileFindFirstFile',
'FileFindNextFile',
'FileFlush',
'FileGetAttrib',
'FileGetEncoding',
'FileGetLongName',
'FileGetPos',
'FileGetShortcut',
'FileGetShortName',
'FileGetSize',
'FileGetTime',
'FileGetVersion',
'FileInstall',
'FileMove',
'FileOpen',
'FileOpenDialog',
'FileRead',
'FileReadLine',
'FileReadToArray',
'FileRecycle',
'FileRecycleEmpty',
'FileSaveDialog',
'FileSelectFolder',
'FileSetAttrib',
'FileSetEnd',
'FileSetPos',
'FileSetTime',
'FileWrite',
'FileWriteLine',
'Floor',
'FtpSetProxy',
'Funcname',
'GUICreate',
'GUICtrlCreateAvi',
'GUICtrlCreateButton',
'GUICtrlCreateCheckbox',
'GUICtrlCreateCombo',
'GUICtrlCreateContextMenu',
'GUICtrlCreateDate',
'GUICtrlCreateDummy',
'GUICtrlCreateEdit',
'GUICtrlCreateGraphic',
'GUICtrlCreateGroup',
'GUICtrlCreateIcon',
'GUICtrlCreateInput',
'GUICtrlCreateLabel',
'GUICtrlCreateList',
'GUICtrlCreateListView',
'GUICtrlCreateListViewItem',
'GUICtrlCreateMenu',
'GUICtrlCreateMenuItem',
'GUICtrlCreateMonthCal',
'GUICtrlCreateObj',
'GUICtrlCreatePic',
'GUICtrlCreateProgress',
'GUICtrlCreateRadio',
'GUICtrlCreateSlider',
'GUICtrlCreateTab',
'GUICtrlCreateTabItem',
'GUICtrlCreateTreeView',
'GUICtrlCreateTreeViewItem',
'GUICtrlCreateUpdown',
'GUICtrlDelete',
'GUICtrlGetHandle',
'GUICtrlGetState',
'GUICtrlRead',
'GUICtrlRecvMsg',
'GUICtrlRegisterListViewSort',
'GUICtrlSendMsg',
'GUICtrlSendToDummy',
'GUICtrlSetBkColor',
'GUICtrlSetColor',
'GUICtrlSetCursor',
'GUICtrlSetData',
'GUICtrlSetDefBkColor',
'GUICtrlSetDefColor',
'GUICtrlSetFont',
'GUICtrlSetGraphic',
'GUICtrlSetImage',
'GUICtrlSetLimit',
'GUICtrlSetOnEvent',
'GUICtrlSetPos',
'GUICtrlSetResizing',
'GUICtrlSetState',
'GUICtrlSetStyle',
'GUICtrlSetTip',
'GUIDelete',
'GUIGetCursorInfo',
'GUIGetMsg',
'GUIGetStyle',
'GUIRegisterMsg',
'GUISetAccelerators',
'GUISetBkColor',
'GUISetCoord',
'GUISetCursor',
'GUISetFont',
'GUISetHelp',
'GUISetIcon',
'GUISetOnEvent',
'GUISetState',
'GUISetStyle',
'GUIStartGroup',
'GUISwitch',
'Hex',
'HotKeySet',
'HttpSetProxy',
'HttpSetUserAgent',
'Hwnd',
'InetClose',
'InetGet',
'InetGetInfo',
'InetGetSize',
'InetRead',
'IniDelete',
'IniRead',
'IniReadSection',
'IniReadSectionNames',
'IniRenameSection',
'IniWrite',
'IniWriteSection',
'InputBox',
'Int',
'IsAdmin',
'IsArray',
'IsBinary',
'IsBool',
'IsDeclared',
'IsDllStruct',
'IsFloat',
'IsFunc',
'IsHwnd',
'IsInt',
'IsKeyword',
'IsMap',
'IsNumber',
'IsObj',
'IsPtr',
'IsString',
'Log',
'MapAppend',
'MapExists',
'MapKeys',
'MapRemove',
'MemGetStats',
'Mod',
'MouseClick',
'MouseClickDrag',
'MouseDown',
'MouseGetCursor',
'MouseGetPos',
'MouseMove',
'MouseUp',
'MouseWheel',
'MsgBox',
'Number',
'ObjCreate',
'ObjCreateInterface',
'ObjEvent',
'ObjGet',
'ObjName',
'OnAutoItExitRegister',
'OnAutoItExitUnRegister',
'Opt',
'Ping',
'PixelChecksum',
'PixelGetColor',
'PixelSearch',
'ProcessClose',
'ProcessExists',
'ProcessGetStats',
'ProcessList',
'ProcessSetPriority',
'ProcessWait',
'ProcessWaitClose',
'ProgressOff',
'Progresson',
'ProgressSet',
'Ptr',
'Random',
'RegDelete',
'RegEnumKey',
'RegEnumVal',
'RegRead',
'RegWrite',
'Round',
'Run',
'RunAs',
'RunAsWait',
'RunWait',
'Send',
'SendKeepActive',
'SetError',
'SetExtended',
'ShellExecute',
'ShellExecuteWait',
'Shutdown',
'Sin',
'Sleep',
'SoundPlay',
'SoundSetWaveVolume',
'SplashImageOn',
'SplashOff',
'SplashTextOn',
'Sqrt',
'SRandom',
'StatusBarGetText',
'StderrRead',
'StdinWrite',
'StdioClose',
'StdoutRead',
'String',
'StringAddCR',
'StringCompare',
'StringFormat',
'StringFromASCIIArray',
'StringInStr',
'StringIsAlNum',
'StringIsAlpha',
'StringIsASCII',
'StringIsDigit',
'StringIsFloat',
'StringIsInt',
'StringIsLower',
'StringIsSpace',
'StringIsUpper',
'StringIsXDigit',
'StringLeft',
'StringLen',
'StringLower',
'StringMid',
'StringRegExp',
'StringRegExpReplace',
'StringReplace',
'StringReverse',
'StringRight',
'StringSplit',
'StringStripCR',
'StringStripWS',
'StringToASCIIArray',
'StringToBinary',
'StringTrimLeft',
'StringTrimRight',
'StringUpper',
'Tan',
'TCPAccept',
'TCPCloseSocket',
'TCPConnect',
'TCPListen',
'TCPNameToIP',
'TCPRecv',
'TCPSend',
'TCPShutdown',
'TCPStartup',
'TimerDiff',
'TimerInit',
'ToolTip',
'TrayCreateItem',
'TrayCreateMenu',
'TrayGetMsg',
'TrayItemDelete',
'TrayItemGetHandle',
'TrayItemGetState',
'TrayItemGetText',
'TrayItemSetOnEvent',
'TrayItemSetState',
'TrayItemSetText',
'TraySetClick',
'TraySetIcon',
'TraySetOnEvent',
'TraySetPauseIcon',
'TraySetState',
'TraySetToolTip',
'TrayTip',
'UBound',
'UDPBind',
'UDPCloseSocket',
'UDPOpen',
'UDPRecv',
'UDPSend',
'UDPShutdown',
'UDPStartup',
'VarGetType',
'WinActivate',
'WinActive',
'WinClose',
'WinExists',
'WinFlash',
'WinGetCaretPos',
'WinGetClassList',
'WinGetClientSize',
'WinGetHandle',
'WinGetPos',
'WinGetProcess',
'WinGetState',
'WinGetText',
'WinGetTitle',
'WinKill',
'WinList',
'WinMenuSelectItem',
'WinMinimizeAll',
'WinMinimizeAllUndo',
'WinMove',
'WinSetOnTop',
'WinSetState',
'WinSetTitle',
'WinSetTrans',
'WinWait',
'WinWaitActive',
'WinWaitClose',
'WinWaitNotActive',
]
A3X_OPCODES = {
0x00: R'{k}', # KEYWORD
0x01: R'{a}', # API
0x05: R'{i}', # INT
0x10: R'{q}', # INT64
0x20: R'{d}', # DOUBLE
0x30: R'{s}', # CONSTRUCT
0x31: R'{s}', # COMMAND
0x32: '@{s}', # MACRO
0x33: '${s}', # VAR
0x34: R'{s}', # FUNC
0x35: '.{s}', # OBJECT
0x36: R'{r}', # STRING
0x37: R'{s}', # DIRECTIVE
0x40: ',',
0x41: '=',
0x42: '>',
0x43: '<',
0x44: '<>',
0x45: '>=',
0x46: '<=',
0x47: '(',
0x48: ')',
0x49: '+',
0x4a: '-',
0x4b: '/',
0x4c: '*',
0x4d: '&',
0x4e: '[',
0x4f: ']',
0x50: '==',
0x51: '^',
0x52: '+=',
0x53: '-=',
0x54: '/=',
0x55: '*=',
0x56: '&=',
0x57: '?',
0x58: ':',
}
_PRETTY: dict[str, str] = {}
_PRETTY.update((name.lower(), name) for name in A3X_APICALLS)
_PRETTY.update((name.lower(), name) for name in A3X_KEYWORDS)
def a3x_number_representation(value: float | int) -> str:
"""
The AutoIt3 compiler will emit constants for -inf/inf/nan. However, AutoIt3 itself has no
keywords for these values; The output of this function is valid AutoIt3 code that will
produce these constants.
https://www.autoitscript.com/autoit3/docs/functions/Dec.htm
"""
if isinstance(value, int):
return str(value)
elif math.isnan(value) or math.isinf(value):
rep = struct.pack('>d', value).hex().upper()
return RF'Dec("{rep}", 3)'
else:
return RF'{value!s}'
def a3x_decompile(bytecode: bytearray | memoryview) -> Generator[tuple[int, str]]:
class _decompiler(dict):
def __missing__(self, key):
if key == 's':
string = reader.read_length_prefixed_string()
return _PRETTY.get(string.lower(), string)
elif key == 'r':
string = reader.read_length_prefixed_string()
return '"{}"'.format(string.replace('"', '""'))
elif key == 'k':
return A3X_KEYWORDS[reader.u32()]
elif key == 'a':
return A3X_APICALLS[reader.u32()]
elif key == 'i':
number = reader.i32()
elif key == 'q':
number = reader.i64()
elif key == 'd':
number = reader.f64()
else:
raise KeyError(key)
if number < 0 and tokens and tokens[~0] == '+':
number = -number
tokens[~0] = '-'
return a3x_number_representation(number)
decompiler = _decompiler()
reader = A3xReader(memoryview(bytecode))
num_lines = reader.u32()
tokens: list[str] = []
expected_terminators: list[str] = []
line = 0
while line < num_lines and not reader.eof:
opc = reader.u8()
if opc == 0x7f:
if not tokens:
continue
indent = len(expected_terminators)
lt = [t.lower() for t in tokens]
if lt[0] == 'if' and lt[~0] == 'then':
expected_terminators.append('endif')
elif lt[0] == 'else':
if not expected_terminators or expected_terminators[~0] != 'endif':
raise ValueError(F'Unexpected {tokens[0]} in line {line}.')
indent -= 1
elif lt[0] == 'case':
if not expected_terminators or not expected_terminators[~0].startswith('ends'):
raise ValueError(F'Unexpected {tokens[0]} in line {line}.')
indent -= 1
elif lt[0] == 'while':
expected_terminators.append('wend')
elif lt[0] == 'do':
expected_terminators.append('until')
elif lt[0] == 'for':
expected_terminators.append('next')
elif lt[0] == 'select':
expected_terminators.append('endselect')
elif lt[0] == 'switch':
expected_terminators.append('endswitch')
elif lt[0] == 'func':
expected_terminators.append('endfunc')
elif lt[0] == 'with':
expected_terminators.append('endwith')
elif lt[0].startswith('end') or lt[0] in {'next', 'until', 'wend'}:
try:
expected = expected_terminators.pop()
except IndexError:
expected = None
if lt[0] != expected:
expected = expected and F', expected {_PRETTY[expected]}' or ''
raise ValueError(
F'Unexpected {tokens[0]} in line {line}{expected}.')
indent -= 1
if not indent and len(expected_terminators) > 0:
yield (0, '')
output = io.StringIO()
for k, token in enumerate(tokens):
space = True
space = space and k > 0
space = space and token not in ')],'
space = space and not (token in '([' and tokens[k - 1][~0].isalnum())
space = space and tokens[k - 1] not in '(['
space = space and not token.startswith('.')
if space:
output.write(' ')
output.write(token)
yield (indent, output.getvalue())
line += 1
tokens.clear()
else:
opt = A3X_OPCODES[opc]
if opc < 0x40:
opt = opt.format_map(decompiler)
tokens.append(opt)
if expected_terminators:
raise ValueError('Script truncated.')
class A3xType(str, Enum):
UNICODE = 'AUTOIT UNICODE SCRIPT'
SCRIPT = 'AUTOIT SCRIPT'
NOEXEC = 'AUTOIT NO CMDEXECUTE'
AHK_SCRIPT = 'AUTOHOTKEY SCRIPT'
AHK_WITH_ICON = 'AHK WITH ICON'
class A3xEncryptionConstants(NamedTuple):
version: bytes
tag_size: int
tag: int
path_size: int
path: int
compressed_size: int
decompressed_size: int
checksum: int
data: int
is_current: bool
class A3xEncryptionType(A3xEncryptionConstants, Enum):
EA06 = (b'AU3!EA06', 0xADBC, 0xB33F, 0xF820, 0xF479, 0x87BC, 0x87BC, 0xA685, 0x2477, True)
EA05 = (b'AU3!EA05', 0x29BC, 0xA25E, 0x29AC, 0xF25E, 0x45AA, 0x45AA, 0xC3D2, 0x22AF, False)
class A3xReader(StructReader[memoryview]):
def read_encrypted_data(self, size_key, seed, is_current=True):
if is_current:
size = 2 * (self.u32() ^ size_key)
seed = int(size // 2) + seed
else:
size = (self.u32() ^ size_key)
seed += size
return a3x_decrypt(self.read_exactly(size), seed, is_current)
def read_encrypted_string(self, size_key, seed, is_current=True):
if is_current:
return self.read_encrypted_data(size_key, seed).decode('utf-16le')
return self.read_encrypted_data(size_key, seed, is_current=False).decode('utf-8')
def read_time(self):
H = self.u32()
L = self.u32()
T = (H << 32) | L
return filetime(T)
def read_length_prefixed_string(self):
length = self.i32()
return ''.join(chr((self.u16() ^ length) & 0xFFFF) for _ in range(length))
class A3xRecord(Struct):
MAGIC = b'\x6B\x43\xCA\x52'
def __init__(self, reader: A3xReader, encryption_type: A3xEncryptionType):
self.magic = reader.read(4)
self.encryption_type = encryption_type
self.type = reader.read_encrypted_string(
encryption_type.tag_size,
encryption_type.tag,
encryption_type.is_current
).lstrip('>').rstrip('<')
self.src_path = reader.read_encrypted_string(
encryption_type.path_size,
encryption_type.path,
encryption_type.is_current
)
self.is_compressed = bool(reader.u8())
self.is_encrypted = True
self.size = reader.u32() ^ encryption_type.compressed_size
self.size_decompressed = reader.u32() ^ encryption_type.decompressed_size
self.checksum = reader.u32() ^ encryption_type.checksum
self.created = reader.read_time()
self.written = reader.read_time()
self.data = reader.read_exactly(self.size)
def __hash__(self):
return hash((self.path, self.type))
def __eq__(self, other):
if not isinstance(other, A3xRecord):
return False
return self.path == other.path and self.type == other.type
def extract(self) -> bytearray:
output = MemoryFile()
it = self.extract_linewise()
output.write(next(it))
for line in it:
output.write_byte(10)
output.write(line)
return output.getvalue()
def extract_linewise(self) -> Generator[bytes]:
if self.is_encrypted:
a3x.log_info('decryption:', self.path)
if self.encryption_type.is_current:
self.data = a3x_decrypt(self.data, self.encryption_type.data, self.encryption_type.is_current)
else:
seed = self.encryption_type.data + 0x849
self.data = a3x_decrypt(self.data, seed, self.encryption_type.is_current)
self.is_encrypted = False
if self.is_compressed:
a3x.log_info('decompress:', self.path)
self.data = a3x_decompress(self.data, self.encryption_type.is_current)
self.is_compressed = False
if self.type == A3xType.UNICODE:
for line in codecs.decode(self.data, 'utf16').splitlines():
yield line.encode(a3x.codec)
return
if self.type == A3xType.SCRIPT:
a3x.log_info('decompiler:', self.path)
for indent, line in a3x_decompile(self.data):
yield F'{indent * 4 * " "}{line}'.encode(a3x.codec)
return
yield self.data
def is_script(self):
return self.type in (
A3xType.SCRIPT,
A3xType.UNICODE,
)
@property
def path(self):
try:
tv = A3xType(self.type)
except Exception:
return self.type
if tv is A3xType.SCRIPT:
return 'script.au3'
if tv is A3xType.UNICODE:
return 'unicode-script.au3'
if tv is A3xType.NOEXEC:
return None
if tv in (A3xType.AHK_WITH_ICON, A3xType.AHK_SCRIPT):
return 'script.ahk'
class A3xScript(Struct):
MAGIC = b'\xA3\x48\x4B\xBE\x98\x6C\x4A\xA9\x99\x4C\x53\x0A\x86\xD6\x48\x7D'
WIDTH = 0x28
def has_valid_magic(self):
return self.magic == self.MAGIC
def __init__(self, reader: A3xReader):
self.magic = reader.read(0x10)
self.type = bytes(reader.read(8))
self._unk = reader.read(16)
self.truncated = False
if not self.type.startswith(B'AU3!'):
self.body = []
return
self.body: list[A3xRecord] = []
last_known_good_position = reader.tell()
types = {at.version: at for at in A3xEncryptionType}
while not reader.eof:
pos = reader.tell()
try:
rt = types.get(self.type, A3xEncryptionType.EA06)
self.body.append(A3xRecord(reader, rt))
except (ValueError, EOFError):
reader.seekset(pos)
break
else:
last_known_good_position = pos
if reader.read(8) != self.type:
self.truncated = True
reader.seekset(last_known_good_position)
if self.body:
self.body.pop()
class a3x(PathExtractorUnit):
"""
Extract resources and decompile bytecode from compiled AutoIt scripts and executables.
"""
def unpack(self, data: bytearray):
view = memoryview(data)
cursor = 0
errors: dict[int, Exception] = {}
script_count = 0
truncated: set[A3xRecord] = set()
intact: set[A3xRecord] = set()
def _package(records: Iterable[A3xRecord]) -> Generator[UnpackResult]:
for k, record in enumerate(records, 1):
self.log_info(F'record {k} type:', record.type)
self.log_info(F'record {k} path:', record.src_path)
if record.path is None:
continue
yield UnpackResult(
record.path,
record.extract,
srcpath=record.src_path,
created=record.created and record.created.isoformat(' ', 'seconds'),
written=record.written and record.written.isoformat(' ', 'seconds'),
)
while cursor < len(view):
self.log_debug(F'searching at offset 0x{cursor:08X}')
nc = data.find(A3xScript.MAGIC, cursor)
if nc >= 0:
cursor = nc
else:
rp = data.find(A3xRecord.MAGIC, cursor) - A3xScript.WIDTH
if rp <= cursor:
break
cursor = rp
try:
script = A3xScript.Parse(view[cursor:])
except Exception as E:
errors[cursor] = E
cursor += 1
continue
else:
valid = script.has_valid_magic()
if valid:
_m = 'correct'
else:
_m = 'invalid'
if not script.body:
cursor += A3xScript.WIDTH
if not script.has_valid_magic():
cursor += len(A3xRecord.MAGIC)
continue
if script.truncated:
_a = 'truncated'
truncated.update(script.body)
else:
script_count += 1
_a = 'intact'
intact.update(script.body)
self.log_info(
F'{_a} script of type', script.type,
F'and length 0x{len(script):08X}',
F'with {len(script.body)} records and {_m} magic:',
script.magic
)
cursor += len(script)
if script.truncated:
if not script.has_valid_magic():
cursor += len(A3xRecord.MAGIC)
continue
yield from _package(script.body)
remaining = truncated - intact
if remaining:
self.log_warn('emitting records from truncated scripts')
yield from _package(remaining)
return
elif truncated:
self.log_debug('good news: intact scripts contained all records from truncated scripts')
if script_count == 0:
error = None
for offset, error in errors.items():
self.log_warn(F'error at offset 0x{offset:08X}:', error)
if error:
raise error
@classmethod
def handles(cls, data) -> bool | None:
return buffer_contains(data, A3xScript.MAGIC) or buffer_contains(data, A3xRecord.MAGIC)