-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathme_unpack.py
1501 lines (1390 loc) · 58 KB
/
me_unpack.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
#!/usr/bin/env python
# Intel ME ROM image dumper/extractor
# Copyright (c) 2012-2014 Igor Skochinsky
# Version 0.1 2012-10-10
# Version 0.2 2013-08-15
# Version 0.3 2014-10-06
#
# This software is provided 'as-is', without any express or implied
# warranty. In no event will the authors be held liable for any damages
# arising from the use of this software.
#
# Permission is granted to anyone to use this software for any purpose,
# including commercial applications, and to alter it and redistribute it
# freely, subject to the following restrictions:
#
# 1. The origin of this software must not be misrepresented; you must not
# claim that you wrote the original software. If you use this software
# in a product, an acknowledgment in the product documentation would be
# appreciated but is not required.
#
# 2. Altered source versions must be plainly marked as such, and must not be
# misrepresented as being the original software.
#
# 3. This notice may not be removed or altered from any source
# distribution.
import ctypes
import struct
import sys
import os
import array
uint8_t = ctypes.c_ubyte
char = ctypes.c_char
uint32_t = ctypes.c_uint
uint64_t = ctypes.c_uint64
uint16_t = ctypes.c_ushort
def replace_bad(value, deletechars):
for c in deletechars:
value = value.replace(c,'_')
return value
def read_struct(li, struct):
s = struct()
slen = ctypes.sizeof(s)
bytes = li.read(slen)
fit = min(len(bytes), slen)
ctypes.memmove(ctypes.addressof(s), bytes, fit)
return s
def get_struct(str_, off, struct):
s = struct()
slen = ctypes.sizeof(s)
bytes = str_[off:off+slen]
fit = min(len(bytes), slen)
if fit < slen:
raise Exception("can't read struct: %d bytes available but %d required" % (fit, slen))
ctypes.memmove(ctypes.addressof(s), bytes, fit)
return s
def DwordAt(f, off):
return struct.unpack("<I", f[off:off+4])[0]
def hexdump(s):
if isinstance(s, str):
s = map(ord, s)
return " ".join("%02X" % v for v in s)
class MeModuleHeader1(ctypes.LittleEndianStructure):
_fields_ = [
("Tag", char*4), # $MME
("Guid", uint8_t*16), #
("MajorVersion", uint16_t), #
("MinorVersion", uint16_t), #
("HotfixVersion", uint16_t), #
("BuildVersion", uint16_t), #
("Name", char*16), #
("Hash", uint8_t*20), #
("Size", uint32_t), #
("Flags", uint32_t), #
("Unk48", uint32_t), #
("Unk4C", uint32_t), #
]
def __init__(self):
self.Offset = None
def comptype(self):
return COMP_TYPE_NOT_COMPRESSED
def print_flags(self):
print " Disable Hash: %d" % ((self.Flags>>0)&1)
print " Optional: %d" % ((self.Flags>>1)&1)
if self.Flags >> 2:
print " Unknown B2_31: %d" % ((self.Flags>>2))
def pprint(self):
print "Header tag: %s" % (self.Tag)
nm = self.Name.rstrip('\0')
print "Module name: %s" % (nm)
print "Guid: %s" % (hexdump(self.Guid))
print "Version: %d.%d.%d.%d" % (self.MajorVersion, self.MinorVersion, self.HotfixVersion, self.BuildVersion)
print "Hash: %s" % (hexdump(self.Hash))
print "Size: 0x%08X" % (self.Size)
if self.Offset != None:
print "(Offset): 0x%08X" % (self.Offset)
print "Flags: 0x%08X" % (self.Flags)
self.print_flags()
print "Unk48: 0x%08X" % (self.Unk48)
print "Unk4C: 0x%08X" % (self.Unk4C)
def print_map(self):
nm = self.Name.rstrip('\0').ljust(16, ' ')
base = self.ModBase
codestart = base
codeend = base + self.CodeSize
dataend = base + self.MemorySize
curoff = base
if codestart:
if curoff < codestart:
print "%08X %08X %s GAP" % (curoff, codestart, nm)
curoff = codestart
print "%08X %08X %s CODE" % (curoff, codeend, nm)
curoff = codeend
if curoff < dataend:
print "%08X %08X %s DATA" % (curoff, dataend, nm)
curoff = dataend
if curoff & 0xFFF:
gapend = (curoff + 0xFFF) & ~0xFFF
print "%08X %08X %s GAP" % (curoff, gapend, nm)
curoff = gapend
class MeModuleFileHeader1(ctypes.LittleEndianStructure):
_fields_ = [
("Tag", char*4), # $MOD
("Unk04", uint32_t), #
("Unk08", uint32_t), #
("MajorVersion", uint16_t), #
("MinorVersion", uint16_t), #
("HotfixVersion", uint16_t), #
("BuildVersion", uint16_t), #
("Unk14", uint32_t), #
("CompressedSize", uint32_t), #
("UncompressedSize", uint32_t), #
("LoadAddress", uint32_t), #
("MappedSize", uint32_t), #
("EntryRVA", uint32_t), #
("Unk2C", uint32_t), #
("Name", char*16), #
("Guid", uint8_t*16), #
]
def pprint(self):
print "Module tag: %s" % (self.Tag)
nm = self.Name.rstrip('\0')
print "Module name: %s" % (nm)
print "Guid: %s" % (hexdump(self.Guid))
print "Version: %d.%d.%d.%d" % (self.MajorVersion, self.MinorVersion, self.HotfixVersion, self.BuildVersion)
print "Unk04: 0x%08X" % (self.Unk04)
print "Unk08: 0x%08X" % (self.Unk08)
print "Unk14: 0x%08X" % (self.Unk14)
print "Compressed size: 0x%08X" % (self.CompressedSize)
print "Uncompressed size: 0x%08X" % (self.UncompressedSize)
print "Mapped address: 0x%08X" % (self.LoadAddress)
print "Mapped size: 0x%08X" % (self.MappedSize)
print "Entrypoint RVA: 0x%08X (VA=%08X)" % (self.EntryRVA, self.EntryRVA+self.LoadAddress)
print "Unk2C: 0x%08X" % (self.Unk2C)
MeModulePowerTypes = ["POWER_TYPE_RESERVED", "POWER_TYPE_M0_ONLY", "POWER_TYPE_M3_ONLY", "POWER_TYPE_LIVE"]
MeCompressionTypes = ["COMP_TYPE_NOT_COMPRESSED", "COMP_TYPE_HUFFMAN", "COMP_TYPE_LZMA", "<unknown>"]
COMP_TYPE_NOT_COMPRESSED = 0
COMP_TYPE_HUFFMAN = 1
COMP_TYPE_LZMA = 2
MeModuleTypes = ["DEFAULT", "PRE_ME_KERNEL", "VENOM_TPM", "APPS_QST_DT", "APPS_AMT", "TEST"]
MeApiTypes = ["API_TYPE_DATA", "API_TYPE_ROMAPI", "API_TYPE_KERNEL", "<unknown>"]
class MeModuleHeader2(ctypes.LittleEndianStructure):
_fields_ = [
("Tag", char*4), # $MME
("Name", char*16), # 4
("Hash", uint8_t*32), # 0x14
("ModBase", uint32_t), # 0x34
("Offset", uint32_t), # 0x38 From the start of manifest
("CodeSize", uint32_t), # 0x3C
("Size", uint32_t), # 0x40
("MemorySize", uint32_t), # 0x44
("PreUmaSize", uint32_t), # 0x48
("EntryPoint", uint32_t), # 0x4C
("Flags", uint32_t), # 0x50
("Unk54", uint32_t), #
("Unk58", uint32_t), #
("Unk5C", uint32_t), #
]
def comptype(self):
return (self.Flags>>4)&7
def print_flags(self):
print " LoadState: %d" % ((self.Flags>>0)&1)
powtype = (self.Flags>>1)&3
print " Power Type: %s (%d)" % (MeModulePowerTypes[powtype], powtype)
print " UMA Dependency: %d" % ((self.Flags>>3)&1)
comptype = (self.Flags>>4)&7
print " Compression: %s (%d)" % (MeCompressionTypes[comptype], comptype)
modstage = (self.Flags>>7)&0xF
if modstage < len(MeModuleTypes):
smtype = MeModuleTypes[modstage]
else:
smtype = "STAGE %X" % modstage
print " Load Stage: %s (%d)" % (smtype, modstage)
apitype = (self.Flags>>11)&7
print " API Type: %s (%d)" % (MeApiTypes[apitype], apitype)
print " Load: %d" % ((self.Flags>>14)&1)
print " Initialize: %d" % ((self.Flags>>15)&1)
print " Privileged: %d" % ((self.Flags>>16)&1)
print " Alias1 Pages (RAPI): %d" % ((self.Flags>>17)&7)
print " Alias2 Pages (KAPI): %d" % ((self.Flags>>20)&3)
print " Pre-UMA Load: %d" % ((self.Flags>>22)&1)
if self.Flags >> 23:
print " Unknown B23_31: %d" % ((self.Flags>>23))
def pprint(self):
print "Header tag: %s" % (self.Tag)
nm = self.Name.rstrip('\0')
print "Module name: %s" % (nm)
print "Hash: %s" % (hexdump(self.Hash))
print "Module base: 0x%08X" % (self.ModBase)
print "Offset: 0x%08X" % (self.Offset)
print "Code size: 0x%08X" % (self.CodeSize)
print "Data length: 0x%08X" % (self.Size)
print "Memory size: 0x%08X" % (self.MemorySize)
print "Pre-UMA size: 0x%08X" % (self.PreUmaSize)
print "Entry point: 0x%08X" % (self.EntryPoint)
print "Flags: 0x%08X" % (self.Flags)
self.print_flags()
print "Unk54: 0x%08X" % (self.Unk54)
print "Unk58: 0x%08X" % (self.Unk58)
print "Unk5C: 0x%08X" % (self.Unk5C)
def print_map(self):
nm = self.Name.rstrip('\0').ljust(16, ' ')
base = self.ModBase
rapi1 = ((self.Flags>>17)&7)
rapi2 = ((self.Flags>>20)&3)
codestart = base + (rapi1+rapi2) * 0x1000
codeend = base + self.CodeSize
dataend = base + self.MemorySize
curoff = base
if rapi1:
rapi1end = curoff + rapi1 * 0x1000
print "%08X %08X %s RAPI" % (curoff, rapi1end, nm)
curoff = rapi1end
if rapi2:
rapi2end = curoff + rapi2 * 0x1000
print "%08X %08X %s KAPI" % (curoff, rapi2end, nm)
curoff = rapi2end
if self.PreUmaSize == 0:
codestart = base
if codestart:
if curoff < codestart:
print "%08X %08X %s GAP" % (curoff, codestart, nm)
curoff = codestart
print "%08X %08X %s CODE" % (curoff, codeend, nm)
curoff = codeend
if curoff < dataend:
print "%08X %08X %s DATA" % (curoff, dataend, nm)
curoff = dataend
if curoff & 0xFFF:
gapend = (curoff + 0xFFF) & ~0xFFF
print "%08X %08X %s GAP" % (curoff, gapend, nm)
curoff = gapend
def extract_code_mods(nm, f, soff):
try:
os.mkdir(nm)
except:
pass
os.chdir(nm)
print " extracting CODE partition %s" % (nm)
if f[soff:soff+4]=='$CPD':
s= CPDHeader
else:
s= MeManifestHeader
manif = get_struct(f, soff, s)
manif.parse_mods(f, soff)
manif.pprint()
manif.extract(f, soff)
os.chdir("..")
def decomp_lzma(compdata):
if os.name == "posix":
import subprocess
elif os.name == "nt":
import subprocess, _subprocess
else:
import subprocess, _subprocess
if os.name == "nt":
# hide the console window
si = subprocess.STARTUPINFO()
si.dwFlags |= _subprocess.STARTF_USESHOWWINDOW
if in_ida:
basedir = idaapi.idadir("loaders")
else:
basedir = os.path.dirname(__file__)
path = os.path.join(basedir, "lzma")
print "using decompressor at '%s'" % path
try:
process = subprocess.Popen([path, "d", "-si", "-so"], startupinfo=si, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, errout = process.communicate(compdata)
retcode = process.poll()
except IOError as e:
print "error %d running lzma!\nstderr output:\n%s" % (e.errno, errout)
return None
except OSError as e:
print "Error running lzma.exe (error %d: %s)" % (e.errno, e.strerror)
return None
except:
print "Error running lzma.exe"
return None
if retcode:
return None
return output
class MeManifestHeader(ctypes.LittleEndianStructure):
_fields_ = [
("ModuleType", uint16_t), # 00
("ModuleSubType", uint16_t), # 02
("HeaderLen", uint32_t), # 04 in dwords
("HeaderVersion", uint32_t), # 08
("Flags", uint32_t), # 0C 0x80000000 = Debug
("ModuleVendor", uint32_t), # 10
("Date", uint32_t), # 14 BCD yyyy.mm.dd
("Size", uint32_t), # 18 in dwords
("Tag", char*4), # 1C $MAN or $MN2
("NumModules", uint32_t), # 20
("MajorVersion", uint16_t), # 24
("MinorVersion", uint16_t), # 26
("HotfixVersion", uint16_t), # 28
("BuildVersion", uint16_t), # 2A
("Unknown1", uint32_t*19), # 2C
("KeySize", uint32_t), # 78
("ScratchSize", uint32_t), # 7C
("RsaPubKey", uint32_t*64), # 80
("RsaPubExp", uint32_t), # 180
("RsaSig", uint32_t*64), # 184
("PartitionName", char*12), # 284
# 290
]
def parse_mods(self, f, offset):
self.modules = []
self.updparts = []
orig_off = offset
offset += self.HeaderLen*4
offset += 12
if self.Tag == '$MN2':
self.cpu = "ARCompact"
htype = MeModuleHeader2
hdrlen = ctypes.sizeof(htype)
if self.NumModules > 1:
# check for TXE
if f[offset+hdrlen:offset+hdrlen+4] != '$MME':
hdrlen = 0x80
if f[offset+hdrlen:offset+hdrlen+4] == '$MME':
print "TXE firmware detected"
self.cpu = "SPARC"
else:
raise Exception("Could not determine module header length!")
udc_fmt = "<4s32s16sII"
udc_len = 0x3C
elif self.Tag == '$MAN':
self.cpu = "ARC"
htype = MeModuleHeader1
hdrlen = ctypes.sizeof(htype)
udc_fmt = "<4s20s16sII"
udc_len = 0x30
else:
print ("Don't know how to parse modules for manifest tag %s!" % self.Tag)
self.huff_start =0
self.huff_end =0
return
raise Exception("Don't know how to parse modules for manifest tag %s!" % self.Tag)
modmap = {}
self.huff_start = 0
for i in range(self.NumModules):
mod = get_struct(f, offset, htype)
if not mod.Tag in ['$MME', '$MDL']:
raise Exception("Bad module tag (%s) at offset %08X!" % (mod.Tag, offset))
nm = mod.Name.rstrip('\0')
modmap[nm] = mod
self.modules.append(mod)
if mod.comptype() == COMP_TYPE_HUFFMAN:
if self.huff_start and self.huff_start != mod.Offset:
print "Warning: inconsistent start offset for Huffman modules!"
self.huff_start = mod.Offset
offset += hdrlen
self.partition_end = None
hdr_end = orig_off + self.Size*4
while offset < hdr_end:
# print "tags %08X" % offset
hdr = f[offset:offset+8]
if hdr == '\xFF' * 8:
offset += hdrlen
continue
if len(hdr) < 8 or hdr[0] != '$':
break
tag, elen = hdr[:4], struct.unpack("<I", hdr[4:])[0]
if elen == 0:
break
print "Tag: %s, data length: %08X (0x%08X bytes)" % (tag, elen, elen*4)
if tag == '$UDC':
subtag, hash, subname, suboff, size = struct.unpack(udc_fmt, f[offset+8:offset+8+udc_len])
suboff += offset
print "Update code part: %s, %s, offset %08X, size %08X" % (subtag, subname.rstrip('\0'), suboff, size)
self.updparts.append((subtag, suboff, size))
elif tag == '$GLT':
suboff, size = struct.unpack("<II", f[offset+8:offset+16])
print "GLUT part: offset +%08X, size %08X" % (suboff, size)
self.updparts.append(('GLUT', offset+suboff, size))
elif elen == 3:
val = struct.unpack("<I", f[offset+8:offset+12])[0]
print "%s: %08X" % (tag[1:], val)
elif elen == 4:
vals = struct.unpack("<II", f[offset+8:offset+16])
print "%s: %08X %08X" % (tag[1:], vals[0], vals[1])
else:
vals = array.array("I", f[offset+8:offset+elen*4])
print "%s: %s" % (tag[1:], " ".join("%08X" % v for v in vals))
if tag == '$MCP':
self.partition_end = vals[0] + vals[1]
offset += elen*4
offset = hdr_end
while True:
print "mods %08X" % offset
if f[offset:offset+4] != '$MOD':
break
mfhdr = get_struct(f, offset, MeModuleFileHeader1)
mfhdr.pprint()
nm = mfhdr.Name.rstrip('\0')
mod = modmap[nm]
# copy some fields needed by other code
mod.Offset = offset - orig_off
mod.UncompressedSize = mfhdr.UncompressedSize
mod.ModBase = mfhdr.LoadAddress
mod.CodeSize = mfhdr.UncompressedSize
mod.MemorySize = mfhdr.MappedSize
mod.PreUmaSize = mod.MemorySize
mod.EntryPoint = mod.ModBase + mfhdr.EntryRVA
offset += mod.Size
# check for huffman LUT
offset = self.huff_start
if f[offset+1:offset+4] == 'LUT':
cnt, unk8, unkc, complen = struct.unpack("<IIII", f[offset+4:offset+20])
self.huff_end = offset + 0x40 + 4*cnt + complen
else:
self.huff_start = 0xFFFFFFFF
self.huff_end = 0xFFFFFFFF
def print_mods(self):
pname = self.PartitionName.rstrip('\0')
print "------%s------" % pname
for i, mod in enumerate(self.modules):
if i: print "--"
mod.print_map()
print "------End-------\n"
for subtag, soff, subsize in self.updparts:
if subtag != 'GLUT':
manif = get_struct(f, soff, MeManifestHeader)
manif.parse_mods(f, soff)
manif.print_mods()
def _get_mod_data(self, f, offset, imod):
huff_end = self.huff_end
nhuffs = 0
for mod in self.modules:
if mod.comptype() != COMP_TYPE_HUFFMAN:
huff_end = min(huff_end, mod.Offset)
else:
nhuffs += 1
mod = self.modules[imod]
nm = mod.Name.rstrip('\0')
islast = (imod == len(self.modules)-1)
if mod.Offset in [0xFFFFFFFF, 0] or (mod.Size in [0xFFFFFFFF, 0] and not islast and mod.comptype() != COMP_TYPE_HUFFMAN):
return None
else:
soff = offset + mod.Offset
size = mod.Size
data = f[soff:soff+size]
if mod.comptype() == COMP_TYPE_LZMA:
ext = "lzma"
if data.startswith("\x36\x00\x40\x00\x00") and data[0xE:0x11] == '\x00\x00\x00':
# delete the extra zeroes so the stream can be decompressed
data = data[:0xE] + data[0x11:]
ud = decomp_lzma(data)
if ud:
data = ud
ext = "bin"
elif mod.comptype() == COMP_TYPE_HUFFMAN:
ext = "huff"
if nhuffs != 1:
nm = self.PartitionName
size = huff_end - mod.Offset
else:
ext = "bin"
if self.Tag == '$MAN':
ext = "mod"
moff = soff+0x50
if f[moff:moff+5] == '\x5D\x00\x00\x80\x00':
data = f[moff:moff+5] + struct.pack("<Q", mod.UncompressedSize) + f[moff+5:moff+mod.Size-0x50]
# file("%s_comp.lzma" % nm, "wb").write(data)
ud = decomp_lzma(data)
if ud:
data = f[soff:soff+0x50] + ud
ext = "bin"
return (data, ext)
def extract(self, f, offset):
huff_end = self.huff_end
nhuffs = 0
for mod in self.modules:
if mod.comptype() != COMP_TYPE_HUFFMAN:
huff_end = min(huff_end, mod.Offset)
else:
print "Huffman module: %r %08X/%08X" % (mod.Name.rstrip('\0'), mod.ModBase, mod.CodeSize)
nhuffs += 1
for imod, mod in enumerate(self.modules):
mod = self.modules[imod]
nm = mod.Name.rstrip('\0')
islast = (imod == len(self.modules)-1)
# print "Module: %r %08X/%08X" % (nm, mod.ModBase, mod.CodeSize),
print "Module: %r" % (nm),
r = self._get_mod_data(f, offset, imod)
if r:
data, ext = r
if ext == "huff" and nhuffs != 1:
nm = self.PartitionName
if ext!= "bin":
fname = "%s_mod.%s" % (nm, ext)
else:
fname = nm
print " => %s" % (fname)
open(fname, "wb").write(data)
for subtag, soff, subsize in self.updparts:
fname = "%s_udc.bin" % subtag
print "Update part: %r %08X/%08X" % (subtag, soff, subsize),
print " => %s" % (fname)
open(fname, "wb").write(f[soff:soff+subsize])
if subtag != 'GLUT':
extract_code_mods(subtag, f, soff)
def pprint(self):
print "Module Type: %d, Subtype: %d" % (self.ModuleType, self.ModuleSubType)
print "Header Length: 0x%02X (0x%X bytes)" % (self.HeaderLen, self.HeaderLen*4)
print "Header Version: %d.%d" % (self.HeaderVersion>>16, self.HeaderVersion&0xFFFF)
print "Flags: 0x%08X" % (self.Flags),
print " [%s signed] [%s flag]" % (["production","debug"][(self.Flags>>31)&1], ["production","pre-production"][(self.Flags>>30)&1])
print "Module Vendor: 0x%04X" % (self.ModuleVendor)
print "Date: %08X" % (self.Date)
print "Total Manifest Size: 0x%02X (0x%X bytes)" % (self.Size, self.Size*4)
print "Tag: %s" % (self.Tag)
print "Number of modules: %d" % (self.NumModules)
print "Version: %d.%d.%d.%d" % (self.MajorVersion, self.MinorVersion, self.HotfixVersion, self.BuildVersion)
print "Unknown data 1: %s" % ([n for n in self.Unknown1])
print "Key size: 0x%02X (0x%X bytes)" % (self.KeySize, self.KeySize*4)
print "Scratch size: 0x%02X (0x%X bytes)" % (self.ScratchSize, self.ScratchSize*4)
print "RSA Public Key: [skipped]"
print "RSA Public Exponent: %d" % (self.RsaPubExp)
print "RSA Signature: [skipped]"
pname = self.PartitionName.rstrip('\0')
if not pname:
pname = "(none)"
print "Partition name: %s" % (pname)
print "---Modules---"
for mod in self.modules:
mod.pprint()
print
print "------End-------"
class CPDEntry(ctypes.LittleEndianStructure):
_fields_ = [
("Name", char*12), # 00
("Offset", uint32_t), # 04
("Size", uint32_t), # 08
("Flags", uint32_t), #0C
# 10
]
def comptype(self):
nm = self.Name.rstrip('\0')
typ = self.Offset>>24
self.ModBase =0
self.CodeSize =0
if nm[-4:-3]=='.': return COMP_TYPE_NOT_COMPRESSED
if typ==2: return COMP_TYPE_HUFFMAN
elif typ==0: return COMP_TYPE_LZMA
else: return COMP_TYPE_NOT_COMPRESSED
def pprint(self):
nm = self.Name.rstrip('\0')
print "Module name: %s" % (nm)
typ = self.Offset>>28
print "Offset: %08X" % (self.Offset & 0xFFFFFF)
print "Compress flag: %08X" % ((self.Offset >>25) &1)
print "Size: %08X" % (self.Size)
print "comp type:%d" %self.comptype()
print "Flags: %08X"% (self.Flags)
class CPDHeader(ctypes.LittleEndianStructure):
_fields_ = [
("Tag", char*4), # 00 $CPD
("NumModules", uint32_t), # 04
("HeaderVersion",uint8_t), # 08
("EntryVersion", uint8_t), # 09
("HeaderLength", uint8_t), # 0A
("Checksum", uint8_t), # 0B
("PartitionName", char*4), #0C
# 10
]
def parse_mods(self, f, offset):
self.modules = []
self.updparts = []
orig_off = offset
offset += 0x10
if self.Tag == '$MN2':
self.cpu = "ARCompact"
htype = MeModuleHeader2
hdrlen = ctypes.sizeof(htype)
udc_fmt = "<4s32s16sII"
udc_len = 0x3C
elif self.Tag == '$MAN':
self.cpu = "ARC"
htype = MeModuleHeader1
hdrlen = ctypes.sizeof(htype)
udc_fmt = "<4s20s16sII"
udc_len = 0x30
elif self.Tag == '$CPD':
self.cpu = "metapc"
htype = CPDEntry
hdrlen = ctypes.sizeof(htype)
udc_fmt = "<4s20s16sII"
udc_len = 0x30
else:
print ("Don't know how to parse modules for manifest tag %r!" % self.Tag)
self.huff_start =0
self.huff_end =0
return
raise Exception("Don't know how to parse modules for manifest tag %s!" % self.Tag)
modmap = {}
self.huff_start = 0
for i in range(self.NumModules):
mod = get_struct(f, offset, htype)
nm = mod.Name.rstrip('\0')
modmap[nm] = mod
self.modules.append(mod)
if mod.comptype() == COMP_TYPE_HUFFMAN:
if self.huff_start and self.huff_start != mod.Offset:
print "Warning: inconsistent start offset for Huffman modules!"
self.huff_start = mod.Offset
offset += hdrlen
self.partition_end = None
hdr_end = offset
while offset < hdr_end:
# print "tags %08X" % offset
hdr = f[offset:offset+8]
if hdr == '\xFF' * 8:
offset += hdrlen
continue
if len(hdr) < 8 or hdr[0] != '$':
break
tag, elen = hdr[:4], struct.unpack("<I", hdr[4:])[0]
if elen == 0:
break
print "Tag: %s, data length: %08X (0x%08X bytes)" % (tag, elen, elen*4)
if tag == '$UDC':
subtag, hash, subname, suboff, size = struct.unpack(udc_fmt, f[offset+8:offset+8+udc_len])
suboff += offset
print "Update code part: %s, %s, offset %08X, size %08X" % (subtag, subname.rstrip('\0'), suboff, size)
self.updparts.append((subtag, suboff, size))
elif tag == '$GLT':
suboff, size = struct.unpack("<II", f[offset+8:offset+16])
print "GLUT part: offset +%08X, size %08X" % (suboff, size)
self.updparts.append(('GLUT', offset+suboff, size))
elif elen == 3:
val = struct.unpack("<I", f[offset+8:offset+12])[0]
print "%s: %08X" % (tag[1:], val)
elif elen == 4:
vals = struct.unpack("<II", f[offset+8:offset+16])
print "%s: %08X %08X" % (tag[1:], vals[0], vals[1])
else:
vals = array.array("I", f[offset+8:offset+elen*4])
print "%s: %s" % (tag[1:], " ".join("%08X" % v for v in vals))
if tag == '$MCP':
self.partition_end = vals[0] + vals[1]
offset += elen*4
offset = hdr_end
while True:
print "mods %08X" % offset
if f[offset:offset+4] != '$MOD':
break
mfhdr = get_struct(f, offset, MeModuleFileHeader1)
mfhdr.pprint()
nm = mfhdr.Name.rstrip('\0')
mod = modmap[nm]
# copy some fields needed by other code
mod.Offset = offset - orig_off
mod.UncompressedSize = mfhdr.UncompressedSize
mod.ModBase = mfhdr.LoadAddress
mod.CodeSize = mfhdr.UncompressedSize
mod.MemorySize = mfhdr.MappedSize
mod.PreUmaSize = mod.MemorySize
mod.EntryPoint = mod.ModBase + mfhdr.EntryRVA
offset += mod.Size
# check for huffman LUT
offset = self.huff_start
if f[offset+1:offset+4] == 'LUT':
cnt, unk8, unkc, complen = struct.unpack("<IIII", f[offset+4:offset+20])
self.huff_end = offset + 0x40 + 4*cnt + complen
else:
self.huff_start = 0xFFFFFFFF
self.huff_end = 0xFFFFFFFF
def print_mods(self):
pname = self.PartitionName.rstrip('\0')
print "------%s------" % pname
for i, mod in enumerate(self.modules):
if i: print "--"
mod.print_map()
print "------End-------\n"
for subtag, soff, subsize in self.updparts:
if subtag != 'GLUT':
manif = get_struct(f, soff, MeManifestHeader)
manif.parse_mods(f, soff)
manif.print_mods()
def _get_mod_data(self, f, offset, imod):
huff_end = self.huff_end
nhuffs = 0
for mod in self.modules:
if mod.comptype() != COMP_TYPE_HUFFMAN:
huff_end = min(huff_end, mod.Offset)
else:
nhuffs += 1
mod = self.modules[imod]
nm = mod.Name.rstrip('\0')
islast = (imod == len(self.modules)-1)
if mod.Offset in [0xFFFFFFFF, 0] or (mod.Size in [0xFFFFFFFF, 0] and not islast and mod.comptype() != COMP_TYPE_HUFFMAN):
return None
else:
if self.Tag == '$CPD':
soff = offset + mod.Offset & 0xFFFFFF
else:
soff = offset + mod.Offset
size = mod.Size
data = f[soff:soff+size]
if mod.comptype() == COMP_TYPE_LZMA and nm[-4:-3] !='.':
ext = "lzma"
if data.startswith("\x36\x00\x40\x00\x00") and data[0xE:0x11] == '\x00\x00\x00':
# delete the extra zeroes so the stream can be decompressed
data = data[:0xE] + data[0x11:]
ud = decomp_lzma(data)
if ud:
data = ud
ext = "bin"
elif mod.comptype() == COMP_TYPE_HUFFMAN:
ext = "huff"
if nhuffs != 1:
nm = self.PartitionName
size = huff_end - mod.Offset
else:
ext = "bin"
if self.Tag == '$MAN':
ext = "mod"
moff = soff+0x50
if f[moff:moff+5] == '\x5D\x00\x00\x80\x00':
data = f[moff:moff+5] + struct.pack("<Q", mod.UncompressedSize) + f[moff+5:moff+mod.Size-0x50]
# file("%s_comp.lzma" % nm, "wb").write(data)
ud = decomp_lzma(data)
if ud:
data = f[soff:soff+0x50] + ud
ext = "bin"
return (data, ext)
def extract(self, f, offset):
huff_end = self.huff_end
nhuffs = 0
for mod in self.modules:
if mod.comptype() != COMP_TYPE_HUFFMAN:
huff_end = min(huff_end, mod.Offset)
else:
print "Huffman module: %r %08X/%08X" % (mod.Name.rstrip('\0'), mod.ModBase, mod.CodeSize)
nhuffs += 1
for imod, mod in enumerate(self.modules):
mod = self.modules[imod]
nm = mod.Name.rstrip('\0')
islast = (imod == len(self.modules)-1)
# print "Module: %r %08X/%08X" % (nm, mod.ModBase, mod.CodeSize),
print "Module: %r" % (nm),
r = self._get_mod_data(f, offset, imod)
if r:
data, ext = r
if ext == "huff" and nhuffs != 1:
nm = self.PartitionName
if ext != "bin":
fname = "%s_mod.%s" % (nm, ext)
else:
fname = nm
print " => %s" % (fname)
open(fname, "wb").write(data)
for subtag, soff, subsize in self.updparts:
fname = "%s_udc.bin" % subtag
print "Update part: %r %08X/%08X" % (subtag, soff, subsize),
print " => %s" % (fname)
open(fname, "wb").write(f[soff:soff+subsize])
if subtag != 'GLUT':
extract_code_mods(subtag, f, soff)
def pprint(self):
print "Tag: %s" % (self.Tag)
print "Number of modules: %d" % (self.NumModules)
print "Header Version: %0X" % (self.HeaderVersion)
print "Entry Version: %02X" % (self.EntryVersion)
print "Header Length: %02X" % (self.HeaderLength)
print "Checksum: %02X" % (self.Checksum)
pname = self.PartitionName.rstrip('\0')
if not pname:
pname = "(none)"
print "Partition name: %s" % (pname)
print "---Modules---"
for mod in self.modules:
mod.pprint()
print
print "------End-------"
PartTypes = ["Code", "BlockIo", "Nvram", "Generic", "Effs", "Rom"]
PT_CODE = 0
PT_BLOCKIO = 1
PT_NVRAM = 2
PT_GENERIC = 3
PT_EFFS = 4
PT_ROM = 5
class MeFptEntry(ctypes.LittleEndianStructure):
_fields_ = [
("Name", char*4), # 00 partition name
("Owner", char*4), # 04 partition owner?
("Offset", uint32_t), # 08 from the start of FPT, or 0
("Size", uint32_t), # 0C
("TokensOnStart", uint32_t), # 10
("MaxTokens", uint32_t), # 14
("ScratchSectors", uint32_t), # 18
("Flags", uint32_t), # 1C
]
#def __init__(self, f, offset):
#self.sig1, self.Owner, self.Offset, self.Size = struct.unpack("<4s4sII", f[offset:offset+0x10])
#self.TokensOnStart, self.MaxTokens, self.ScratchSectors, self.Flags = struct.unpack("<IIII", f[offset+0x10:offset+0x20])
def ptype(self):
return self.Flags & 0x7F
def print_flags(self):
pt = self.ptype()
if pt < len(PartTypes):
stype = "%d (%s)" % (pt, PartTypes[pt])
else:
stype = "%d" % pt
print " Type: %s" % stype
print " DirectAccess: %d" % ((self.Flags>>7)&1)
print " Read: %d" % ((self.Flags>>8)&1)
print " Write: %d" % ((self.Flags>>9)&1)
print " Execute: %d" % ((self.Flags>>10)&1)
print " Logical: %d" % ((self.Flags>>11)&1)
print " WOPDisable: %d" % ((self.Flags>>12)&1)
print " ExclBlockUse: %d" % ((self.Flags>>13)&1)
def pprint(self):
print "Partition: %r" % self.Name
print "Owner: %s" % [repr(self.Owner), "(none)"][self.Owner == '\xFF\xFF\xFF\xFF']
print "Offset/size: %08X/%08X" % (self.Offset, self.Size)
print "TokensOnStart: %08X" % (self.TokensOnStart)
print "MaxTokens: %08X" % (self.MaxTokens)
print "ScratchSectors: %08X" % (self.ScratchSectors)
print "Flags: %04X" % self.Flags
self.print_flags()
class MeFptTable:
def __init__(self, f, offset):
hdr = f[offset:offset+0x30]
if hdr[0x10:0x14] == '$FPT':
self.rombjump = hdr[:0x10]
base = offset + 0x10
elif hdr[0:4] == '$FPT':
base = offset
self.rombjump = None
else:
raise Exception("FPT format not recognized")
num_entries = DwordAt(f, base+4)
self.BCDVer, self.FPTEntryType, self.HeaderLen, self.Checksum = struct.unpack("<BBBB", f[base+8:base+12])
self.FlashCycleLifetime, self.FlashCycleLimit, self.UMASize = struct.unpack("<HHI", f[base+12:base+20])
x = struct.unpack("<I4H", f[base+20:base+32])
self.Flags, self.ExtraVer = x[0], x[1:5]
offset = base + 0x20
self.parts = []
for i in range(num_entries):
part = get_struct(f, offset, MeFptEntry) #MeFptEntry(f, offset)
offset += 0x20
self.parts.append(part)
def extract(self, f, offset):
for ipart in range(len(self.parts)):
part = self.parts[ipart]
print "Partition: %r %08X/%08X" % (part.Name, part.Offset, part.Size),
islast = (ipart == len(self.parts)-1)
if part.Offset in [0xFFFFFFFF, 0] or (part.Size in [0xFFFFFFFF, 0] and not islast):
print " (skipping)"
else:
nm = part.Name.rstrip('\0')
soff = offset + part.Offset
fname = "%s_part.bin" % (part.Name)
fname = replace_bad(fname, map(chr, range(128, 256) + range(0, 32)))
print " => %s" % (fname)
open(fname, "wb").write(f[soff:soff+part.Size])
if part.ptype() == PT_CODE:
extract_code_mods(nm, f, soff)
def find_part(self, name):
for part in self.parts:
if part.Name == name:
return part
return None
def pprint(self):
print "===ME Flash Partition Table==="
print "NumEntries: %d" % len(self.parts)
print "Version: %d.%d" % (self.BCDVer >> 4, self.BCDVer & 0xF)
print "EntryType: %02X" % (self.FPTEntryType)
print "HeaderLen: %02X" % (self.HeaderLen)
print "Checksum: %02X" % (self.Checksum)
print "FlashCycleLifetime: %d" % (self.FlashCycleLifetime)
print "FlashCycleLimit: %d" % (self.FlashCycleLimit)
print "UMASize: %d" % self.UMASize
print "Flags: %08X" % self.Flags
print " EFFS present: %d" % (self.Flags&1)
print " ME Layout Type: %d" % ((self.Flags>>1)&0xFF)
print "Extra ver: %d.%d.%d.%d" % (self.ExtraVer)
if self.rombjump:
print "ROM Bypass instruction: %s" % hexdump(self.rombjump)
print "---Partitions---"
for part in self.parts:
part.pprint()
print
print "------End-------"
region_names = ["Descriptor", "BIOS", "ME", "GbE", "PDR", "Region 5", "Region 6", "Region 7" ]
region_fnames =["Flash Descriptor", "BIOS Region", "ME Region", "GbE Region", "PDR Region", "Region 5", "Region 6", "Region 7" ]
def print_flreg(val, name):
print "%s region:" % name
lim = ((val >> 4) & 0xFFF000)
base = (val << 12) & 0xFFF000
if lim == 0 and base == 0xFFF000:
print " [unused]"
return None
lim |= 0xFFF
print " %08X - %08X (0x%08X bytes)" % (base, lim, lim - base + 1)
return (base, lim)
def parse_descr(f, offset, extract):
mapoff = offset
if f[offset+0x10:offset+0x14] == "\x5A\xA5\xF0\x0F":
mapoff = offset + 0x10
elif f[offset:offset+0x4] != "\x5A\xA5\xF0\x0F":
return -1
print "Flash Descriptor found at %08X" % offset
FLMAP0, FLMAP1, FLMAP2 = struct.unpack("<III", f[mapoff+4:mapoff+0x10])
nr = (FLMAP0 >> 24) & 0x7