forked from Satsuoni/widevine-l3-guesser
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Longsusrunner.py
1323 lines (1217 loc) · 45 KB
/
Longsusrunner.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
# Simple attempt emulate suspicious functions in widewine (4.10.2209.0). Adjust to taste (starting point, logs, etc) and run while project is open.
#@author Satsuoni
#@category Deobfuscation
#@keybinding
#@menupath
#@toolbar
from binascii import hexlify
import logging
from ghidra.app.emulator import EmulatorHelper
#from ghidra.program.model.symbol import SymbolUtilities
from ghidra.util.task import ConsoleTaskMonitor
from ghidra.program.model.pcode import PcodeOp
from ghidra.program.model.symbol import *
from ghidra.program.model.pcode import JumpTable
from java.util import LinkedList, Arrays, ArrayList
from ghidra.app.cmd.function import CreateFunctionCmd
from ghidra.app.cmd.disassemble import DisassembleCommand
from ghidra.program.model.lang import Register
from ghidra.program.model.lang import OperandType
from ghidra.program.model.lang import RegisterManager
import array
import sys
logger = logging.getLogger("")
logger.setLevel(logging.DEBUG)
handler1=logging.StreamHandler(sys.stdout)
class WarnFormatter(logging.Formatter):
err_fmt = "ERROR: %(msg)s"
warn_fmt = "Warning: %(msg)s"
dbg_fmt = "DBG: %(module)s: %(lineno)d: %(msg)s"
info_fmt = "%(msg)s"
def __init__(self, fmt="%(levelno)s: %(msg)s"):
logging.Formatter.__init__(self, fmt)
def format(self, record):
# Save the original format configured by the user
# when the logger formatter was instantiated
format_orig = self._fmt
# Replace the original format with one customized by logging level
if record.levelno == logging.DEBUG:
self._fmt = WarnFormatter.dbg_fmt
elif record.levelno == logging.INFO:
self._fmt = WarnFormatter.info_fmt
elif record.levelno == logging.ERROR:
self._fmt = WarnFormatter.err_fmt
elif record.levelno == logging.WARNING:
self._fmt = WarnFormatter.warn_fmt
# Call the original formatter class to do the grunt work
result = logging.Formatter.format(self, record)
# Restore the original format configured by the user
self._fmt = format_orig
return result
formatter = WarnFormatter('%(message)s')
handler1.setFormatter(formatter)
handler2=logging.FileHandler("trunlog.log", mode='w', encoding="utf-8")
handler2.setFormatter(formatter)
logger.addHandler(handler1)
logger.addHandler(handler2)
def getAddress(offset):
return currentProgram.getAddressFactory().getDefaultAddressSpace().getAddress(offset)
def getProgramRegisterList(currentProgram):
pc = currentProgram.getProgramContext()
return pc.registers
def step(emu,monitor):
success = emu.step(monitor)
if (success == False):
lastError = emu.getLastError()
logger.error("Emulation Error: '{}'".format(lastError))
return success
def isCallInstruction(instr):
if instr is None:
return False
flowType = instr.getFlowType()
if flowType.isCall():
return True
return False
# 009bc60e heap alloc. No free available or necessary
class FakeMemory(object):
def __init__(self,startpoint):
self.start=startpoint
self.curpoint=self.start
def allocate(self,ln):
rpoint=self.curpoint
self.curpoint+=ln
return rpoint
mem=FakeMemory( 0x000000F02FFF0000)
def EmuRet(emu,offs=0):
pos=emu.readStackValue(0,8,False)
emu.writeRegister(emu.getPCRegister(), pos)
stack=emu.readRegister("RSP")
emu.writeRegister("RSP",stack+8+offs)
def OperatorNew(emu):
bytes=emu.readRegister("RCX")
ptr=mem.allocate(bytes)
logger.info("Allocating (new) {} bytes to {:x}".format(bytes,ptr))
emu.writeRegister("RAX",ptr)
EmuRet(emu)
def HeapAlloc(emu):
bytes=emu.readRegister("R8")
logger.info("Allocating {} bytes".format(bytes))
ptr=mem.allocate(bytes)
emu.writeRegister("RAX",ptr)
EmuRet(emu)
def MFree(emu):
bt2=emu.readRegister("R8")
logger.info("Freed something at {:x}".format(bt2))
emu.writeRegister("RAX",bt2)
EmuRet(emu)
def EnterCriticalSection(emu):
EmuRet(emu)
def TryAcquireSRWLockExclusive(emu):
emu.writeRegister("RAX",1)
EmuRet(emu)
tlsval=1
tlsstorage={}
def TlsAlloc(emu):
global tlsval
emu.writeRegister("RAX",tlsval)
tlsval+=1
EmuRet(emu)
def TlsSetValue(emu):
global tlsval,tlsstorage
index=emu.readRegister("RCX")
value=emu.readRegister("RDX")
tlsstorage[index]=value
emu.writeRegister("RAX",1)
EmuRet(emu)
def TlsGetValue(emu):
global tlsval,tlsstorage
index=emu.readRegister("RCX")
if index in tlsstorage:
emu.writeRegister("RAX",tlsstorage[index])
else:
emu.writeRegister("RAX",0)
EmuRet(emu)
def QueryPerformanceFrequency(emu):
offs=emu.readRegister("RCX")
emu.writeMemoryValue(getAddress(offs),8,1000)
emu.writeRegister("RAX",1)
EmuRet(emu)
def Ret0(emu):
emu.writeRegister("RAX",0)
EmuRet(emu)
def Ret1(emu):
emu.writeRegister("RAX",1)
EmuRet(emu)
def Ret1st(emu):
emu.writeRegister("RAX",emu.readRegister("RCX"))
EmuRet(emu)
time_cnt=0
def timeGetTime(emu):
global time_cnt
emu.writeRegister("RAX",time_cnt)
time_cnt+=1
EmuRet(emu)
last_error=-20
def LoadLibrary(emu):
global last_error
offs=emu.readRegister("RCX")
lname=emu.readMemory(getAddress(offs),200)
logger.info("Load library: {}".format(lname))
emu.writeRegister("RAX",0)
last_error=-21
EmuRet(emu)
def GetLastError(emu):
global last_error
emu.writeRegister("RAX",last_error)
EmuRet(emu)
def SetLastError(emu):
global last_error
last_error=emu.readRegister("RCX")
EmuRet(emu)
def getptd_noexit(emu):
global mem
tiddata=mem.allocate(256) # _tiddata
emu.writeRegister("RAX",tiddata)
EmuRet(emu)
def findwindowA(emu):
lpclass=emu.readRegister("RCX")
lpname=emu.readRegister("RDX")
logger.info(emu.readNullTerminatedString(getAddress(lpclass),200))
logger.info(emu.readNullTerminatedString(getAddress(lpname),200))
emu.writeRegister("RAX",0)
EmuRet(emu)
def InitThreadHeader(emu):
mm=emu.readRegister("RCX")
logger.info("Init Thread header?")
emu.writeMemoryValue(getAddress(mm),4,-1)
EmuRet(emu)
def InitThreadFooter(emu):
mm=emu.readRegister("RCX")
logger.info("Init Thread footer?")
emu.writeMemoryValue(getAddress(mm),4,-1)
EmuRet(emu)
def GetRandom(emu):
ptr=emu.readRegister("RCX")
len=emu.readRegister("RDX")
logger.info("Random... kinda")
for a in range(len):
emu.writeMemoryValue(getAddress(ptr),1,0xaf)
ptr+=1
emu.writeRegister("RAX",1)
EmuRet(emu)
dict={}
dict[getAddress(0x009bc60e )]=HeapAlloc
dict[getAddress(0x009bc1ec )]=EnterCriticalSection
dict[getAddress(0x009bc61a )]=MFree
dict[getAddress(0x009bcae2 )]=TlsAlloc
dict[getAddress(0x009bcb06 )]=TlsSetValue
dict[getAddress(0x009bcaf8 )]=TlsGetValue
dict[getAddress(0x009bcb14 )]=TryAcquireSRWLockExclusive
dict[getAddress(0x009bc8d6 )]=EnterCriticalSection #void
dict[getAddress(0x009bc874 )]=QueryPerformanceFrequency
dict[getAddress(0x009bccb6 )]=timeGetTime
dict[getAddress(0x009bc7f6 )]=LoadLibrary
dict[getAddress(0x009bc422 )]=GetLastError
dict[getAddress(0x18052d44c)]=EnterCriticalSection #FlsSetValue
dict[getAddress(0x009bc7ba )]=EnterCriticalSection #LeaveCriticalSection
dict[getAddress(0x009bcce8 )]=findwindowA
dict[getAddress(0x009bc4ae )]=Ret0 #GetModuleHandle
dict[getAddress(0x009bc4e4 )]=Ret0 #GetProcAddress
dict[getAddress(0x009bcc80 )]=GetRandom #SystemFunction036
dict[getAddress(0x009bc81c )]=EnterCriticalSection #OutputDebugString - void
dict[getAddress(0x009bc392 )]=Ret1 #GetCurrentThreadId
dict[getAddress(0x009bc100 )]=Ret0 #AcquireSRWLockExclusive
dict[getAddress(0x18052cc50)]=getptd_noexit
dict[getAddress(0x009bca2a )]=SetLastError
dict[getAddress(0x180256270)]=Ret0 #GetCurrentDir??
dict[getAddress(0x18050f1c0)]=OperatorNew
#dict[getAddress(0x180111f45)]=Ret1 #probably a table generator. Very slow, but nothing works after without it
dict[getAddress(0x18050f330)]=InitThreadHeader
dict[getAddress(0x18050f3c8)]=InitThreadFooter
dict[getAddress(0x180256d10)]=Ret1st
dict[getAddress(0x18050f580)]=EnterCriticalSection
def allocLargeStdstring(emu,len):
ptr=mem.allocate(24)
emu.writeMemoryValue(getAddress(ptr+8),8,len)
emu.writeMemoryValue(getAddress(ptr+16),8,len)
buf=mem.allocate(len)
emu.writeMemoryValue(getAddress(ptr),8,buf)
return ptr
def HostAllocate(emu):
bytes=emu.readRegister("RDX")
logger.info("HostAllocate: {} bytes".format(bytes))
ptr=mem.allocate(bytes)
emu.writeRegister("RAX",ptr)
EmuRet(emu)
dict[getAddress(0x0aa01)]=HostAllocate
def HostSetTimer(emu):
delay=emu.readRegister("RDX")
logger.info("HostSetTimer: {} msec".format(delay))
EmuRet(emu)
dict[getAddress(0x0aa02)]=HostSetTimer
def HostGetCurrentWallTime(emu):
logger.info("HostGetCurrentWallTime")
emu.writeRegister("XMM0",0)
EmuRet(emu)
dict[getAddress(0x0aa03)]=HostGetCurrentWallTime
def HostOnInitialized(emu):
success=emu.readRegister("EDX")
logger.info("OnInitialized : maybe?: {}".format(success))
EmuRet(emu)
dict[getAddress(0x0aa04)]=HostOnInitialized
def HostOnResolveKeyStatusPromise(emu):
prid=emu.readRegister("EDX")
logger.info("HostOnResolveKeyStatusPromise : {}".format(prid))
EmuRet(emu)
dict[getAddress(0x0aa05)]=HostOnResolveKeyStatusPromise
def HostOnResolveNewSessionPromise(emu):
prid=emu.readRegister("EDX")
sesid=emu.readRegister("R8")
logger.info("OnResolveNewSessionPromise : {} {}".format(prid,sesid))
EmuRet(emu)
dict[getAddress(0x0aa06)]=HostOnResolveNewSessionPromise
def HostOnResolvePromise(emu):
prid=emu.readRegister("EDX")
logger.info("HostOnResolvePromise : {}".format(prid))
EmuRet(emu)
dict[getAddress(0x0aa07)]=HostOnResolvePromise
def HostOnRejectPromise(emu):
prid=emu.readRegister("EDX")
ex=emu.readRegister("R8")
sc=emu.readRegister("R9")
logger.info("HostOnRejectPromise : {} Exc: {} sc: {}".format(prid,ex,sc ))
EmuRet(emu,8)
dict[getAddress(0x0aa08)]=HostOnRejectPromise
def HostOnSessionMessage(emu):
saveSnapshot(emu,"OnSessionMessage.gz")
messSize=emu.readStackValue(0x30,8,False)
print(messSize)
messPtr=emu.readStackValue(0x28,8,False)
mtype=emu.readRegister("R9")
logger.info("message_type")
logger.info(mtype)
mm=emu.readMemory(getAddress(messPtr),int(messSize))
logger.info("OnSessionMessage {} {} ".format( mtype, mm))
rmsg=""
for a in mm:
if a<0: a=256+a
rmsg+="{:02X}".format(a)
logger.info(rmsg)
raise 999
EmuRet(emu,8)
dict[getAddress(0x0aa09)]=HostOnSessionMessage
def HostOnSessionKeysChange(emu):
logger.info("HostOnSessionKeysChange")
EmuRet(emu,8)
dict[getAddress(0x0aa0a)]=HostOnSessionKeysChange
def HostOnExpirationChange(emu):
logger.info("HostOnExpirationChange")
EmuRet(emu)
dict[getAddress(0x0aa0b)]=HostOnExpirationChange
def HostOnSessionClosed(emu):
logger.info("HostOnSessionClosed")
EmuRet(emu)
dict[getAddress(0x0aa0c)]=HostOnExpirationChange
def HostSendPlatformChallenge(emu):
logger.info("HostSendPlatformChallenge")
EmuRet(emu)
dict[getAddress(0x0aa0d)]=HostSendPlatformChallenge
def HostEnableOutputProtection(emu):
logger.info("HostEnableOutputProtection")
EmuRet(emu)
dict[getAddress(0x0aa0e)]=HostEnableOutputProtection
def HostQueryOutputProtectionStatus(emu):
logger.info("HostQueryOutputProtectionStatus")
EmuRet(emu)
dict[getAddress(0x0aa0f)]=HostQueryOutputProtectionStatus
def HostOnDeferredInitializationDone(emu):
logger.info("HostOnDeferredInitializationDone")
EmuRet(emu)
dict[getAddress(0x0aa10)]=HostOnDeferredInitializationDone
def HostCreateFileIO(emu):
logger.info("HostCreateFileIO")
emu.writeRegister("RAX",0)
EmuRet(emu)
dict[getAddress(0x0aa11)]=HostCreateFileIO
def HostRequestStorageId(emu):
logger.info("HostRequestStorageId")
EmuRet(emu)
dict[getAddress(0x0aa12)]=HostRequestStorageId
# create Host structure+vtable
def allocHost(emu):
vt_ptr=mem.allocate(8*16)
ptr=vt_ptr
emu.writeMemoryValue(getAddress(ptr),8,0x0aa01)
ptr+=8
emu.writeMemoryValue(getAddress(ptr),8,0x0aa02)
ptr+=8
emu.writeMemoryValue(getAddress(ptr),8,0x0aa03)
ptr+=8
emu.writeMemoryValue(getAddress(ptr),8,0x0aa04)
ptr+=8
emu.writeMemoryValue(getAddress(ptr),8,0x0aa05)
ptr+=8
emu.writeMemoryValue(getAddress(ptr),8,0x0aa06)
ptr+=8
emu.writeMemoryValue(getAddress(ptr),8,0x0aa07)
ptr+=8
emu.writeMemoryValue(getAddress(ptr),8,0x0aa08)
ptr+=8
emu.writeMemoryValue(getAddress(ptr),8,0x0aa09)
ptr+=8
emu.writeMemoryValue(getAddress(ptr),8,0x0aa0a)
ptr+=8
emu.writeMemoryValue(getAddress(ptr),8,0x0aa0b)
ptr+=8
emu.writeMemoryValue(getAddress(ptr),8,0x0aa0c)
ptr+=8
emu.writeMemoryValue(getAddress(ptr),8,0x0aa0d)
ptr+=8
emu.writeMemoryValue(getAddress(ptr),8,0x0aa0e)
ptr+=8
emu.writeMemoryValue(getAddress(ptr),8,0x0aa0f)
ptr+=8
emu.writeMemoryValue(getAddress(ptr),8,0x0aa10)
ptr+=8
emu.writeMemoryValue(getAddress(ptr),8,0x0aa11)
ptr+=8
emu.writeMemoryValue(getAddress(ptr),8,0x0aa12)
cls=mem.allocate(8)
emu.writeMemoryValue(getAddress(cls),8,vt_ptr)
return cls
def makeHost(emu):
logger.info("Getting host")
ptr=allocHost(emu)
emu.writeRegister("RAX",ptr)
EmuRet(emu)
def isCallOther(instr):
if instr is None:
return False
raw_pcode = instr.getPcode()
for code in raw_pcode:
if code.getOpcode()==PcodeOp.CALLOTHER:
return True
return False
def getCallOtherName(instr):
if instr is None:
return None
raw_pcode = instr.getPcode()
for code in raw_pcode:
if code.getOpcode()==PcodeOp.CALLOTHER:
return currentProgram.getLanguage().getUserDefinedOpName(code.getInput(0).getOffset())
return None
def skip(emu):
executionAddress = emu.getExecutionAddress()
instr=getInstructionAt(executionAddress)
nextInstr=instr.getNext()
lval = int("0x{}".format(nextInstr.getAddress()), 16)
emu.writeRegister(emu.getPCRegister(), lval)
dict[getAddress(0xf0000)]=makeHost
initCdm=getAddress(0x180001040)
monitor=ConsoleTaskMonitor()
rspStart=0x000000002FFF0000
emu=EmulatorHelper(currentProgram)
startaddr=initCdm#getAddress(0x18017e3b0)
cur_fun=getFunctionContaining(startaddr)
mainFunctionEntryLong = int("0x{}".format(cur_fun.getEntryPoint()), 16)
emu.writeRegister(emu.getPCRegister(), mainFunctionEntryLong)
emu.writeRegister("RSP", rspStart)
emu.writeRegister("RBP", 0x000000002FFF0000)
datstring=allocLargeStdstring(emu,256)
emu.writeRegister("RDX",datstring)
#clearkeys = "org.w3.clearkey"
import struct
def readULL(emu,addr):
dat=emu.readMemory(addr,8)
cdv=struct.unpack("<Q",dat)[0]
return cdv
def get_cptr(emu,string):
ptr=mem.allocate(len(string)+1)
emu.writeMemory(getAddress(ptr),string.encode("utf-8"))
emu.writeMemory(getAddress(ptr+len(string)),b'\0')
return ptr
def listToMem(emu,lst):
ptr=mem.allocate(len(lst)+1)
emu.writeMemory(getAddress(ptr),array.array('B',lst).tostring())
emu.writeMemory(getAddress(ptr+len(lst)),b'\0')
logger.info("Written memory is: {}".format(emu.readMemory(getAddress(ptr),len(lst))))
logger.info("Lst is is: {}".format(array.array('B',lst)))
return ptr
def EmuPush(emu,val):
stack=emu.readRegister("RSP")
stack=stack-8
emu.writeRegister("RSP",stack)
emu.writeMemoryValue(getAddress(stack), 8,val)
def EmuPull(emu,offs):
stack=emu.readRegister("RSP")
stack=stack+offs
emu.writeRegister("RSP",stack)
# +x30 +x20
def EmuPush4(emu,val):
stack=emu.readRegister("RSP")
stack=stack-4
emu.writeRegister("RSP",stack)
emu.writeMemoryValue(getAddress(stack), 4,val)
def isReturn(instr):
if instr is None:
return False
raw_pcode = instr.getPcode()
for code in raw_pcode:
if code.getOpcode()==PcodeOp.RETURN:
return True
return False
#fill process information blocks with varying garbage
emu.writeRegister("GS_OFFSET",0x3f000)
threadinfo=mem.allocate(1024)
pptr=threadinfo
#fill with the same struct 128 times
threaddata=mem.allocate(1024)
for a in range(128):
emu.writeMemoryValue(getAddress(pptr),8,threaddata)
pptr+=8
for a in range(1024):
emu.writeMemoryValue(getAddress(threaddata+a),1,0xff)
emu.writeMemoryValue(getAddress(0x3f058),8,threadinfo)
logger.info("GS: {:x}".format(emu.readRegister("GS_OFFSET")))
trace=False
class Operand(object):
def getVal(self,emu):
if self.type=="const":
return self.value
elif self.type=="register":
return emu.readRegister(self.value)
elif self.type=="stackvar":
return emu.readStackValue(int(self.value,0),self.length,False)
elif self.type=="memconst":
return 0 #need implementation?
def __hash__(self):
return hash((self.type, self.value))
def __eq__(self, other):
return (self.type, self.value) == (other.type, other.value)
def __ne__(self, other):
return not(self == other)
def __init__(self,instr,num):
self.type="unknown"
if instr is None:
return
if num>=instr.getNumOperands():
return
tp=instr.getOperandType(num)
objlist=instr.getOpObjects(num)
ln=len(objlist)
if ln==0:
return
if tp&OperandType.SCALAR: #const
self.type="const"
self.value=int(str(objlist[0]),16)
return
if tp&OperandType.REGISTER and len(objlist)==1: #pure register
self.type="register"
self.value=str(objlist[0])
return
if len(objlist)==2 and str(objlist[0])=="RSP":
self.type="stackvar"
self.value="0x{:x}".format(int(str(objlist[1]),0))
self.offset=int(str(objlist[1]),0)
self.len=1
oprep=instr.getDefaultOperandRepresentation(num)
if "xword" in oprep:
self.length=16
elif "qword" in oprep:
self.length=8
elif "dword" in oprep:
self.length=4
elif "word ptr" in oprep:
self.length=2
elif "byte ptr" in oprep:
self.length=1
return
if len(objlist)==2 and tp&OperandType.DYNAMIC and tp&OperandType.ADDRESS : #dword ptr [RCX + -0x4]
self.type="memconst"
self.value=str(objlist[1])
self.olist=objlist
return
if len(objlist)==2 and str(objlist[0])=="GS":
self.type="debugho"
self.value="__0x{:x}".format(int(str(objlist[1]),0))
return
if len(objlist)==3 and isinstance(objlist[0],Register): #not quite correct, but. uff
self.type="register"
self.value=str(objlist[0])
return
logger.warning("{} {:x} {} needs operand implementation {}".format(instr,tp,num,objlist))
#not sure why only these are missing.
def pshuflw(emu,instr):
if instr is None: return
if instr.getNumOperands()!=3: return
reg_into=Operand(instr,0)
reg_from=Operand(instr,1)
shuf=Operand(instr,2)
if reg_into.type!="register" or reg_from.type!="register" or shuf.type!="const" :
raise 33
fr=emu.readRegister(reg_from.value)
imm=shuf.value
to=(fr&0xffffffffffffffff0000000000000000)
to+=(fr>> (imm&4)*16 )&0xffff
to+=((fr>> ( (imm>>2) & 4)*16 )&0xffff)<<16
to+=((fr>> ( (imm>>4) & 4)*16 )&0xffff)<<32
to+=((fr>> ( (imm>>8) & 4)*16 )&0xffff)<<48
emu.writeRegister(reg_into.value,to)
skip(emu)
def pmovmskb(emu,instr):
if instr is None: return
if instr.getNumOperands()!=2: return
reg_into=Operand(instr,0)
reg_from=Operand(instr,1)
if reg_into.type!="register" or reg_from.type!="register":
raise 34
fr=emu.readRegister(reg_from.value)
cnt=1
val=0
for bt in range(16):
idir=int((fr&(1<<(8*cnt-1)))!=0)
val |= (idir<<bt)
cnt+=1
emu.writeRegister(reg_into.value,val)
skip(emu)
def dumpParameters(emu,num):
pars=[emu.readRegister("RCX"),emu.readRegister("RDX"),emu.readRegister("R8"),emu.readRegister("R9")]
if num>4:
co=0x28
esp=emu.readRegister("ESP")
for a in range(num-4):
pars.append(readULL(emu,getAddress(esp+co)))
co+=8
for a in range (num):
logger.info("Param_{}: {:x}".format(a+1,pars[a]))
def writeRegister(emu,reg,fl):
nm=reg.getName()
ln=reg.getMinimumByteSize()
if ln >8:
ln=16
elif ln>4:
ln=8
elif ln >2:
ln=4
else:
ln=2
fl.write(struct.pack("<H", len(nm)))
fl.write(nm.encode("ascii"))
fl.write(struct.pack("<H", ln))
val=emu.readRegister(nm)
if ln==16:
fl.write(struct.pack("<Q", (val>>64)&0xffffffffffffffff ))
fl.write(struct.pack("<Q", val&0xffffffffffffffff))
elif ln==8:
fl.write(struct.pack("<Q", val&0xffffffffffffffff))
elif ln==4:
fl.write(struct.pack("<I", val&0xffffffff))
else:
fl.write(struct.pack("<H", val&0xffff))
def writeMemoryChunk(emu,start,ln,fl):
fl.write(struct.pack("<Q",start))
fl.write(struct.pack("<Q",ln))
if ln>0:
mbuf=emu.readMemory(getAddress(start),ln)
fl.write(mbuf)
def writeSnapshot(emu,fl):
global mem, rspStart, currentProgram
excl=set(["contextreg"])
br=set([e.getBaseRegister() for e in getProgramRegisterList(currentProgram) if e.getBaseRegister().getName() not in excl])
rsp=emu.readRegister("RSP")
fl.write(struct.pack("<I",len(br)))
for reg in br:
writeRegister(emu,reg,fl)
writeMemoryChunk(emu,mem.start,mem.curpoint-mem.start,fl)
if rsp<=rspStart:
writeMemoryChunk(emu,rsp,rspStart-rsp+8,fl)
for blk in currentProgram.getMemory().getBlocks():
writeMemoryChunk(emu,blk.getStart().getOffset(),blk.getSize(),fl)
def readRegister(emu,fl):
dt=fl.read(2)
if len(dt)<2: return False
nmlen=struct.unpack("<H",dt)[0]
nml=fl.read(nmlen)
if len(nml)<nmlen: return False
nm=nml.decode("ascii")
dt=fl.read(2)
if len(dt)<2: return False
ln=struct.unpack("<H",dt)[0]
if ln==16:
dt=fl.read(16)
if len(dt)<16: return False
vals=struct.unpack("<QQ",dt)
val=(vals[0]<<64)+vals[1]
elif ln==8:
dt=fl.read(8)
if len(dt)<8: return False
val=struct.unpack("<Q",dt)[0]
elif ln==4:
dt=fl.read(4)
if len(dt)<4: return False
val=struct.unpack("<I",dt)[0]
else:
dt=fl.read(2)
if len(dt)<2: return False
val=struct.unpack("<H",dt)[0]
if nm!= "contextreg":
emu.writeRegister(nm,val)
return True
def readMemoryChunk(emu,fl,setmem=False):
#start,ln,
global mem
dt=fl.read(8)
if len(dt)<8: return False
start=struct.unpack("<Q",dt)[0]
dt=fl.read(8)
if len(dt)<8: return False
ln=struct.unpack("<Q",dt)[0]
if ln>0:
dat=fl.read(ln)
if len(dat)<ln: return False
emu.writeMemory(getAddress(start),dat)
if setmem:
mem.start=start
mem.curpoint=start+ln
return True
def readSnapshot(emu,fl):
global mem, rspStart
numreg=struct.unpack("<I",fl.read(4))[0]
for i in range(numreg):
if not readRegister(emu,fl):
logger.warning("Corrupt snapshot: not enough registers")
return
mset=True
while readMemoryChunk(emu,fl,mset):
mset=False
import gzip
import os
basedir="./"
def saveSnapshot(emu,name):
global basedir
fname=os.path.join(basedir,name)
with gzip.open(fname, 'wb',compresslevel=8) as f:
writeSnapshot(emu,f)
def loadSnapshot(emu,name):
global basedir
fname=os.path.join(basedir,name)
with gzip.open(fname, 'rb') as f:
readSnapshot(emu,f)
class Permutator(object): #for 256-byte objects...
def __init__(self, grabAddr,tableReg,ptrReg,name=None,cntd=31):
self.grabAddr=grabAddr
self.table=None
self.tableReg=tableReg
self.ptrReg=ptrReg
self.countdown=0
self.name=name
self.cntd=cntd
def grab(self, emu,addr):
if addr==self.grabAddr:
if self.table is None:
print("Getting table from {}".format(self.tableReg))
if isinstance(self.tableReg, (int,long)):
rg=self.tableReg
else:
rg=emu.readRegister(self.tableReg)
self.table=[]
for a in range(32):
self.table.append(emu.readMemoryByte(getAddress(rg+a)))
if self.countdown>0:
self.countdown-=1
else:
#print("Grabbing at {}".format(addr))
if isinstance(self.ptrReg,list):
if len(self.ptrReg)==2:
dataAddr=emu.readRegister(self.ptrReg[0])+self.ptrReg[1]
else:
indirAddr=emu.readRegister(self.ptrReg[0])+self.ptrReg[1]
dataAddr=readULL(emu,getAddress(indirAddr))
elif isinstance(self.ptrReg,(int,long)):
dataAddr=self.ptrReg
else:
dataAddr=emu.readRegister(self.ptrReg)
val=0
for a in range(32):
dlt=readULL(emu,getAddress(dataAddr+8*self.table[a]))
val=val+dlt*(1<<(64*a))
self.countdown=self.cntd
if self.name is None:
logger.info("Grabbed at {}: {:x}".format(self.grabAddr,val))
else:
logger.info("Grabbed {} at {}: {:x}".format(self.name,self.grabAddr,val))
class BCollector(object):
def __init__(self,name,startAddr,collectAddr,collectA,collectB,endAddr,paraCol=False):
self.name=name
self.startAddr=getAddress(startAddr)
self.endAddr=getAddress(endAddr)
self.collectAddr=getAddress(collectAddr)
self.isCollecting=False
self.collectA=collectA
self.a=0
self.collectB=collectB
self.b=0
self.cnt=0
self.cntb=0
self.paracol=paraCol
def emget(self,emu, coll):
lc=len(coll)
if lc ==1:
if isinstance(coll[0],int):
return readULL(emu,getAddress(coll[0]))
else:
return emu.readRegister(coll[0])
elif lc==2: #[reg+const]
addr=emu.readRegister(coll[0])+coll[1]
return readULL(emu,getAddress(addr))
elif lc==3: #[reg+reg*const]
addr=emu.readRegister(coll[0])+emu.readRegister(coll[1])*coll[2]
#logger.info("Cll: {:x} {:x} {:x}".format(emu.readRegister(coll[0]),emu.readRegister(coll[1]),addr))
return readULL(emu,getAddress(addr))
elif lc==4: #[reg+reg*const+c2]
addr=emu.readRegister(coll[0])+emu.readRegister(coll[1])*coll[2]+coll[3]
return readULL(emu,getAddress(addr))
elif lc==5: # ["RSP",40,"RAX",8,"indir"]
addr=emu.readRegister(coll[0])+coll[1]
addr2=readULL(emu,getAddress(addr))+emu.readRegister(coll[2])*coll[3]
return readULL(emu,getAddress(addr2))
def collect(self,emu,addr):
if addr==self.startAddr:
self.a=0
self.b=0
self.cntb=0
self.cnt=0
self.isCollecting=True
elif addr==self.endAddr:
logger.info("Collected as {} ,a : {:x}".format(self.name,self.a))
logger.info("Collected as {} ,b : {:x}".format(self.name,self.b))
logger.info("Collection rounds as {} , {}".format(self.name,self.cnt))
self.a=0
self.b=0
self.cnt=0
self.isCollecting=False
elif addr==self.collectAddr and self.isCollecting:
da=self.emget(emu,self.collectA)
if not self.paracol:
db=self.emget(emu,self.collectB)
ml=(1<<(64*self.cnt))
self.a+=ml*da
if not self.paracol:
self.b+=ml*db
self.cnt+=1
elif self.isCollecting and self.paracol and self.cntb<32 and addr>self.startAddr and addr<self.endAddr:
instr=getInstructionAt(addr)
if instr.getMnemonicString()=="MUL":
db=self.emget(emu,self.collectB)
ml=(1<<(64*self.cntb))
self.b+=ml*db
self.cntb+=1
snc=528
def dumpBuffer(emu,offs_addr,ln):
dl=emu.readMemory(getAddress(offs_addr),ln)
dst=""
for a in dl:
if a<0: a+=256
dst+="{:02X}".format(a)
logger.info("{}".format(dst))
def runModule(start,lSnapshot=None):
global trace, basedir, snc
cur_fun=getFunctionContaining(start)
mainFunctionEntryLong = int("0x{}".format(cur_fun.getEntryPoint()), 16)
emu.writeRegister(emu.getPCRegister(), mainFunctionEntryLong)
#for nl in range(nnl):
subN=False
nnn=0
fff=0
ncnt=0
cnt=0
#stack=emu.readRegister("RSP")
fname=None
if lSnapshot is not None:
if os.path.isfile(lSnapshot):
fname=lSnapshot
elif os.path.isfile(os.path.join(basedir,lSnapshot)):
fname=os.path.join(basedir,lSnapshot)
else:
logger.warning("{} is not correct file name".format(lSnapshot))
if fname is None:
EmuPush(emu,0xfafadeadbeef)
else:
loadSnapshot(emu,fname)
snapcnt=0
#precoll= BCollector("MbSubtr",0x18017b07c,0x18017b0eb,["R14"],["RCX","RAX",8],0x18017b13f)
#ncoll=BCollector("SubN",0x18017b140,0x18017b1e5,["RDI"],["RAX"],0x18017b24b)
#vcoll=BCollector("VC",0x18016dc81,0x18016dcb5,["RCX"],["RCX"],0x18016dcdb)
#pcoll=BCollector("Plus",0x18017b367,0x18017b397,["R14","RAX",8],["R15","RAX",8],0x18017b3ff)
#ucoll=BCollector("Upper",0x18017c4d2,0x18017c52a,["RAX"],["R12","RCX",8],0x18017d326,False)
#yacoll=BCollector("YetAnother",0x18017b513,0x18017b578,["RAX"],["R14","RCX",8],0x18017c2f5,False)
#hm1coll=BCollector("HasMulAdd",0x18016dd26,0x18016dd87,["RAX"],["R13","RCX",8],0x18016ebb4,False)
#hm2coll=BCollector("HasMulAdd2",0x18016ec3f,0x18016eca5,["RAX"],["R12","RCX",8],0x18016fab9,False)
#mnscoll=BCollector("Subtractor",0x18017d4ac,0x18017d54a,["R12"],["RAX"],0x18017d598)
# add permutators to track Bignum manipulation. Each one slows down execution, so use with care?
prms=[Permutator(getAddress(0x18017c373),"RSI","R14"),
Permutator(getAddress(0x18017c505),"RBX","R12"),
Permutator(getAddress(0x18017b0c7),"RDI","R15"),
#MaybeImportantSubtraction
Permutator(getAddress(0x18017b0eb),0x180bb7258,"R15","SubtractionA"), #maybesubtraction
Permutator(getAddress(0x18017b0eb),0x180bb7258,["RSP", 32,"rd"],"SubtractionB"), #maybesubtraction
#SubN - moved to next function that actually finalized modN operation, it seems.
Permutator(getAddress(0x18017b33d),0x180bb7258,["RSP", 32,"rd"],"ModN",0),
#VC - maybe first op?
Permutator(getAddress(0x18016dce0),0x180bb7258,["RSP", 0xae20],"VC"), #VC
#LooksSum: only args?
Permutator(getAddress(0x18017b367),0x180bb7258,"R15","SumA",0),#sum?
Permutator(getAddress(0x18017b367),0x180bb7258,"R14","SumB",0),#sum?
#Plum - only result
Permutator(getAddress(0x18017b4ba),0x180bb7258,"R13","PostSum",0),#dealing with overflow?
#"Upper" multiply. Looks like square, honestly
Permutator(getAddress(0x18017d313),0x180bb7258,["RSP", 48,"rd"],"Upper",0),
#YetAnother: get args:
Permutator(getAddress(0x18017b513),0x180bb7258,["RSP", 0x60,"rd"],"MulA",0),#mul?
Permutator(getAddress(0x18017b513),0x180bb7258,["RSP", 56,"rd"],"MulB",0),#mul?
#Main(?) func has several multiplies separate
Permutator(getAddress(0x18016dd26),0x180bb7258,["RSP", 0xab20],"Main1A",0),
Permutator(getAddress(0x18016dd26),0x180bb7258,0x180650ef0,"Main1B",0),
Permutator(getAddress(0x18016ec3f),0x180bb7258,["RSP", 0xaa20],"Main2A",0),
Permutator(getAddress(0x18016ec3f),0x180bb7258,0x180651450,"Main2B",0),
#CopyLnum
Permutator(getAddress(0x18017c39f),0x180bb7258,"R15","Copy",0),
# Second func (decrypt?)
Permutator(getAddress(0x180148eea),0x180bb70d4,"R15","S_SubtractionA"), #maybesubtraction
Permutator(getAddress(0x180148eea),0x180bb70d4,["RSP", 32,"rd"],"S_SubtractionB"), #maybesubtraction
#main
Permutator(getAddress(0x180144477),0x180bb70d4,["RSP", 0xb000],"S_Main1A",0),
Permutator(getAddress(0x180144477),0x180bb70d4,0x18064e750,"S_Main1B",0),
#nmodulo
Permutator(getAddress(0x1801491ab),0x180bb70d4,["RSP", 32,"rd"],"S_ModN",0),
#sum
Permutator(getAddress(0x1801491e5),0x180bb70d4,"R15","S_SumA",0),#sum?
Permutator(getAddress(0x1801491e5),0x180bb70d4,"R14","S_SumB",0),#sum?
#sumres
Permutator(getAddress(0x180149328),0x180bb70d4,"R13","PostSum",0),#dealing with overflow?
Permutator(getAddress(0x18017d50a),"RSI","RCX"),
#Permutator(getAddress(0x18017d535),"RDI","RCX"), is xored??
#AdcUser??
Permutator(getAddress(0x18014b378),"RSI","RCX"),
#SumAdc??
Permutator(getAddress(0x180149205),"RDI","R15"),
Permutator(getAddress(0x180149228),"RDI","R14"),
#Another minusN?
Permutator(getAddress(0x180149013),"RBX","RCX"),
#Mul is suspect
Permutator(getAddress(0x1801444a6),"R13",["RSP", 0xb000]),
]
#prms=[]
coutp=None
cclen=None
#very detailed trace, good for spotting small discrepancies but slow and verbose
superTrace=False
while True:
executionAddress = emu.getExecutionAddress()
if executionAddress==getAddress(0xfafadeadbeef):
logger.info("Probably return ")
break
if executionAddress==getAddress(0x18016dc81):
rsp=emu.readRegister("RSP")+0xb120
logger.info("Preload")
dumpBuffer(emu,rsp,0x402)
if executionAddress==getAddress(0x18016d323):
rsi=emu.readRegister("RSI")