-
Notifications
You must be signed in to change notification settings - Fork 1
/
obfu_patches_old.py
2557 lines (2204 loc) · 133 KB
/
obfu_patches_old.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 re
import idc
from idc import *
import itertools as it
from obfu_handler import PatternMatchingRule
if not idc:
from bitwise import BitwiseMask
from di import diInsns, my_decode_insn, de
from obfu_helpers import kassemble, ObfuFailure, bitsize_signed_2, hex_pattern
from sftools import dinjasm, MyGetOperandDisplacement
from slowtrace_helpers import GetInsnLen
from start import isInt
FLAG_LOCK = 1<<0
FLAG_REPNZ = 1<<1
FLAG_REP = 1<<2
FLAG_HINT_TAKEN = 1<<3
FLAG_HINT_NOT_TAKEN = 1<<4
FLAG_IMM_SIGNED = 1<<5
FLAG_DST_WR = 1<<6
FLAG_RIP_RELATIVE = 1<<7
FLAG_MASK = (1<<8) - 1
# mark_sp_factory('lea_rbp_rsp_x'))
# , [], set_sp_factory('lea_rbp_rsp_x'))
patchmarks = globals().get('patchmarks', dict())
def simple_patch_factory(s):
"""
simple_patch_factory("push qword [{idc.get_name(idc.get_operand_value(addressList[1], 1))}]")
would create a patch to evaluate and replace: {idc.get_name(idc.get_operand_value(addressList[1], 1))}
"""
# regex = re.compile(r'\{([^}]+)\}')
regex = r'\{([^}]+)\}'
# replace=replaceFunction(search, replace, original, ea, addressList, patternComment)
def patch( search, replace, original, ea, addressList, patternComment, addressListWithNops):
def terp(m):
return eval(m.group(1), globals(), {'addressList': addressList})
def interpolate_inner(s):
return re.sub(regex, terp, s)
result = interpolate_inner(s)
# dprint("[simple_patch_factory] result")
print("[simple_patch_factory] result:{}".format(result))
return (len(search), [result])
return patch
def mark_sp_factory(mark):
"""
Typical Input:
028 -250 48 81 ec 50 02 00 00 sub rsp, 0x250 ; won't be passed as input
278 [48 8d 6c 24 20] lea rbp, [rsp+0x20]
.....................................................
48 8d a5 30 02 00 00 lea rsp, [rbp+0x230] ; will be passed as set_sp_factory input
"""
# replace=replaceFunction(search, replace, original, ea, addressList, patternComment)
def patch( search, replace, original, ea, addressList, patternComment, addressListWithNops):
# spd = idc.get_spd(ea) # a.k.a `ea`
# print('search: {}'.format(search))
spd = -slvars.rsp
if len(search) > 4:
disp = idc.get_operand_value(ea, 1)
if not spd and disp:
return
else:
disp = 0
if disp:
disp = MyGetOperandDisplacement(ea, 1)
value = spd + disp
print("{:x} storing mark {}: {:x} + {:x}".format(ea, mark, spd, disp))
patchmarks[mark] = value
return []
return patch
def set_sp_factory(mark):
"""
Typical Input:
48 8d a5[30 02 00 00] lea rsp, [rbp+0x230] ; will be passed as set_sp_factory input
"""
global slvars
def patch(search, replace, original, ea, addressList, patternComment, addressListWithNops):
if mark not in patchmarks:
print("Potential SP adjustment failed due to no patchmark {:x}".format(ea))
return []
value = patchmarks[mark]
# spd = idc.get_spd(ea)
spd = -slvars.rsp
if len(search) > 4:
disp = idc.get_operand_value(ea, 1)
else:
disp = 0
print("{:x} retrieved mark {}: {:x} + {:x}".format(ea, mark, value, disp))
print("{:x} adjusting spd from {:x} by {:x} to get {:x}".format(ea + len(search), spd, (value + disp) - spd, (value + disp)))
_spd = (value + disp) - spd
idc.add_user_stkpnt(ea + len(search), _spd)
cmt = "[SPD=0x{:x}]".format( _spd )
Commenter(ea, "line").remove_matching(r'^\[SPD=')
Commenter(ea, "line").add(cmt).commit()
return patch
def mark_sp_reg_factory(reg):
"""
Typical Input:
mov rax, rsp 48 8B C4
sub rsp, 0xb8
lea r11, [rax]
mov rsp, r11
retn
"""
# replace=replaceFunction(search, replace, original, ea, addressList, patternComment)
def patch( search, replace, original, ea, addressList, patternComment, addressListWithNops):
# spd = idc.get_spd(ea) # a.k.a `ea`
spd = -slvars.rsp
disp = idc.get_operand_value(ea, 1)
if not spd and disp:
return
if disp:
disp = MyGetOperandDisplacement(ea, 1)
value = spd + disp
print("{:x} storing reg {}: {:x}".format(ea, reg, value))
patchmarks[reg] = value
return []
return patch
def gen_mask(pattern, previous=[]):
if not isinstance(previous, list):
raise Exception("argument 'previous' was not a list (type: {})".format(type(previous)))
if len(previous) < 2:
sometimes = []
always = []
for v in pattern:
sometimes.append(v)
always.append(v)
return [sometimes, always]
sometimes = previous[0]
always = previous[1]
if pattern is None:
mask = []
for i, unused in enumerate(always):
mask.append( ~(sometimes[i] ^ always[i]) )
return [always, mask]
for i, v in enumerate(pattern):
sometimes[i] |= v
always[i] &= v
return [sometimes, always]
def patch_32bit_add(search, replace, original, ea, addressList, patternComment, addressListWithNops):
"""
replace: 48 81 c1 08 00 00 00 add rcx, 8
with: 48 83 c1 08 add rcx, 8
"""
if debug: print("patch_32bit_add")
length = MyGetInstructionLength(ea)
# e = deCode(get_bytes(ea, length), ea)
e = de(ea)
if isinstance(e, list):
e = e[0]
# pp(e.__dict__)
globals()['e'] = e
flags = e.rawFlags & FLAG_MASK
if e.mnemonic == 'ADD' \
and e.opcode == 11 \
and flags == (FLAG_DST_WR | FLAG_IMM_SIGNED) \
and e.operands[0].type == 'Register' \
and e.operands[1].type == 'Immediate' \
and e.operands[1].size == 32:
requiredSize = bitsize_signed_2(e.operands[1].value)
if requiredSize == 16:
requiredSize = 32
if debug: print("0x%x: patch_32bit_add: acutalSize: %i, requiredSize: %i" % (ea, e.operands[1].size, requiredSize))
if requiredSize == 8:
addresses = addressList[0:e.size]
return (addresses,
(["add {}, {}".format(e.operands[0].name, e.operands[1].value)]))
else:
if debug: print("patch_32bit_add: e was type %s" % type(e))
return []
_push_imm = []
def patch_manual_store(search, replace, original, ea, addressList, patternComment, addressListWithNops):
global _push_imm
imm = idc.get_wide_byte(addressList[1])
_push_imm.append(imm)
print("storing push imm: 0x{:x}".format(imm))
def patch_manual(search, replace, original, ea, addressList, patternComment, addressListWithNops):
global _push_imm
imm = _push_imm.pop()
print("using push imm: 0x{:x}".format(imm))
if not isInt(ea):
raise ValueError("ea is {}".format(ea))
# sig_maker_ex(obfu.combEx(ea, length=64), fullSig=1, noSig=1, show=1)
return kassemble('add rsp, 0x{:x}'.format(imm))
def patch_double_stack_push_call_jump(search, replace, original, ea, addressList, patternComment, addressListWithNops):
# 48 ?? ?? ?? ?? ?? ?? mov rax, qword [LoadLibraryA]
# 48 ?? ?? ?? lea rdx, qword [rbp+48h]
# 48 ?? ?? mov rcx, rdx ; mov library name into rcx
# 55 push rbp
# 48 ?? ?? ?? ?? ?? ?? lea rbp, qword [sub_144A4AF5F]
# 48 ?? ?? 24 xchg rbp, [rsp]
# 50 push rax
# c3 retn
# -- a different example
# 48 8b 05 14 91 05 fd mov rax, qword [AddVectoredExceptionHandler]
# 48 8d 15 a6 4f 0e 00 lea rdx, qword [loc_14486BDC5]
# b9 01 00 00 00 mov ecx, 1
# 55 push rbp
# 48 8d 2d ad b0 4b 00 lea rbp, qword [sub_144ACFED4]
# 48 87 2c 24 xchg rbp, [rsp]
# 50 push rax
# c3 retn
# -- a different example
# 48 8b 05 f8 cc 04 fe mov rax, qword [SetUnhandledExceptionFilter]
# 48 8d 15 54 6d 65 01 lea rdx, qword [byte_144DE9A5F]
# 52 push rdx
# 59 pop rcx
# 55 push rbp
# 48 8d 2d 6d da 65 01 lea rbp, qword [sub_144DF078B]
# 48 87 2c 24 xchg rbp, [rsp]
# 50 push rax
# c3 retn
# mov rax, [0x1417f2798]
# lea rdx, [rbp+0x48]
# push rdx
# pop rcx
# lea rsp, [rsp-0x8]
# mov [rsp], rbp
# lea rbp, [0x144345cd3]
# xchg [rsp], rbp
# push rax
# retn
# -- a false positive
# mov rax, cs:LoadLibraryA
# lea rdx, [rbp+48h]
# push rdx
# pop rcx
# mov [rbp+100h], rax
# mov rax, [rbp+100h]
# mov [rbp+150h], rax
# lea rax, [rbp+48h]
# jmp loc_14424AFE2 ; [obfu
# b1180 example
# 48 8b 05 43 dd 00 fd mov rax, [off_140D0AB4C] ; flags are 0x30509574
# 8b 15 2d 6c d6 fc mov edx, [dword_140A63A3C]
# 89 d1 mov ecx, edx
# 55 push rbp
# 48 8d 2d a2 bc db ff lea rbp, [label22]
# 48 87 2c 24 xchg [rsp], rbp
# 50 push rax
# c3 retn
# all our arguments are basically useless, we're going to have to start from scratch.
# first check if we're actually loading something that is actually code
# idc.is_code(idc.get_full_flags(GetOperandValue(EA(), 1)))
target = GetOperandValue(ea, 1)
flags = idc.get_full_flags(target)
# dprint("[debug] target, flags")
if debug: print("[patch_double_stack_push_call_jump] target:{:x}, flags:{:x}".format(target, flags))
if idc.is_code(flags) \
or flags == 0x305054a0 \
or flags & idc.FF_0OFF \
or (type(idc.GetDisasm(target)) is str and idc.GetDisasm(target).startswith("extrn")) \
or (type(GetType(target)) is str and GetType(target).endswith(")")):
# raise ObfuFailure("0x%x: serious business: %s {%s}" % (addressList[0], GetDisasm(target), GetDisasm(target)))
state = 0
solution = []
callAddress = BADADDR
jmpAddress = BADADDR
addrLen = len(addressList)
insAddresses = []
i = 0
while i < addrLen:
addr = addressList[i]
insAddresses.append(addr)
skip = MyGetInstructionLength(addr)
if debug: print("skipped %i addressList" % skip)
i += skip
if debug: print("insAddresses: %s" % insAddresses) # not used yet
ourAddressList = []
inslen = MyGetInstructionLength(ea)
skip = 0
end = 0
for idx, a in enumerate(insAddresses):
# d = re.sub(r'\s+', ' ', GetDisasm(a))
d = dinjasm(a)
if (1 + idx) < len(insAddresses):
dpeek = dinjasm(insAddresses[idx + 1])
else:
dpeek = ""
# print("0x%x: state: %i: %s" % (a, state, d))
inslen = MyGetInstructionLength(a)
# not used yet
for i in range(inslen):
ourAddressList.append(a + i)
# 0x144a91628: state: 0: mov rax, qword ptr cs:[LoadLibraryA]
# 0x144a9162f: state: 1: lea rdx, qword ptr [rbp+48h]
# 0x144a91633: state: 1: push rdx
# 0x144a91634: state: 1: pop rcx
# 0x144345cd3: state: 1: mov qword ptr [rbp+100h], rax
# 0x144345cda: state: 1: mov rax, qword ptr [rbp+100h]
#
# .text:0000000144A91628 1B8 48 8B 05 69 11 D6 FC mov rax, cs:LoadLibraryA
# .text:0000000144A9162F 1B8 48 8D 55 48 lea rdx, [rbp+48h]
# .text:0000000144A91633 1B8 52 push rdx
# .text:0000000144A91634 1C0 59 pop rcx
# .text:0000000144345CD3 000 48 89 85 00 01 00 00 mov [rbp+100h], rax
# .text:0000000144345CDA 000 48 8B 85 00 01 00 00 mov rax, [rbp+100h]
# .text:0000000144345CE1 000 48 89 85 50 01 00 00 mov [rbp+150h], rax
# .text:0000000144345CE8 000 48 8D 45 48 lea rax, [rbp+48h]
# .text:0000000144345CEC 000 E9 F1 52 F0 FF jmp loc_14424AFE2 ; [obfu::comb] unconditional jump
# .text:0000000144345CEC ; END OF FUNCTION CHUNK FOR sub_14548F1ED#
if d.startswith("mov rax"):
t = GetOpType(a, 1)
# if t in (idc.o_mem, idc.o_displ) and state == 0:
if state == 0:
callAddress = GetOperandValue(a, 1)
state = 1
# continue, else we'll add this line to our solution
continue
else:
if debug: print("sequence: %i" % state)
return [] # raise ObfuFailure("serious business: out of sequence: %s" % d)
elif d.startswith("mov [rsp-8], rbp") \
and dpeek.startswith("lea rsp, [rsp-8]"):
if state == 1:
state = 2
else:
if debug: print("serious business: out of sequence: %s" % (d + "; " + dpeek))
return []
elif d.startswith("lea rsp, [rsp-8]") \
and dpeek.startswith("mov [rsp], rbp"):
if state == 1:
state = 2
else:
if debug: print("serious business: out of out of sequence: %s" % (d + "; " + dpeek))
return []
elif d.startswith("push rbp"):
if state == 1:
state = 2
else:
if debug: print("out of sequence: %i" % state)
return [] # raise ObfuFailure("serious business: out of out of sequence: %s" % d)
# elif d.startswith("lea rbp") and GetOpType(a, 1) in (idc.o_mem, idc.o_displ):
elif d.startswith("lea rbp"):
if state == 2:
jmpAddress = GetOperandValue(a, 1)
if debug: print("jmpAddress: 0x%x" % jmpAddress)
state = 3
else:
if debug: print("0x%x: serious business: out of out of sequence (%s): %s" % (ea, state, d))
return []
elif d.startswith("xchg rbp, [rsp]") \
or d.startswith("xchg [rsp], rbp"):
if state == 3:
state = 4
else:
if debug: print("0x%x: serious business: out of out of sequence (%s): %s" % (ea, state, d))
return []
elif d.startswith("push rax"):
if state == 4:
state = 5
else:
if debug: print("0x%x: serious business: out of out of sequence (%s): %s" % (ea, state, d))
return []
elif d.startswith("ret"):
if state == 5:
state = 6
end = insAddresses[idx] + GetInsnLen(insAddresses[idx])
break
else:
if debug: print("out of sequence: %i" % state)
if state > 2:
if debug: print("0x%x: serious business: out of out of sequence (%s): %s" % (ea, state, d))
return []
else:
return []
if state == 1:
# solution.append(dii(a))
solution.append(d)
if state == 6:
# solution.append("CALL 0x%x" % callAddress)
# solution.append("JMP 0x%x" % jmpAddress)
# this way...
usedAddresses = []
for a in addressList:
if a == end:
break
usedAddresses.append(a)
# --or--
# https://stackoverflow.com/questions/5883265/python-add-item-to-list-until-a-condition-is-true
usedAddresses2 = [x for x in it.takewhile(lambda x: x != end, addressList)]
usedCount = len(usedAddresses)
# compact, but readable? ... compact: yes, readable: hardly
print("usedAddresses1: %s" % usedAddresses)
print("usedAddresses2: %s" % usedAddresses)
solution.append("call qword [0x%x]" % callAddress)
solution.append("jmp 0x%x" % jmpAddress)
print("Possible solution:\n%s" % "\n".join(solution))
return (usedAddresses, solution)
# return (usedAddresses,
# return (search, replace, original, ea, addressList, patternComment, addressListWithNops)
elif state > 4:
raise ObfuFailure("serious business: only reached state %i of 6" % state)
return []
def patch_double_rsp_push_call_jump(search, replace, original, ea, addressList, patternComment, addressListWithNops):
"""
0: 55 push rbp
1: 48 8d 2d ?? ?? ?? ?? lea rbp,[rip+0xfffffffffc1c7fa1]
8: 48 87 2c 24 xchg QWORD PTR [rsp],rbp
c: 55 push rbp
d: 48 8d 2d ?? ?? ?? ?? lea rbp,[rip+0x1e650e]
14: 48 87 2c 24 xchg QWORD PTR [rsp],rbp
18: c3 ret
19:
"""
jmpAddress = GetOperandValue(addressList[0x01], 1)
callAddress = GetOperandValue(addressList[0x0d], 1)
# we can return the entire addressList, as this is a terminal pattern
# (it ends it retn)
return (addressList, [
"call 0x{:x}".format(callAddress),
"jmp 0x{:x}".format(jmpAddress),
# "ret"
])
def patch_double_rsp_push_call_jump_b(search, replace, original, ea, addressList, patternComment, addressListWithNops):
"""
0: 55 push rbp
(shoe-horn in 48 8d 64 24 f8 instead of 55)
1: 48 8d 2d ?? ?? ?? ?? lea rbp,[rip+0xfffffffffc1c7fa1]
8: 48 87 2c 24 xchg QWORD PTR [rsp],rbp
c: 55 push rbp
d: 48 8d 2d ?? ?? ?? ?? lea rbp,[rip+0x1e650e]
14: 48 87 2c 24 xchg QWORD PTR [rsp],rbp
18: c3 ret
19:
"""
jmpAddress = GetOperandValue(addressList[0x01 + 4], 1)
callAddress = GetOperandValue(addressList[0x0d + 4], 1)
# we can return the entire addressList, as this is a terminal pattern
# (it ends it retn)
return (addressList, [
"call 0x{:x}".format(callAddress),
"jmp 0x{:x}".format(jmpAddress),
# "ret"
])
def patch_single_rsp_push_call_jump(search, replace, original, ea, addressList, patternComment, addressListWithNops):
"""
0: 55 push rbp
1: 48 8D 2D[AB 37 35 00] lea rbp, sub_143C53296
8: 48 87 2C 24 xchg QWORD PTR [rsp],rbp
c: E9[03 DC DC FF] jmp _sub_1436CD6F7
0: e8[0f dc dc ff] call _sub_1436CD6F7
5: e9[a9 37 35 00] jmp sub_143C53296
"""
jmpAddress = GetOperandValue(addressList[0x01], 1)
# we can't see `jmp` instructions because they're purposefully hidden for chunk processing
addressJmp = addressList[0x0b] + 1
# dprint("[patch_single_rsp_push_call_jump] jmpAddress, addressJmp")
print("[patch_single_rsp_push_call_jump] jmpAddress:{:x}, addressJmp:{:x}".format(jmpAddress, addressJmp))
if isUnconditionalJmp(addressJmp):
callAddress = GetTarget(addressJmp)
# Now we have to check what's next, to avoid clobbering other patterns
addressNext = callAddress + GetInsnLen(callAddress)
# dprint("[patch_single_rsp_push_call_jump] callAddress, addressNext")
print("[patch_single_rsp_push_call_jump] callAddress:{:x}, addressNext:{:x}".format(callAddress, addressNext))
if IdaGetMnem(callAddress) in ('ret', 'retn', 'xchg') or \
IdaGetMnem(addressNext) in ('ret', 'retn', 'xchg'):
print("[patch_single_rsp_push_call_jump] fail: retn/xchg in callAddress:{:x}, addressNext:{:x}".format(callAddress, addressNext))
return []
if not IsFuncHead(callAddress) and len(xrefs_to_ex(callAddress, flow=0)) < 2:
print("[patch_single_rsp_push_call_jump] fail: not enough xrefs to callAddress:{:x}".format(callAddress))
return []
""" some real subs
.text:00000001441DC002 000 push rbp ; [PatchBytes] lea rsp, qword ptr [rsp-8]; mov [rsp], rbp
.text:00000001441DC003 008 nop dword ptr [rax+rax+00000000h]
.text:00000001441DC00B 008 sub rsp, 40h
.text:00000001441DC00F 048 lea rbp, [rsp+20h]
.text:00000001441DC014 048 mov [rbp+30h], rcx
(same sub, before de-obfu)
.text:00000001441DC002 000 lea rsp, [rsp-8]
.text:00000001441DC007 008 mov [rsp+8+var_8], rbp
.text:00000001441DC00B 008 sub rsp, 40h
.text:00000001441DC00F 048 lea rbp, [rsp+48h+var_28]
.text:00000001441DC014 048 mov [rbp+30h], rcx
"""
ForceFunction(callAddress)
nassemble(addressJmp, "jmp 0x{:x}".format(jmpAddress), apply=1)
return len(search), [
"call 0x{:x}".format(callAddress),
# "jmp 0x{:x}".format(jmpAddress),
]
# "ret"
return []
def patch_checksummer(search, replace, original, ea, addressList, patternComment, addressListWithNops):
# idc.patch_dword(addressList[4], idc.get_wide_dword(addressList[4]) - 0x20)
# PatchNops(addressList[8], 5)
value = idc.get_wide_dword(addressList[4]) - 0x20
# 55 48 8D AC 24
# 0-value
# 60 FF FF FF
# idc.patch_byte(addressList[12], value)
# PatchNops(addressList[1], 7)
return (addressList[0:13], [
"push rbp",
"sub rsp, 0{:x}h".format(value),
"lea rbp, [rsp]"
])
def process_replace(replace, replace_asm):
ra = kassemble(replace_asm)
# print("pr", replace, ra, replace_asm.split(';'))
if ra == replace:
return replace_asm.split(';')
print("replace", replace)
print("nassemb", ra)
return replace
def process_hex_pattern(replace):
hp = hex_pattern(replace)
d = _.pluck(diInsns(hp), 3)
def fn(value, index, container):
return [int(x, 16) for x in re.split('(..)', value) if x]
d = _.flatten(_.map(d, fn))
#
if d == hp:
return _.pluck(diInsns(hp), 2)
print("process_hex_pattern", d, hp, _.pluck(diInsns(hp), 2))
return hex_pattern(replace)
def obfu_append_patches():
global obfu
obfu.patterns = list()
# obfu.append("", "push r11, pop rsp -> mov rsp, r11", hex_pattern(["41 53", "5c"]), hex_pattern(["4C 89 dc"]), safe=1)
# obfu.append("", "push r11, pop rsp -> mov rsp, r11", hex_pattern(["41 53", "5c"]), ["mov rsp, r11"], safe=1)
"""
028 -250 48 81 ec 50 02 00 00 sub rsp, 0x250
278 48 8d 6c 24 20 lea rbp, [rsp+0x20]
.....................................................
48 8d a5 30 02 00 00 lea rsp, [rbp+0x230]
"""
obfu.append("", "mark lea rbp, [rsp+x]", hex_pattern("48 8d 6c 24 ??"), [], mark_sp_factory('lea_rbp_rsp_x'))
obfu.append("", "set lea rsp, [rbp+x]", hex_pattern("48 8d a5 ?? ?? ?? ??"), [], set_sp_factory('lea_rbp_rsp_x'))
obfu.append("", "set mov rsp, rbp", hex_pattern("48 8b e5"), [], set_sp_factory('lea_rbp_rsp_x'))
obfu.append("", "mov r11, rsp", hex_pattern("4c 8b dc") or nassemble("mov r11, rsp"), [], mark_sp_factory('mov_r11_rsp'))
obfu.append("", "lea r11, [rsp+??h]", hex_pattern("4c 8d 5c 24 ??") or nassemble("lea r11, [rsp+60h]"), [], mark_sp_factory('mov_r11_rsp'))
obfu.append("", "lea r11, [rsp+????????h]",
hex_pattern("4c 8d 9c 24 ?? ?? ?? ??") or nassemble("lea r11, [rsp+]"), [], mark_sp_factory('mov_r11_rsp'))
obfu.append("", "mov rsp, r11", hex_pattern("49 8b e3") or nassemble("mov rsp, r11"), [], set_sp_factory('mov_r11_rsp'))
obfu.append("""
0: 48 8d 64 24 f8 lea rsp, [rsp-0x8]
5: 48 89 2c 24 mov [rsp], rbp
9: 48 8d 2d ?? ?? ?? ?? lea rbp, [rip+0x0] # 0x10
10: 48 87 2c 24 xchg [rsp], rbp
14: 48 8d 64 24 08 lea rsp,[rsp+0x8]
19: ff 64 24 f8 jmp [rsp-0x8]
""", "lea rbp<>rsp jmp variant1 (mit nop)",
hex_pattern([
"48 8d 64 24 f8",
"48 89 2c 24",
"90",
"48 8d 2d ?? ?? ?? ??",
"48 87 2c 24",
"48 8d 64 24 08",
"ff 64 24 f8"
]), [],
generate_patch1(0x09 + 3 + 1) # , 0x10 + 1, 0x05)
)
obfu.append("""
000 48 89 6C 24 F8 mov [rsp+var_8], rbp ; [PatchBytes] mov/lea->push order swap: rbp
; [PatchBytes] lea rsp, qword ptr [rsp-8]; mov [rsp], rbp
000 48 8D 64 24 F8 lea rsp, [rsp-8]
008 48 83 EC 40 sub rsp, 40h
048 48 8D 6C 24 20 lea rbp, [rsp+20h]
to
000 55 push rbp ; [PatchBytes] mov/lea->push order swap: rbp
; [PatchBytes] lea rsp, qword ptr [rsp-8]; mov [rsp], rbp
008 48 83 EC 40 sub rsp, 40h
048 48 8D 6C 24 20 lea rbp, [rsp+20h]
048 0F 1F 84 00 00 00 00 00 nop dword ptr [rax+rax+00000000h] ; [PatchBytes] PatchNops
048 90 nop
""", "ArxanHelper prologue",
hex_pattern([
"48 89 6C 24 F8",
"48 8D 64 24 F8",
"48 83 EC 40",
"48 8D 6C 24 20",
]),
hex_pattern([
"55",
"48 83 EC 40",
"48 8D 6C 24 20",
]),
safe = 1
)
# obfu.append("""
# 0: 48 8d 64 24 f8 lea rsp, [rsp-8] ; === call LOCATION_2, insert LOCATION_1 into return stack
# 5: 48 89 2c 24 mov [rsp], rbp ; push rbp
# 9: 48 8d 2d ?? ?? ?? ?? lea rbp, LOCATION_1 ; rbp = LOCATION_1
# 10: 48 87 2c 24 xchg rbp, [rsp] ; pop rbp ; push LOCATION_1 ; push LOCATION_1
# 14: 55 push rbp ; push rbp
# 15: 48 8d 2d ?? ?? ?? ?? lea rbp, LOCATION_2 ; rbp = LOCATION_2
# 1c: 48 87 2c 24 xchg rbp, [rsp] ; pop rbp; push LOCATION_2 ; push LOCATION_2
# 20: c3 retn ; pop rax; jmp eax ; pop rax; jmp rax
# """,
# "faked call to LOCATION_2 from LOCATION_1 ",
# hex_pattern([
# "48 8d 64 24 f8",
# "48 89 2c 24",
# "48 8d 2d ?? ?? ?? ??",
# "48 87 2c 24",
# "55",
# "48 8d 2d ?? ?? ?? ??",
# "48 87 2c 24",
# "c3"
# ]),
# [],
# generate_call_with_fake_return(0x18)
# )
# 0: 58 pop rax # 0: 50 push rax
# 1: 59 pop rcx # 1: 51 push rcx
# 2: 5a pop rdx # 2: 52 push rdx
# 3: 5b pop rbx # 3: 53 push rbx
# 4: 5c pop rsp # 4: 54 push rsp
# 5: 5d pop rbp # 5: 55 push rbp
# 6: 5e pop rsi # 6: 56 push rsi
# 7: 5f pop rdi # 7: 57 push rdi
# 8: 41 58 pop r8 # 8: 41 50 push r8
# a: 41 59 pop r9 # a: 41 51 push r9
# c: 41 5a pop r10 # c: 41 52 push r10
# e: 41 5b pop r11 # e: 41 53 push r11
# 10: 41 5c pop r12 # 10: 41 54 push r12
# 12: 41 5d pop r13 # 12: 41 55 push r13
# 14: 41 5e pop r14 # 14: 41 56 push r14
# 16: 41 5f pop r15 # 16: 41 57 push r15
####
#
# A series of patches to convert:
# mov [rsp-8], REG
# lea rsp, [rsp -8]
#
# with the slightly shorter
# lea rsp, [rsp-8]
# mov [rsp], REG
#
movlealistpush = [
# MOV [RSP-0x8], RAX; LEA RSP, [RSP-0x8]
[["48 89 44 24 f8", "48 8d 64 24 f8"], ["48 8d 64 24 f8", "48 89 04 24"], "rax"],
[["48 89 4c 24 f8", "48 8d 64 24 f8"], ["48 8d 64 24 f8", "48 89 0c 24"], "rcx"],
[["48 89 54 24 f8", "48 8d 64 24 f8"], ["48 8d 64 24 f8", "48 89 14 24"], "rdx"],
[["48 89 5c 24 f8", "48 8d 64 24 f8"], ["48 8d 64 24 f8", "48 89 1c 24"], "rbx"],
[["48 89 64 24 f8", "48 8d 64 24 f8"], ["48 8d 64 24 f8", "48 89 24 24"], "rsp"],
[["48 89 6c 24 f8", "48 8d 64 24 f8"], ["48 8d 64 24 f8", "48 89 2c 24"], "rbp"],
[["48 89 74 24 f8", "48 8d 64 24 f8"], ["48 8d 64 24 f8", "48 89 34 24"], "rsi"],
[["48 89 7c 24 f8", "48 8d 64 24 f8"], ["48 8d 64 24 f8", "48 89 3c 24"], "rdi"],
[["4c 89 44 24 f8", "48 8d 64 24 f8"], ["48 8d 64 24 f8", "4c 89 04 24"], "r8"],
[["4c 89 4c 24 f8", "48 8d 64 24 f8"], ["48 8d 64 24 f8", "4c 89 0c 24"], "r9"],
[["4c 89 54 24 f8", "48 8d 64 24 f8"], ["48 8d 64 24 f8", "4c 89 14 24"], "r10"],
[["4c 89 5c 24 f8", "48 8d 64 24 f8"], ["48 8d 64 24 f8", "4c 89 1c 24"], "r11"],
[["4c 89 64 24 f8", "48 8d 64 24 f8"], ["48 8d 64 24 f8", "4c 89 24 24"], "r12"],
[["4c 89 6c 24 f8", "48 8d 64 24 f8"], ["48 8d 64 24 f8", "4c 89 2c 24"], "r13"],
[["4c 89 74 24 f8", "48 8d 64 24 f8"], ["48 8d 64 24 f8", "4c 89 34 24"], "r14"],
[["4c 89 7c 24 f8", "48 8d 64 24 f8"], ["48 8d 64 24 f8", "4c 89 3c 24"], "r15"]
]
# A series of patches to convert:
# mov [rdx+8], REG
# lea rsp, [rsp+8]
#
# with the slightly shorter
# lea rsp, [rsp-8]
# mov [rsp], REG
#
movlealistpop = [# {{{
# CANNOT FIND ANY OCCURANCES OF THIS OBFU IN 2189 -- WAS IT EVERY VALID?
# 0: 48 8b 54 24 08 mov rdx,QWORD PTR [rsp+0x8]
# 5: 48 8d 64 24 08 lea rsp,[rsp+0x8]
#
# 48 8b ?? 24 08 48 8d 64 24 08
#
#
# MOV RAX, [RSP+0x8]; LEA RSP, [RSP+0x8]
[["48 8b 44 24 08", "48 8d 64 24 08"], ["48 8d 64 24 08", "48 8b 04 24"], "rax"],
[["48 8b 4c 24 08", "48 8d 64 24 08"], ["48 8d 64 24 08", "48 8b 0c 24"], "rcx"],
[["48 8b 54 24 08", "48 8d 64 24 08"], ["48 8d 64 24 08", "48 8b 14 24"], "rdx"],
[["48 8b 5c 24 08", "48 8d 64 24 08"], ["48 8d 64 24 08", "48 8b 1c 24"], "rbx"],
[["48 8b 64 24 08", "48 8d 64 24 08"], ["48 8d 64 24 08", "48 8b 24 24"], "rsp"],
[["48 8b 6c 24 08", "48 8d 64 24 08"], ["48 8d 64 24 08", "48 8b 2c 24"], "rbp"],
[["48 8b 74 24 08", "48 8d 64 24 08"], ["48 8d 64 24 08", "48 8b 34 24"], "rsi"],
[["48 8b 7c 24 08", "48 8d 64 24 08"], ["48 8d 64 24 08", "48 8b 3c 24"], "rdi"],
[["4c 8b 44 24 08", "48 8d 64 24 08"], ["48 8d 64 24 08", "4c 8b 04 24"], "r8"],
[["4c 8b 4c 24 08", "48 8d 64 24 08"], ["48 8d 64 24 08", "4c 8b 0c 24"], "r9"],
[["4c 8b 54 24 08", "48 8d 64 24 08"], ["48 8d 64 24 08", "4c 8b 14 24"], "r10"],
[["4c 8b 5c 24 08", "48 8d 64 24 08"], ["48 8d 64 24 08", "4c 8b 1c 24"], "r11"],
[["4c 8b 64 24 08", "48 8d 64 24 08"], ["48 8d 64 24 08", "4c 8b 24 24"], "r12"],
[["4c 8b 6c 24 08", "48 8d 64 24 08"], ["48 8d 64 24 08", "4c 8b 2c 24"], "r13"],
[["4c 8b 74 24 08", "48 8d 64 24 08"], ["48 8d 64 24 08", "4c 8b 34 24"], "r14"],
[["4c 8b 7c 24 08", "48 8d 64 24 08"], ["48 8d 64 24 08", "4c 8b 3c 24"], "r15"]
]# }}}
"""
.text:0000000140CBD671 000 48 83 EC 28 sub rsp, 28h
.text:0000000140CBD675 028 48 8B 41 10 mov rax, [rcx+10h]
.text:0000000140CBD679 028 83 38 03 cmp dword ptr [rax], 3
.text:0000000140CBD67C 028 48 89 6C 24 F8 / mov [rsp-8], rbp
.text:0000000140CBD681 028 48 8D 64 24 F8 \ lea rsp, [rsp-8]
.text:0000000140CBD686 030 48 BD 2B 93 18 44 01 00 00 00 mov rbp, offset sub_14418932B
.text:0000000140CBD690 030 48 87 2C 24 xchg rbp, [rsp]
.text:0000000140CBD694 030 48 8D 64 24 F8 lea rsp, [rsp-8]
.text:0000000140CBD699 038 48 89 14 24 mov [rsp], rdx
.text:0000000140CBD69D 038 48 89 5C 24 F8 / mov [rsp-8], rbx
.text:0000000140CBD6A2 038 48 8D 64 24 F8 \ lea rsp, [rsp-8]
.text:0000000140CBD6A7 040 48 8B 54 24 10 mov rdx, [rsp+10h]
.text:0000000140CBD6AC 040 48 BB 47 A5 D3 40 01 00 00 00 mov rbx, offset loc_140D3A547
.text:0000000140CBD6B6 040 48 0F 47 D3 cmova rdx, rbx
.text:0000000140CBD6BA 040 48 89 54 24 10 mov [rsp+10h], rdx
.text:0000000140CBD6BF 040 48 8D 64 24 08 lea rsp, [rsp+8]
.text:0000000140CBD6C4 038 48 8B 5C 24 F8 mov rbx, [rsp-8]
.text:0000000140CBD6C9 038 48 8D 64 24 08 lea rsp, [rsp+8]
.text:0000000140CBD6CE 030 48 8B 54 24 F8 mov rdx, [rsp-8]
.text:0000000140CBD6D3 030 48 8D 64 24 08 lea rsp, [rsp+8]
.text:0000000140CBD6D8 028 FF 64 24 F8 jmp qword ptr [rsp-8]
.text:0000000140CBD6DC ; ---------------------------------------------------------------------------
.text:0000000140CBD6DC 000 E9 4A BC 4C 03 jmp near ptr sub_14418932B
.text:0000000140CBD6E1
"""
####
# POP1 POP2
#
# mov [rsp+8], REG lea rsp, [rsp+8]
# lea rsp, [rsp+8] mov REG, [rsp-8]
#
# with the slightly shorter
# lea rsp, [rsp+8] mov [rsp], REG
# mov [rsp], REG lea rsp, [rsp+8]
# A series of patches to convert:
# lea rsp, [rsp+8]
# mov REG, [rbp-8],
#
# with the slightly shorter
# mov [rsp], REG
# lea rsp, [rsp+8]
movlealistpop2 = [
# lea [rsp],[rsp+8]; mov {r64},[rsp-8] => nop; mov [rsp],{r64}; lea rsp, [rsp+8]
#
# LEA RSP, [RSP+0x8]; MOV RAX, [RSP-0x8]
[["48 8d 64 24 08", "48 8b 44 24 f8"], ["48 8b 04 24", "48 8d 64 24 08"], "rax"],
[["48 8d 64 24 08", "48 8b 4c 24 f8"], ["48 8b 0c 24", "48 8d 64 24 08"], "rcx"],
[["48 8d 64 24 08", "48 8b 54 24 f8"], ["48 8b 14 24", "48 8d 64 24 08"], "rdx"],
[["48 8d 64 24 08", "48 8b 5c 24 f8"], ["48 8b 1c 24", "48 8d 64 24 08"], "rbx"],
[["48 8d 64 24 08", "48 8b 64 24 f8"], ["48 8b 24 24", "48 8d 64 24 08"], "rsp"],
[["48 8d 64 24 08", "48 8b 6c 24 f8"], ["48 8b 2c 24", "48 8d 64 24 08"], "rbp"],
[["48 8d 64 24 08", "48 8b 74 24 f8"], ["48 8b 34 24", "48 8d 64 24 08"], "rsi"],
[["48 8d 64 24 08", "48 8b 7c 24 f8"], ["48 8b 3c 24", "48 8d 64 24 08"], "rdi"],
[["48 8d 64 24 08", "4c 8b 44 24 f8"], ["4c 8b 04 24", "48 8d 64 24 08"], "r8"],
[["48 8d 64 24 08", "4c 8b 4c 24 f8"], ["4c 8b 0c 24", "48 8d 64 24 08"], "r9"],
[["48 8d 64 24 08", "4c 8b 54 24 f8"], ["4c 8b 14 24", "48 8d 64 24 08"], "r10"],
[["48 8d 64 24 08", "4c 8b 5c 24 f8"], ["4c 8b 1c 24", "48 8d 64 24 08"], "r11"],
[["48 8d 64 24 08", "4c 8b 64 24 f8"], ["4c 8b 24 24", "48 8d 64 24 08"], "r12"],
[["48 8d 64 24 08", "4c 8b 6c 24 f8"], ["4c 8b 2c 24", "48 8d 64 24 08"], "r13"],
[["48 8d 64 24 08", "4c 8b 74 24 f8"], ["4c 8b 34 24", "48 8d 64 24 08"], "r14"],
[["48 8d 64 24 08", "4c 8b 7c 24 f8"], ["4c 8b 3c 24", "48 8d 64 24 08"], "r15"]
#pattern: 48 8d 64 24 08; (4[c8]) 8b ([4567][4c]) 24 f8
#replace: 90; \1 8b \=printf('%02x' % submatch(2) - 0x40) 24; 48 8d 64 24 08
# 'trinary' search: '01001.00 10001011 01...100 00100100 f8',
# 'trinary' replace: '90 01001.00 10001011 00...100 00100100',
]
# messing about with alternate ways of expression
lhs = braceexpandlist("4{8,c} 8b {4..7}{4,c} 24 f8")
rhs = braceexpandlist("90 4{8,c} 8b {0..3}{4,c} 24")
search_r = r"""(?x
(\x48|\x4c) \x8b [\x44-\x7c] \x24 \xf8
)"""
replace_r = "\x90\1\x8b\$(\2 & ~0x40)\x24"
# classic push - in reverse order (push1)
search_asm = "mov [rsp-8], {r64}; lea rsp, [rsp-8]" # MOV [RSP-0x8], RAX; LEA RSP, [RSP-0x8]
# becomes classic push
# RSP <- RSP - 8; (* Push quadword *)
# [RSP] <- SRC;
replace_asm= "lea rsp, [rsp-8]; mov [rsp], {0}; nop"
# THIS ONE SEEMS INVALID?!
# pop-peek (double pop, first pop ignored) -- or perhaps this is two halves of different "atomic" instructions
# DEST <- [RSP + 8]; (* Copy quadword *)
# RSP <- RSP + 8;
search_asm = "mov {r64}, [rsp+8]; lea rsp, [rsp+8]" # MOV RAX, [RSP+0x8]; LEA RSP, [RSP+0x8]
# becomes tidier
# RSP <- RSP + 8;
# DEST <- [RSP]; (* Copy quadword *)
replace_asm= "lea rsp, [rsp+8]; mov [rsp], {0}; nop"
# classic pop - in reverse order (pop2)
# RSP <- RSP + 8;
# DEST <- [RSP - 8]; (* Copy quadword *)
search_asm = "lea [rsp], [rsp+8]; mov {r64}, [rsp-8]" # LEA RSP, [RSP+0x8]; MOV RAX, [RSP-0x8]
# becomes classic pop
# DEST <- [RSP]; (* Copy quadword *)
# RSP <- RSP + 8;
replace_asm= "nop; mov {0}, [rsp]; lea rsp, [rsp+8]"
# end messing about
# intel pop
# DEST <- [RSP]; (* Copy quadword *)
# RSP <- RSP + 8;
# intel push
# RSP <- RSP - 8; (* Push quadword */
# [RSP] <- SRC;
with BitwiseMask() as bm:
for r in movlealistpush:
bm.add_list(hex_pattern(r[0]))
obfu.append("", "mov/lea->push order swap: %s" % r[2], hex_pattern(r[0]), process_hex_pattern(r[1]), safe=1, group=bm)
if 0: # can't find any instances of this in 2189
for r in movlealistpop:
obfu.append("", "mov/lea->pop order swap: %s" % r[2], hex_pattern(r[0]), process_hex_pattern(r[1]), safe=1)
with BitwiseMask() as bm:
for r in movlealistpop2:
bm.add_list(hex_pattern(r[0]))
obfu.append("", "mov/lea->pop#2 order swap: %s" % r[2], hex_pattern(r[0]), process_hex_pattern(r[1]), safe=1, group=bm)
# 48 05 FF FF FF 08 add rax, 8FFFFFFh # standard short form
# 48 81 C0 FF FF FF 08 add rax, 8FFFFFFh # unused full form
# 48 81 C1 FF FF FF 08 add rcx, 8FFFFFFh
# 48 81 C2 FF FF FF 08 add rdx, 8FFFFFFh
# 48 81 C3 FF FF FF 08 add rbx, 8FFFFFFh
# 48 81 C4 FF FF FF 08 add rsp, 8FFFFFFh
# 48 81 C5 FF FF FF 08 add rbp, 8FFFFFFh
# 48 81 C6 FF FF FF 08 add rsi, 8FFFFFFh
# 48 81 C7 FF FF FF 08 add rdi, 8FFFFFFh
#
# 49 81 C0 FF FF FF 08 add r8, 8FFFFFFh
# 49 81 C1 FF FF FF 08 add r9, 8FFFFFFh
# 49 81 C2 FF FF FF 08 add r10, 8FFFFFFh
# 49 81 C3 FF FF FF 08 add r11, 8FFFFFFh
# 49 81 C4 FF FF FF 08 add r12, 8FFFFFFh
# 49 81 C5 FF FF FF 08 add r13, 8FFFFFFh
# 49 81 C6 FF FF FF 08 add r14, 8FFFFFFh
# 49 81 C7 FF FF FF 08 add r15, 8FFFFFFh
#
# rax 01001000 00000101 11111111 11111111 11111111 00001000
#
# rbx 01001000 10000001 11000011 11111111 11111111 11111111 00001000
# rcx 01001000 10000001 11000001 11111111 11111111 11111111 00001000
# rdx 01001000 10000001 11000010 11111111 11111111 11111111 00001000
# rbp 01001000 10000001 11000101 11111111 11111111 11111111 00001000
# rsp 01001000 10000001 11000100 11111111 11111111 11111111 00001000
# rdi 01001000 10000001 11000111 11111111 11111111 11111111 00001000
# rsi 01001000 10000001 11000110 11111111 11111111 11111111 00001000
#
# r8 01001001 10000001 11000000 11111111 11111111 11111111 00001000
# r9 01001001 10000001 11000001 11111111 11111111 11111111 00001000
# r10 01001001 10000001 11000010 11111111 11111111 11111111 00001000
# r11 01001001 10000001 11000011 11111111 11111111 11111111 00001000
# r12 01001001 10000001 11000100 11111111 11111111 11111111 00001000
# r13 01001001 10000001 11000101 11111111 11111111 11111111 00001000
# r14 01001001 10000001 11000110 11111111 11111111 11111111 00001000
# r15 01001001 10000001 11000111 11111111 11111111 11111111 00001000
# hex
# https://en.wikibooks.org/wiki/X86_Assembly/X86_Architecture
br64 = "r{{a,c,d,b}x,{s,b}p,{s,d}i,{8..15}}"
br32 = "{e{{a,c,d,b}x,{s,b}p,{s,d}i},r{8..15}d}"
br16 = "{{{a,c,d,b}x,{s,b}p,{s,d}i},r{8..15}w}"
br8 = "{{{a,c,d,b}{h,l},{s,b}pl,{s,d}il},r{8..15}b}"
r64 = braceexpandlist(br64) # 16
r32 = braceexpandlist(br32) # 16
r16 = braceexpandlist(br16) # 16
r8 = braceexpandlist(br8) # 20
flags = braceexpandlist("{{c,p,a,z,s,t,i,d,o,r,vi}f,ac,id,iopl,nt,vip,vm}")
xmm = braceexpandlist("xmm{0..15}")
st87 = braceexpandlist("st{0..7}")
valid = list()
valid.append([r64[2], r32[2], r16[2], r8[2 * 2], r8[2 * 2 + 1], xmm[0]])
valid.append([r64[3], r32[3], r16[3], r8[3 * 2], r8[3 * 2 + 1], xmm[1]])
valid.append([r64[8], r32[8], r16[8], r8[8 * 2], r8[8 * 1 + 4], xmm[2]])
valid.append([r64[9], r32[9], r16[9], r8[9 * 2], r8[9 * 1 + 4], xmm[3]])
# 48 89 e1 mov rcx, rsp
# 48 81 c1 f8 ff ff ff add rcx, 0FFFFFFFFFFFFFFF8h
# 51 push rcx
# 5c pop rsp
with BitwiseMask() as bm:
for r in r64:
# convert 32-bit ADD to 8-bit ADD
if r == 'rsp':
continue
# search = hex_pattern([re.sub(r' de ad ff 08', ' f8 ff ff ff', listAsHex(kassemble(search_asm)))])
search_asm = "add {}, dword 0fffffff8h".format(r)
search = nassemble(search_asm)
bm.add_list(search)
search = hex_pattern(listAsHex(search).replace('f8 ff ff ff', '08 00 00 00'))
bm.add_list(search)
# print("searchasm: %s" % search_asm)
# print("replaceasm: %s" % replace_asm)
# print("search: %s" % listAsHex(search))
# print("replace: %s" % listAsHex(replace))
# [values, mask] = gen_mask(None, previous)
# obfu.append_bitwise(values, mask, patch_32bit_add)
obfu.append_bitwise(bm.value, bm.mask, patch_32bit_add)
if debug: pp([binlist(bm._set), binlist(bm._clear), bm._size, bm._reserved, binlist(bm.value), binlist(bm.mask)])