forked from bkerler/mtkclient
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mtk
executable file
·1709 lines (1638 loc) · 99.6 KB
/
mtk
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# MTK Flash Client (c) B.Kerler 2018-2021.
# Licensed under MIT License
import shutil
import os
import json
import sys
import logging
import time
import argparse
from binascii import hexlify
from struct import unpack, pack
from mtkclient.config.usb_ids import default_ids
from mtkclient.config.payloads import pathconfig
from mtkclient.Library.pltools import PLTools
from mtkclient.Library.mtk_preloader import Preloader
from mtkclient.Library.mtk_daloader import DAloader
from mtkclient.Library.Port import Port
from mtkclient.Library.utils import LogBase, logsetup, getint
from mtkclient.config.brom_config import Mtk_Config
from mtkclient.Library.utils import print_progress
from mtkclient.Library.error import ErrorHandler
def split_by_n(seq, unit_count):
"""A generator to divide a sequence into chunks of n units."""
while seq:
yield seq[:unit_count]
seq = seq[unit_count:]
class ArgHandler(metaclass=LogBase):
def __init__(self, args, config):
try:
if args.vid is not None:
config.vid = getint(args.vid)
except AttributeError:
pass
try:
if args.pid is not None:
config.pid = getint(args.pid)
except AttributeError:
pass
try:
if args.payload is not None:
config.payloadfile = args.payload
except:
pass
try:
if args.loader is not None:
config.loader=args.loader
except AttributeError:
pass
try:
if args.da_address is not None:
config.chipconfig.da_payload_addr = getint(args.da_address)
self.info("O:DA offset:\t\t\t" + args.da_address)
except AttributeError:
pass
try:
if args.brom_address is not None:
config.chipconfig.brom_payload_addr = getint(args.brom_address)
self.info("O:Payload offset:\t\t" + args.brom_address)
except AttributeError:
pass
try:
if args.watchdog_address is not None:
config.chipconfig.watchdog = getint(args.wdt)
self.info("O:Watchdog addr:\t\t" + args.wdt)
except AttributeError:
pass
try:
if args.skipwdt is not None:
config.skipwdt = args.skipwdt
except AttributeError:
pass
try:
if args.uart_address is not None:
config.chipconfig.uart = getint(args.uart_address)
self.info("O:Uart addr:\t\t" + args.uart_address)
except AttributeError:
pass
try:
if args.preloader is not None:
config.chipconfig.var1 = getint(args.var1)
self.info("O:Var1:\t\t" + args.var1)
except AttributeError:
pass
try:
if args.preloader is not None:
config.preloader = args.preloader
except AttributeError:
pass
try:
if args.generatekeys is not None:
config.generatekeys = args.generatekeys
except AttributeError:
pass
try:
if args.ptype is not None:
config.ptype = args.ptype
except AttributeError:
pass
try:
if args.socid is not None:
config.readsocid = args.socid
except AttributeError:
pass
try:
if args.crash is not None:
config.enforcecrash = args.crash
except AttributeError:
pass
class Mtk(metaclass=LogBase):
def __init__(self, config, loglevel=logging.INFO, preinit=True):
self.config = config
self.loader = config.loader
self.vid = config.vid
self.pid = config.pid
self.interface = config.interface
self.pathconfig = pathconfig()
self.__logger = logsetup(self, self.__logger, loglevel)
self.eh = ErrorHandler()
if preinit:
self.init()
def patch_preloader_security(self, data):
patched = False
data = bytearray(data)
patches = [
("A3687BB12846","0123A3602846"), #oppo security
("B3F5807F01D1", "B3F5807F01D14FF000004FF000007047"), #confirmed : mt6739 c30, mt6833
("B3F5807F04BF4FF4807305F011B84FF0FF307047", "B3F5807F04BF4FF480734FF000004FF000007047"),
]
i=0
for patchval in patches:
pattern = bytes.fromhex(patchval[0])
idx = data.find(pattern)
if idx != -1:
patch = bytes.fromhex(patchval[1])
data[idx:idx + len(patch)] = patch
patched = True
#break
i+=1
if patched:
# with open(sys.argv[1]+".patched","wb") as wf:
# wf.write(data)
# print("Patched !")
self.info(f"Patched preloader security: {hex(i)}")
else:
self.warning(f"Failed to patch preloader security")
return data
def parse_preloader(self, preloader):
if isinstance(preloader, str):
if os.path.exists(preloader):
with open(preloader, "rb") as rf:
data=rf.read()
else:
data=preloader
data=bytearray(data)
magic = unpack("<I", data[:4])[0]
if magic == 0x014D4D4D:
self.info(f"Valid preloader detected.")
daaddr = unpack("<I", data[0x1C:0x20])[0]
dasize = unpack("<I", data[0x20:0x24])[0]
maxsize = unpack("<I", data[0x24:0x28])[0]
content_offset = unpack("<I", data[0x28:0x2C])[0]
sig_length = unpack("<I", data[0x2C:0x30])[0]
jump_offset = unpack("<I", data[0x30:0x34])[0]
daaddr = jump_offset + daaddr
dadata = data[jump_offset:]
else:
self.warning("Preloader detected as shellcode, might fail to run.")
daaddr = self.config.chipconfig.da_payload_addr
dadata = data
return daaddr, dadata
def init(self, vid=None, pid=None, interface=None):
if vid is None:
vid = self.vid
if pid is None:
pid = self.pid
if interface is None:
interface = self.interface
if vid != -1 and pid != -1:
if interface == -1:
for dev in default_ids:
if dev[0] == vid and dev[1] == pid:
interface = dev[2]
break
portconfig = [[vid, pid, interface]]
else:
portconfig = default_ids
self.port = Port(self, portconfig, self.__logger.level)
self.preloader = Preloader(self, self.__logger.level)
self.daloader = DAloader(self, self.__logger.level)
def crasher(self, display=True, mode=None):
rmtk = self
plt = PLTools(self, self.__logger.level)
if self.config.enforcecrash or self.config.meid is None:
self.info("We're not in bootrom, trying to crash da...")
if mode is None:
for crashmode in range(0, 3):
try:
plt.crash(crashmode)
except:
pass
rmtk = Mtk(config=self.config, loglevel=self.__logger.level)
rmtk.preloader.display = display
if rmtk.preloader.init(maxtries=20):
break
else:
try:
plt.crash(mode)
except Exception as err:
self.__logger.debug(str(err))
pass
rmtk = Mtk(config=self.config, loglevel=self.__logger.level)
rmtk.preloader.display = display
if rmtk.preloader.init(maxtries=20):
return rmtk
return rmtk
def bypass_security(self):
mtk = self.crasher()
plt = PLTools(mtk, self.__logger.level)
if self.config.payloadfile is None:
if self.config.chipconfig.loader is None:
self.config.payloadfile = os.path.join(self.pathconfig.get_payloads_path(), "generic_patcher_payload.bin")
else:
self.config.payloadfile = os.path.join(self.pathconfig.get_payloads_path(), self.config.chipconfig.loader)
if plt.runpayload(filename=self.config.payloadfile):
mtk.port.run_handshake()
# mtk.port.close()
# mtk = Mtk(loader=args.loader, loglevel=self.__logger.level, vid=vid, pid=pid,
# interface=interface, args=args)
# mtk.preloader.init(args=args, readsocid=readsocid)
return mtk
else:
self.error("Error on running kamakiri payload")
return self
class Main(metaclass=LogBase):
def __init__(self, args):
self.__logger = self.__logger
self.info = self.__logger.info
self.debug = self.__logger.debug
self.error = self.__logger.error
self.warning = self.__logger.warning
self.args = args
if not os.path.exists("logs"):
os.mkdir("logs")
def dump_preloader_ram(self, mtk):
try:
data = b"".join([pack("<I", val) for val in mtk.preloader.read32(0x200000, 0x10000 // 4)])
idx = data.find(b"\x4D\x4D\x4D\x01\x38\x00\x00\x00")
if idx != -1:
data = data[idx:]
length = unpack("<I", data[0x20:0x24])[0]
time.sleep(0.05)
data = b"".join([pack("<I", val) for val in mtk.preloader.read32(0x200000 + idx, length + 4 // 4)])
preloader = data[:length]
idx = data.find(b"MTK_BLOADER_INFO")
if idx != -1:
filename = data[idx + 0x1B:idx + 0x1B + 0x30].rstrip(b"\x00").decode('utf-8')
if preloader is not None:
pfilename = os.path.join(mtk.pathconfig.get_loader_path(), "Preloader", filename)
if not os.path.exists(pfilename):
with open(pfilename, "wb") as wf:
wf.write(preloader)
print(f"Successfully extracted preloader for this device to: {pfilename}")
return preloader
except Exception as err:
self.error(str(err))
return None
def close(self):
sys.exit(0)
def run(self):
try:
if self.args.debugmode:
loglevel=logging.DEBUG
self.__logger.setLevel(logging.DEBUG)
else:
loglevel=logging.INFO
self.__logger.setLevel(logging.INFO)
except:
loglevel=logging.INFO
self.__logger.setLevel(logging.INFO)
pass
config = Mtk_Config(loglevel=loglevel)
ArgHandler(self.args, config)
self.eh = ErrorHandler()
mtk = Mtk(config=config, loglevel=loglevel)
if mtk.config.debugmode:
logfilename = os.path.join("logs", "log.txt")
if os.path.exists(logfilename):
os.remove(logfilename)
fh = logging.FileHandler(logfilename)
self.__logger.addHandler(fh)
self.debug(" ".join(sys.argv))
cmd = self.args.cmd
if cmd == "dumpbrom":
if mtk.preloader.init():
rmtk = mtk.crasher()
if rmtk is None:
sys.exit(0)
if rmtk.port.cdc.vid != 0xE8D and rmtk.port.cdc.pid != 0x0003:
self.warning("We couldn't enter preloader.")
filename = self.args.filename
if filename is None:
cpu = ""
if rmtk.config.cpu != "":
cpu = "_" + rmtk.config.cpu
filename = "brom" + cpu + "_" + hex(rmtk.config.hwcode)[2:] + ".bin"
plt = PLTools(rmtk, self.__logger.level)
plt.run_dump_brom(filename, self.args.ptype)
rmtk.port.close()
self.close()
elif cmd == "dumppreloader":
if mtk.preloader.init():
rmtk = mtk.crasher()
if rmtk is None:
sys.exit(0)
if rmtk.port.cdc.vid != 0xE8D and rmtk.port.cdc.pid != 0x0003:
self.warning("We couldn't enter preloader.")
plt = PLTools(rmtk, self.__logger.level)
data, filename = plt.run_dump_preloader(self.args.ptype)
if data is not None:
if filename == "":
if self.args.filename is not None:
filename = self.args.filename
else:
filename = "preloader.bin"
with open(filename, 'wb') as wf:
print_progress(0, 100, prefix='Progress:', suffix='Complete', bar_length=50)
wf.write(data)
print_progress(100, 100, prefix='Progress:', suffix='Complete', bar_length=50)
self.info("Preloader dumped as: " + filename)
rmtk.port.close()
self.close()
elif cmd == "brute":
self.info("Kamakiri / DA Bruteforce run")
rmtk = Mtk(config=mtk.config, loglevel=self.__logger.level)
plt = PLTools(rmtk, self.__logger.level)
plt.runbrute(self.args)
self.close()
elif cmd == "crash":
if mtk.preloader.init():
mtk = mtk.crasher(mode=getint(self.args.mode))
mtk.port.close()
self.close()
elif cmd == "plstage":
dadata = None
if mtk.config.chipconfig.pl_payload_addr is not None:
plstageaddr = mtk.config.chipconfig.pl_payload_addr
else:
plstageaddr = 0x40200000 # 0x40001000
if self.args.pl is None:
plstage = os.path.join(mtk.pathconfig.get_payloads_path(), "pl.bin")
else:
plstage = self.args.pl
if os.path.exists(plstage):
with open(plstage, "rb") as rf:
rf.seek(0)
pldata = rf.read()
if mtk.preloader.init():
if mtk.config.target_config["daa"]:
mtk = mtk.bypass_security()
if mtk is None:
self.error("Error on bypassing security, aborting")
return
self.info("Connected to device, loading")
else:
self.error("Couldn't connect to device, aborting.")
if mtk.config.preloader is not None:
filename=mtk.config.preloader
if mtk.config.is_brom and mtk.config.preloader is None:
self.warning("PL stage needs preloader, please use --preloader option. " +
"Trying to dump preloader from ram.")
plt = PLTools(mtk=mtk, loglevel=self.__logger.level)
dadata, filename = plt.run_dump_preloader(self.args.ptype)
mtk.config.preloader = self.patch_preloader_security(dadata)
if mtk.config.preloader is not None:
self.info("Using custom preloader : "+filename)
daaddr, dadata = mtk.parse_preloader(mtk.config.preloader)
if mtk.preloader.send_da(daaddr, len(dadata), 0x100, dadata):
self.info(f"Sent preloader to {hex(daaddr)}, length {hex(len(dadata))}")
if mtk.preloader.jump_da(daaddr):
self.info(f"PL Jumped to daaddr {hex(daaddr)}.")
time.sleep(2)
mtk = Mtk(config=mtk.config, loglevel=self.__logger.level)
res = mtk.preloader.init()
if not res:
self.error("Error on loading preloader")
return
else:
self.info("Successfully connected to pl")
if self.args.startpartition is not None:
partition = self.args.startpartition
self.info("Booting to : " + partition)
# if data[0:4]!=b"\x88\x16\x88\x58":
# data=0x200*b"\x00"+data
mtk.preloader.send_partition_data(partition, pldata)
status = mtk.preloader.jump_to_partition(partition) # Do not remove !
if status!=0x0:
self.error("Error on jumping to partition: "+self.eh.status(status))
else:
self.info("Jumping to partition ....")
return
if mtk.preloader.send_da(plstageaddr, len(pldata), 0x100, pldata):
self.info(f"Sent stage2 to {hex(plstageaddr)}, length {hex(len(pldata))}")
mtk.preloader.get_hw_sw_ver()
if mtk.preloader.jump_da(plstageaddr):
self.info(f"Jumped to stage2 at {hex(plstageaddr)}.")
ack = unpack(">I", mtk.port.usbread(4))[0]
if ack == 0xB1B2B3B4:
self.info("Successfully loaded stage2")
return
else:
self.error("Error on jumping to pl")
return
else:
self.error("Error on sending pl")
return
self.close()
elif cmd == "peek":
addr = getint(self.args.address)
length = getint(self.args.length)
if self.args.preloader is not None:
preloader = self.args.preloader
if os.path.exists(preloader):
daaddr, dadata = mtk.parse_preloader(preloader)
if self.args.filename is None:
filename = ""
else:
filename = self.args.filename
if mtk.preloader.init():
if mtk.config.target_config["daa"]:
mtk = mtk.bypass_security()
if mtk is not None:
if self.args.preloader is not None:
if mtk.preloader.send_da(daaddr, len(dadata), 0x100, dadata):
self.info(f"Sent preloader to {hex(daaddr)}, length {hex(len(dadata))}")
if mtk.preloader.jump_da(daaddr):
self.info(f"Jumped to pl {hex(daaddr)}.")
time.sleep(2)
mtk = Mtk(loglevel=self.__logger.level)
res = mtk.preloader.init()
if not res:
self.error("Error on loading preloader")
return
else:
self.info("Successfully connected to pl.")
# mtk.preloader.get_hw_sw_ver()
# status=mtk.preloader.jump_to_partition(b"") # Do not remove !
else:
self.error("Error on jumping to pl")
return
self.info("Starting to read ...")
dwords = length // 4
if length % 4:
dwords += 1
if filename != "":
wf = open(filename, "wb")
sdata = b""
print_progress(0, 100, prefix='Progress:',
suffix='Starting, addr 0x%08X' % addr, bar_length=50)
length = dwords * 4
old = 0
pos = 0
while dwords:
size = min(512 // 4, dwords)
data = b"".join(int.to_bytes(val, 4, 'little') for val in mtk.preloader.read32(addr + pos, size))
sdata += data
if filename != "":
wf.write(data)
pos += len(data)
prog = pos / length * 100
if round(prog, 1) > old:
print_progress(prog, 100, prefix='Progress:',
suffix='Complete, addr 0x%08X' % (addr + pos), bar_length=50)
old = round(prog, 1)
dwords = (length - pos) // 4
print_progress(100, 100, prefix='Progress:',
suffix='Finished', bar_length=50)
if filename == "":
print(hexlify(sdata).decode('utf-8'))
else:
wf.close()
self.info(f"Data from {hex(addr)} with size of {hex(length)} was written to " + filename)
self.close()
elif cmd == "stage":
if self.args.filename is None:
pc = pathconfig()
stage1file = os.path.join(pc.get_payloads_path(), "generic_stage1_payload.bin")
else:
stage1file = self.args.filename
if not os.path.exists(stage1file):
self.error(f"Error: {stage1file} doesn't exist !")
return False
if self.args.stage2addr is None:
stage2addr = None
else:
stage2addr = getint(self.args.stage2addr)
if self.args.stage2 is None:
stage2file = os.path.join(mtk.pathconfig.get_payloads_path(), "stage2.bin")
else:
stage2file = self.args.stage2
if not os.path.exists(stage2file):
self.error(f"Error: {stage2file} doesn't exist !")
return False
verifystage2 = self.args.verifystage2
if mtk.preloader.init():
mtk = mtk.crasher()
if mtk.port.cdc.pid == 0x0003:
plt = PLTools(mtk, self.__logger.level)
self.info("Uploading stage 1")
if plt.runpayload(filename=stage1file):
self.info("Successfully uploaded stage 1, sending stage 2")
with open(stage2file, "rb") as rr:
stage2data = rr.read()
while len(stage2data) % 0x200:
stage2data += b"\x00"
if stage2addr is None:
stage2addr = mtk.config.chipconfig.da_payload_addr
if stage2addr is None:
stage2addr = 0x201000
# ###### Send stage2
# magic
mtk.port.usbwrite(pack(">I", 0xf00dd00d))
# cmd write
mtk.port.usbwrite(pack(">I", 0x4000))
# address
mtk.port.usbwrite(pack(">I", stage2addr))
# length
mtk.port.usbwrite(pack(">I", len(stage2data)))
bytestowrite = len(stage2data)
pos = 0
while bytestowrite > 0:
size = min(bytestowrite, 1)
if mtk.port.usbwrite(stage2data[pos:pos + size]):
bytestowrite -= size
pos += size
# mtk.port.usbwrite(b"")
time.sleep(0.1)
flag = mtk.port.rdword()
if flag != 0xD0D0D0D0:
self.error(f"Error on sending stage2, size {hex(len(stage2data))}.")
self.info(f"Done sending stage2, size {hex(len(stage2data))}.")
if verifystage2:
self.info("Verifying stage2 data")
rdata = b""
mtk.port.usbwrite(pack(">I", 0xf00dd00d))
mtk.port.usbwrite(pack(">I", 0x4002))
mtk.port.usbwrite(pack(">I", stage2addr))
mtk.port.usbwrite(pack(">I", len(stage2data)))
bytestoread = len(stage2data)
while bytestoread > 0:
size = min(bytestoread, 1)
rdata += mtk.port.usbread(size)
bytestoread -= size
flag = mtk.port.rdword()
if flag != 0xD0D0D0D0:
self.error("Error on reading stage2 data")
if rdata != stage2data:
self.error("Stage2 data doesn't match")
with open("rdata", "wb") as wf:
wf.write(rdata)
else:
self.info("Stage2 verification passed.")
# ####### Kick Watchdog
# magic
# mtk.port.usbwrite(pack("<I", 0xf00dd00d))
# cmd kick_watchdog
# mtk.port.usbwrite(pack("<I", 0x3001))
# ######### Jump stage1
# magic
mtk.port.usbwrite(pack(">I", 0xf00dd00d))
# cmd jump
mtk.port.usbwrite(pack(">I", 0x4001))
# address
mtk.port.usbwrite(pack(">I", stage2addr))
self.info("Done jumping stage2 at %08X" % stage2addr)
ack = unpack(">I", mtk.port.usbread(4))[0]
if ack == 0xB1B2B3B4:
self.info("Successfully loaded stage2")
self.close()
else:
mtk.port.close()
return False
elif cmd == "payload":
if mtk.preloader.init():
mtk = mtk.crasher()
plt = PLTools(mtk, self.__logger.level)
payloadfile = self.args.payload
if payloadfile is None:
if mtk.config.chipconfig.loader is None:
payloadfile = os.path.join(mtk.pathconfig.get_payloads_path(), "generic_patcher_payload.bin")
else:
payloadfile = os.path.join(mtk.pathconfig.get_payloads_path(), mtk.config.chipconfig.loader)
ptype = ""
if self.args.ptype is not None:
ptype = self.args.ptype
plt.runpayload(filename=payloadfile)
mtk.port.close(reset=True)
self.close()
elif cmd == "gettargetconfig":
if mtk.preloader.init():
self.info("Getting target info...")
mtk.preloader.get_target_config()
mtk.port.close()
self.close()
else:
# DA / FLash commands start here
mtk.port.cdc.connected=mtk.port.cdc.connect()
if mtk.port.cdc.connected and os.path.exists(".state"):
info=mtk.daloader.reinit()
else:
if os.path.exists("logs"):
try:
shutil.rmtree("logs", ignore_errors=True, onerror=None)
os.mkdir("logs")
except:
pass
try:
preloader = self.args.preloader
except:
preloader = None
if mtk.preloader.init():
if mtk.config.target_config["daa"]:
mtk = mtk.bypass_security()
self.info("Device is protected.")
if mtk is not None:
if mtk.config.is_brom:
self.info("Device is in BROM mode. Trying to dump preloader.")
if preloader is None:
preloader = self.dump_preloader_ram(mtk)
else:
self.info("Device is unprotected.")
if mtk.config.is_brom:
mtk = mtk.bypass_security() # Needed for dumping preloader
if preloader is None:
self.warning("Device is in BROM mode. No preloader given, trying to dump preloader from ram.")
preloader = self.dump_preloader_ram(mtk)
if preloader is None:
self.error("Failed to dump preloader from ram.")
if not mtk.daloader.upload_da(preloader=preloader):
self.error("Error uploading da")
return False
else:
mtk.daloader.writestate()
else:
return False
if cmd == "gpt":
directory = self.args.directory
if directory is None:
directory = ""
sfilename = os.path.join(directory, f"gpt_main.bin")
data, guid_gpt = mtk.daloader.get_gpt(self.args)
if guid_gpt is None:
self.error("Error reading gpt")
self.close()
else:
with open(sfilename, "wb") as wf:
wf.write(data)
print(f"Dumped GPT from to {sfilename}")
sfilename = os.path.join(directory, f"gpt_backup.bin")
with open(sfilename, "wb") as wf:
wf.write(data[mtk.daloader.daconfig.pagesize:])
print(f"Dumped Backup GPT to {sfilename}")
self.close()
elif cmd == "printgpt":
data, guid_gpt = mtk.daloader.get_gpt(self.args)
if guid_gpt is None:
self.error("Error reading gpt")
else:
guid_gpt.print()
self.close()
elif cmd == "r":
partitionname = self.args.partitionname
parttype = self.args.parttype
filename = self.args.filename
filenames = filename.split(",")
partitions = partitionname.split(",")
if len(partitions) != len(filenames):
self.error("You need to gives as many filenames as given partitions.")
self.close()
if parttype == "user" or parttype is None:
i = 0
self.info("Requesting available partitions ....")
gpttable = mtk.daloader.get_partition_data(self.args, parttype=parttype)
for partition in partitions:
partfilename = filenames[i]
i += 1
if partition == "gpt":
mtk.daloader.readflash(addr=0,
length=0x16000,
filename=partfilename, parttype=parttype)
continue
else:
rpartition = None
for gptentry in gpttable:
if gptentry.name.lower() == partition.lower():
rpartition = gptentry
break
if rpartition is not None:
self.info(f"Dumping partition \"{rpartition.name}\"")
if mtk.daloader.readflash(addr=rpartition.sector * mtk.daloader.daconfig.pagesize,
length=rpartition.sectors * mtk.daloader.daconfig.pagesize,
filename=partfilename, parttype=parttype):
self.info(f"Dumped sector {str(rpartition.sector)} with sector count " +
f"{str(rpartition.sectors)} as {partfilename}.")
else:
self.info(f"Failed to dump sector {str(rpartition.sector)} with sector count " +
f"{str(rpartition.sectors)} as {partfilename}.")
else:
self.error(f"Error: Couldn't detect partition: {partition}\nAvailable partitions:")
for rpartition in gpttable:
self.info(rpartition.name)
else:
i = 0
for partfilename in filenames:
pos = 0
if mtk.daloader.readflash(addr=pos, length=0xFFFFFFFF, filename=partfilename,
parttype=parttype):
print(f"Dumped partition {str(partitionname)} as {partfilename}.")
else:
print(f"Failed to dump partition {str(partitionname)} as {partfilename}.")
i += 1
self.close()
elif cmd == "rl":
directory = self.args.directory
parttype = self.args.parttype
if self.args.skip:
skip = self.args.skip.split(",")
else:
skip = []
if not os.path.exists(directory):
os.mkdir(directory)
data, guid_gpt = mtk.daloader.get_gpt(self.args, parttype=parttype)
if guid_gpt is None:
self.error("Error reading gpt")
else:
storedir = directory
if not os.path.exists(storedir):
os.mkdir(storedir)
sfilename = os.path.join(storedir, f"gpt_main.bin")
with open(sfilename, "wb") as wf:
wf.write(data)
sfilename = os.path.join(storedir, f"gpt_backup.bin")
with open(sfilename, "wb") as wf:
wf.write(data[mtk.daloader.daconfig.pagesize * 2:])
for partition in guid_gpt.partentries:
partitionname = partition.name
if partition.name in skip:
continue
filename = os.path.join(storedir, partitionname + ".bin")
self.info(
f"Dumping partition {str(partition.name)} with sector count {str(partition.sectors)} " +
f"as {filename}.")
mtk.daloader.readflash(addr=partition.sector * mtk.daloader.daconfig.pagesize,
length=partition.sectors * mtk.daloader.daconfig.pagesize,
filename=filename,
parttype=parttype)
self.close()
elif cmd == "rf":
filename = self.args.filename
parttype = self.args.parttype
if mtk.daloader.daconfig.flashtype == "ufs":
if parttype == "lu0":
length = mtk.daloader.daconfig.flashsize[0]
elif parttype == "lu1":
length = mtk.daloader.daconfig.flashsize[1]
elif parttype == "lu2":
length = mtk.daloader.daconfig.flashsize[2]
else:
length = mtk.daloader.daconfig.flashsize[0]
else:
length = mtk.daloader.daconfig.flashsize
print(f"Dumping sector 0 with flash size {hex(length)} as {filename}.")
if mtk.daloader.readflash(addr=0, length=length, filename=filename, parttype=parttype):
print(f"Dumped sector 0 with flash size {hex(length)} as {filename}.")
else:
print(f"Failed to dump sector 0 with flash size {hex(length)} as {filename}.")
self.close()
elif cmd == "rs":
start = getint(self.args.start_sector)
sectors = getint(self.args.sectors)
filename = self.args.filename
parttype = self.args.parttype
if mtk.daloader.readflash(addr=start * mtk.daloader.daconfig.pagesize,
length=sectors * mtk.daloader.daconfig.pagesize,
filename=filename, parttype=parttype):
print(f"Dumped sector {str(start)} with sector count {str(sectors)} as {filename}.")
else:
print(f"Failed to dump sector {str(start)} with sector count {str(sectors)} as {filename}.")
self.close()
elif cmd == "footer":
filename = self.args.filename
data, guid_gpt = mtk.daloader.get_gpt(self.args)
if guid_gpt is None:
self.error("Error reading gpt")
self.close()
else:
pnames = ["userdata2", "metadata", "userdata", "reserved1", "reserved2", "reserved3"]
for partition in guid_gpt.partentries:
if partition.name in pnames:
print(f"Detected partition: {partition.name}")
if partition.name in ["userdata2", "userdata"]:
data = mtk.daloader.readflash(
addr=(partition.sector + partition.sectors) *
mtk.daloader.daconfig.pagesize - 0x4000,
length=0x4000, filename="", parttype="user", display=False)
else:
data = mtk.daloader.readflash(addr=partition.sector * mtk.daloader.daconfig.pagesize,
length=0x4000, filename="", parttype="user",
display=False)
if data == b"":
continue
val = unpack("<I", data[:4])[0]
if (val & 0xFFFFFFF0) == 0xD0B5B1C0:
with open(filename, "wb") as wf:
wf.write(data)
print(f"Dumped footer from {partition.name} as {filename}.")
self.close()
return
self.error(f"Error: Couldn't detect footer partition.")
self.close()
elif cmd == "w":
partitionname = self.args.partitionname
filename = self.args.filename
parttype = self.args.parttype
filenames = filename.split(",")
partitions = partitionname.split(",")
if len(partitions) != len(filenames):
self.error("You need to gives as many filenames as given partitions.")
self.close()
exit(0)
if parttype == "user" or parttype is None:
i = 0
for partition in partitions:
partfilename = filenames[i]
i += 1
if partition == "gpt":
mtk.daloader.writeflash(addr=0,
length=os.stat(partfilename).st_size,
filename=partfilename,
parttype=parttype)
continue
res = mtk.daloader.detect_partition(self.args, partition, parttype)
if res[0]:
rpartition = res[1]
if mtk.daloader.writeflash(addr=rpartition.sector * mtk.daloader.daconfig.pagesize,
length=rpartition.sectors * mtk.daloader.daconfig.pagesize,
filename=partfilename,
parttype=parttype):
print(
f"Wrote {partfilename} to sector {str(rpartition.sector)} with " +
f"sector count {str(rpartition.sectors)}.")
else:
print(
f"Failed to write {partfilename} to sector {str(rpartition.sector)} with " +
f"sector count {str(rpartition.sectors)}.")
else:
self.error(f"Error: Couldn't detect partition: {partition}\nAvailable partitions:")
for rpartition in res[1]:
self.info(rpartition.name)
else:
pos = 0
for partfilename in filenames:
size = os.stat(partfilename).st_size
if mtk.daloader.writeflash(addr=pos, length=size, filename=partfilename,
partitionname=partitionname,
parttype=parttype):
print(f"Wrote {partfilename} to sector {str(pos // 0x200)} with " +
f"sector count {str(size)}.")
else:
print(f"Failed to write {partfilename} to sector {str(pos // 0x200)} with " +
f"sector count {str(size)}.")
psize = size // 0x200 * 0x200
if size % 0x200 != 0:
psize += 0x200
pos += psize
self.close()
elif cmd == "wl":
directory = self.args.directory
parttype = self.args.parttype
filenames = []
for dirName, subdirList, fileList in os.walk(directory):
for fname in fileList:
filenames.append(os.path.join(dirName, fname))
if parttype == "user" or parttype is None:
i = 0
for partfilename in filenames:
partition = os.path.basename(partfilename)
partition = os.path.splitext(partition)[0]
i += 1
if partition == "gpt":
self.info(f"Writing partition {partition}")
if mtk.daloader.writeflash(addr=0,
length=os.stat(partfilename).st_size,
filename=partfilename,
parttype=parttype):
print(f"Wrote {partition} to sector {str(0)}")
else:
print(f"Failed to write {partition} to sector {str(0)}")
continue
res = mtk.daloader.detect_partition(self.args, partition, parttype)
if res[0]:
rpartition = res[1]
if mtk.daloader.writeflash(addr=rpartition.sector * mtk.daloader.daconfig.pagesize,
length=rpartition.sectors * mtk.daloader.daconfig.pagesize,
filename=partfilename,
parttype=parttype):
print(
f"Wrote {partfilename} to sector {str(rpartition.sector)} with " +
f"sector count {str(rpartition.sectors)}.")
else:
print(
f"Failed to write {partfilename} to sector {str(rpartition.sector)} with " +
f"sector count {str(rpartition.sectors)}.")
else:
self.error(f"Error: Couldn't detect partition: {partition}\n, skipping")
else:
pos = 0
for partfilename in filenames:
size = os.stat(partfilename).st_size
partition = os.path.basename(partfilename)
partition = os.path.splitext(partition)[0]
self.info(f"Writing filename {partfilename}")
if mtk.daloader.writeflash(addr=pos, length=size, filename=partfilename,
partitionname=partition,
parttype=parttype):
print(f"Wrote {partfilename} to sector {str(pos // 0x200)} with " +
f"sector count {str(size)}.")
else:
print(f"Failed to write {partfilename} to sector {str(pos // 0x200)} with " +
f"sector count {str(size)}.")
psize = size // 0x200 * 0x200
if size % 0x200 != 0:
psize += 0x200
pos += psize
self.close()
elif cmd == "e":
partitionname = self.args.partitionname
parttype = self.args.parttype
partitions = partitionname.split(",")
if parttype == "user" or parttype is None:
i = 0
for partition in partitions:
i += 1
res = mtk.daloader.detect_partition(self.args, partition, parttype)
if res[0]:
rpartition = res[1]
if mtk.daloader.formatflash(addr=rpartition.sector * mtk.daloader.daconfig.pagesize,
length=rpartition.sectors * mtk.daloader.daconfig.pagesize,
partitionname=partition, parttype=parttype):
print(
f"Formatted sector {str(rpartition.sector)} with " +
f"sector count {str(rpartition.sectors)}.")
else:
print(
f"Failed to format sector {str(rpartition.sector)} with " +
f"sector count {str(rpartition.sectors)}.")
else:
self.error(f"Error: Couldn't detect partition: {partition}\nAvailable partitions:")
for rpartition in res[1]:
self.info(rpartition.name)
self.close()
elif cmd == "es":
partitionname = self.args.partitionname
parttype = self.args.parttype
sectors = getint(self.args.sectors)
if self.args.sectors is None:
self.error("Sector count is missing. Usage: es [partname] [sector count]")
self.close()
partitions = partitionname.split(",")
if parttype == "user" or parttype is None:
i = 0