me_cleaner.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. #!/usr/bin/python
  2. # me_cleaner - Tool for partial deblobbing of Intel ME/TXE firmware images
  3. # Copyright (C) 2016, 2017 Nicola Corna <nicola@corna.info>
  4. #
  5. # This program is free software; you can redistribute it and/or modify
  6. # it under the terms of the GNU General Public License as published by
  7. # the Free Software Foundation; either version 3 of the License, or
  8. # (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. import sys
  16. import itertools
  17. import binascii
  18. import hashlib
  19. import argparse
  20. import shutil
  21. from struct import pack, unpack
  22. min_ftpr_offset = 0x60
  23. unremovable_modules = ("BUP", "ROMP")
  24. class OutOfRegionException(Exception):
  25. pass
  26. class regionFile:
  27. def __init__(self, f, region_start, region_end):
  28. self.f = f
  29. self.region_start = region_start
  30. self.region_end = region_end
  31. def read(self, n):
  32. return self.f.read(n)
  33. def readinto(self, b):
  34. return self.f.readinto(b)
  35. def seek(self, offset):
  36. return self.f.seek(offset)
  37. def write_to(self, offset, data):
  38. if offset >= self.region_start and \
  39. offset + len(data) <= self.region_end:
  40. self.f.seek(offset)
  41. return self.f.write(data)
  42. else:
  43. raise OutOfRegionException()
  44. def fill_range(self, start, end, fill):
  45. if start >= self.region_start and end <= self.region_end:
  46. if start < end:
  47. block = fill * 4096
  48. self.f.seek(start)
  49. self.f.writelines(itertools.repeat(block,
  50. (end - start) // 4096))
  51. self.f.write(block[:(end - start) % 4096])
  52. else:
  53. raise OutOfRegionException()
  54. def move_range(self, offset_from, size, offset_to, fill):
  55. if offset_from >= self.region_start and \
  56. offset_from + size <= self.region_end and \
  57. offset_to >= self.region_start and \
  58. offset_to + size <= self.region_end:
  59. for i in range(0, size, 4096):
  60. self.f.seek(offset_from + i, 0)
  61. block = self.f.read(4096 if size - i >= 4096 else size - i)
  62. self.f.seek(offset_from + i, 0)
  63. self.f.write(fill * len(block))
  64. self.f.seek(offset_to + i, 0)
  65. self.f.write(block)
  66. else:
  67. raise OutOfRegionException()
  68. def get_chunks_offsets(llut, me_start):
  69. chunk_count = unpack("<I", llut[0x04:0x08])[0]
  70. huffman_stream_end = sum(unpack("<II", llut[0x10:0x18])) + me_start
  71. nonzero_offsets = [huffman_stream_end]
  72. offsets = []
  73. for i in range(0, chunk_count):
  74. chunk = llut[0x40 + i * 4:0x44 + i * 4]
  75. offset = 0
  76. if chunk[3] != 0x80:
  77. offset = unpack("<I", chunk[0:3] + b"\x00")[0] + me_start
  78. offsets.append([offset, 0])
  79. if offset != 0:
  80. nonzero_offsets.append(offset)
  81. nonzero_offsets.sort()
  82. for i in offsets:
  83. if i[0] != 0:
  84. i[1] = nonzero_offsets[nonzero_offsets.index(i[0]) + 1]
  85. return offsets
  86. def remove_modules(f, mod_headers, ftpr_offset, me_end):
  87. comp_str = ("Uncomp.", "Huffman", "LZMA")
  88. unremovable_huff_chunks = []
  89. chunks_offsets = []
  90. base = 0
  91. chunk_size = 0
  92. end_addr = 0
  93. for mod_header in mod_headers:
  94. name = mod_header[0x04:0x14].rstrip(b"\x00").decode("ascii")
  95. offset = unpack("<I", mod_header[0x38:0x3C])[0] + ftpr_offset
  96. size = unpack("<I", mod_header[0x40:0x44])[0]
  97. flags = unpack("<I", mod_header[0x50:0x54])[0]
  98. comp_type = (flags >> 4) & 7
  99. sys.stdout.write(" {:<16} ({:<7}, ".format(name, comp_str[comp_type]))
  100. if comp_type == 0x00 or comp_type == 0x02:
  101. sys.stdout.write("0x{:06x} - 0x{:06x}): "
  102. .format(offset, offset + size))
  103. if name in unremovable_modules:
  104. end_addr = max(end_addr, offset + size)
  105. print("NOT removed, essential")
  106. else:
  107. end = min(offset + size, me_end)
  108. f.fill_range(offset, end, b"\xff")
  109. print("removed")
  110. elif comp_type == 0x01:
  111. sys.stdout.write("fragmented data ): ")
  112. if not chunks_offsets:
  113. f.seek(offset)
  114. llut = f.read(4)
  115. if llut == b"LLUT":
  116. llut += f.read(0x3c)
  117. chunk_count = unpack("<I", llut[0x4:0x8])[0]
  118. base = unpack("<I", llut[0x8:0xc])[0] + 0x10000000
  119. chunk_size = unpack("<I", llut[0x30:0x34])[0]
  120. llut += f.read(chunk_count * 4)
  121. chunks_offsets = get_chunks_offsets(llut, me_start)
  122. else:
  123. sys.exit("Huffman modules found, but LLUT is not present")
  124. if name in unremovable_modules:
  125. print("NOT removed, essential")
  126. module_base = unpack("<I", mod_header[0x34:0x38])[0]
  127. module_size = unpack("<I", mod_header[0x3c:0x40])[0]
  128. first_chunk_num = (module_base - base) // chunk_size
  129. last_chunk_num = first_chunk_num + module_size // chunk_size
  130. unremovable_huff_chunks += \
  131. [x for x in chunks_offsets[first_chunk_num:
  132. last_chunk_num + 1] if x[0] != 0]
  133. else:
  134. print("removed")
  135. else:
  136. sys.stdout.write("0x{:06x} - 0x{:06x}): unknown compression, "
  137. "skipping".format(offset, offset + size))
  138. if chunks_offsets:
  139. removable_huff_chunks = []
  140. for chunk in chunks_offsets:
  141. if all(not(unremovable_chk[0] <= chunk[0] < unremovable_chk[1] or
  142. unremovable_chk[0] < chunk[1] <= unremovable_chk[1])
  143. for unremovable_chk in unremovable_huff_chunks):
  144. removable_huff_chunks.append(chunk)
  145. for removable_chunk in removable_huff_chunks:
  146. if removable_chunk[1] > removable_chunk[0]:
  147. end = min(removable_chunk[1], me_end)
  148. f.fill_range(removable_chunk[0], end, b"\xff")
  149. end_addr = max(end_addr,
  150. max(unremovable_huff_chunks, key=lambda x: x[1])[1])
  151. return end_addr
  152. def check_partition_signature(f, offset):
  153. f.seek(offset)
  154. header = f.read(0x80)
  155. modulus = int(binascii.hexlify(f.read(0x100)[::-1]), 16)
  156. public_exponent = unpack("<I", f.read(4))[0]
  157. signature = int(binascii.hexlify(f.read(0x100)[::-1]), 16)
  158. header_len = unpack("<I", header[0x4:0x8])[0] * 4
  159. manifest_len = unpack("<I", header[0x18:0x1c])[0] * 4
  160. f.seek(offset + header_len)
  161. sha256 = hashlib.sha256()
  162. sha256.update(header)
  163. sha256.update(f.read(manifest_len - header_len))
  164. decrypted_sig = pow(signature, public_exponent, modulus)
  165. return "{:#x}".format(decrypted_sig).endswith(sha256.hexdigest()) # FIXME
  166. def relocate_partition(f, me_start, me_end, partition_header_offset,
  167. new_offset, mod_headers):
  168. f.seek(partition_header_offset)
  169. name = f.read(4).rstrip(b"\x00").decode("ascii")
  170. f.seek(partition_header_offset + 0x8)
  171. old_offset, partition_size = unpack("<II", f.read(0x8))
  172. old_offset += me_start
  173. llut_start = 0
  174. for mod_header in mod_headers:
  175. if (unpack("<I", mod_header[0x50:0x54])[0] >> 4) & 7 == 0x01:
  176. llut_start = unpack("<I", mod_header[0x38:0x3C])[0] + old_offset
  177. break
  178. if llut_start != 0:
  179. # Bytes 0x9:0xb of the LLUT (bytes 0x1:0x3 of the AddrBase) are added
  180. # to the SpiBase (bytes 0xc:0x10 of the LLUT) to compute the final
  181. # start of the LLUT. Since AddrBase is not modifiable, we can act only
  182. # on SpiBase and here we compute the minimum allowed new_offset.
  183. f.seek(llut_start + 0x9)
  184. lut_start_corr = unpack("<H", f.read(2))[0]
  185. new_offset = max(new_offset,
  186. lut_start_corr + me_start - llut_start - 0x40 +
  187. old_offset)
  188. new_offset = ((new_offset + 0x1f) // 0x20) * 0x20
  189. offset_diff = new_offset - old_offset
  190. print("Relocating {} to {:#x} - {:#x}..."
  191. .format(name, new_offset, new_offset + partition_size))
  192. print(" Adjusting FPT entry...")
  193. f.write_to(partition_header_offset + 0x8,
  194. pack("<I", new_offset - me_start))
  195. if llut_start != 0:
  196. f.seek(llut_start)
  197. if f.read(4) == b"LLUT":
  198. print(" Adjusting LUT start offset...")
  199. lut_offset = llut_start + offset_diff + 0x40 - lut_start_corr
  200. f.write_to(llut_start + 0x0c, pack("<I", lut_offset))
  201. print(" Adjusting Huffman start offset...")
  202. f.seek(llut_start + 0x14)
  203. old_huff_offset = unpack("<I", f.read(4))[0]
  204. f.write_to(llut_start + 0x14,
  205. pack("<I", old_huff_offset + offset_diff))
  206. print(" Adjusting chunks offsets...")
  207. f.seek(llut_start + 0x4)
  208. chunk_count = unpack("<I", f.read(4))[0]
  209. f.seek(llut_start + 0x40)
  210. chunks = bytearray(chunk_count * 4)
  211. f.readinto(chunks)
  212. for i in range(0, chunk_count * 4, 4):
  213. if chunks[i + 3] != 0x80:
  214. chunks[i:i + 3] = \
  215. pack("<I", unpack("<I", chunks[i:i + 3] +
  216. b"\x00")[0] + offset_diff)[0:3]
  217. f.write_to(llut_start + 0x40, chunks)
  218. else:
  219. sys.exit("Huffman modules present but no LLUT found!")
  220. else:
  221. print(" No Huffman modules found")
  222. print(" Moving data...")
  223. partition_size = min(partition_size, me_end - old_offset)
  224. f.move_range(old_offset, partition_size, new_offset, b"\xff")
  225. return new_offset
  226. if __name__ == "__main__":
  227. parser = argparse.ArgumentParser(description="Tool to remove as much code "
  228. "as possible from Intel ME/TXE firmwares")
  229. parser.add_argument("file", help="ME/TXE image or full dump")
  230. parser.add_argument("-O", "--output", help="save the modified image in a "
  231. "separate file, instead of modifying the original "
  232. "file")
  233. parser.add_argument("-r", "--relocate", help="relocate the FTPR partition "
  234. "to the top of the ME region", action="store_true")
  235. parser.add_argument("-k", "--keep-modules", help="don't remove the FTPR "
  236. "modules, even when possible", action="store_true")
  237. parser.add_argument("-c", "--check", help="verify the integrity of the "
  238. "fundamental parts of the firmware and exit",
  239. action="store_true")
  240. args = parser.parse_args()
  241. f = open(args.file, "rb" if args.check or args.output else "r+b")
  242. f.seek(0x10)
  243. magic = f.read(4)
  244. if magic == b"$FPT":
  245. print("ME/TXE image detected")
  246. me_start = 0
  247. f.seek(0, 2)
  248. me_end = f.tell()
  249. elif magic == b"\x5a\xa5\xf0\x0f":
  250. print("Full image detected")
  251. f.seek(0x14)
  252. flmap0 = unpack("<I", f.read(4))[0]
  253. nr = flmap0 >> 24 & 0x7
  254. frba = flmap0 >> 12 & 0xff0
  255. if nr >= 2:
  256. f.seek(frba + 0x8)
  257. flreg2 = unpack("<I", f.read(4))[0]
  258. me_start = (flreg2 & 0x1fff) << 12
  259. me_end = flreg2 >> 4 & 0x1fff000 | 0xfff + 1
  260. if me_start >= me_end:
  261. sys.exit("The ME/TXE region in this image has been disabled")
  262. f.seek(me_start + 0x10)
  263. if f.read(4) != b"$FPT":
  264. sys.exit("The ME/TXE region is corrupted or missing")
  265. print("The ME/TXE region goes from {:#x} to {:#x}"
  266. .format(me_start, me_end))
  267. else:
  268. sys.exit("This image does not contains a ME/TXE firmware NR = {})"
  269. .format(nr))
  270. else:
  271. sys.exit("Unknown image")
  272. print("Found FPT header at {:#x}".format(me_start + 0x10))
  273. f.seek(me_start + 0x14)
  274. entries = unpack("<I", f.read(4))[0]
  275. print("Found {} partition(s)".format(entries))
  276. f.seek(me_start + 0x14)
  277. header_len = unpack("B", f.read(1))[0]
  278. f.seek(me_start + 0x30)
  279. partitions = f.read(entries * 0x20)
  280. ftpr_header = b""
  281. for i in range(entries):
  282. if partitions[i * 0x20:(i * 0x20) + 4] == b"FTPR":
  283. ftpr_header = partitions[i * 0x20:(i + 1) * 0x20]
  284. break
  285. if ftpr_header == b"":
  286. sys.exit("FTPR header not found, this image doesn't seem to be valid")
  287. ftpr_offset, ftpr_lenght = unpack("<II", ftpr_header[0x08:0x10])
  288. ftpr_offset += me_start
  289. print("Found FTPR header: FTPR partition spans from {:#x} to {:#x}"
  290. .format(ftpr_offset, ftpr_offset + ftpr_lenght))
  291. f.seek(ftpr_offset)
  292. if f.read(4) == b"$CPD":
  293. me11 = True
  294. num_entries = unpack("<I", f.read(4))[0]
  295. ftpr_mn2_offset = 0x10 + num_entries * 0x18
  296. else:
  297. me11 = False
  298. ftpr_mn2_offset = 0
  299. f.seek(ftpr_offset + ftpr_mn2_offset + 0x24)
  300. version = unpack("<HHHH", f.read(0x08))
  301. print("ME/TXE firmware version {}"
  302. .format('.'.join(str(i) for i in version)))
  303. if not args.check:
  304. if args.output:
  305. f.close()
  306. shutil.copy(args.file, args.output)
  307. f = open(args.output, "r+b")
  308. rf = regionFile(f, me_start, me_end)
  309. print("Removing extra partitions...")
  310. rf.fill_range(me_start + 0x30, ftpr_offset, b"\xff")
  311. rf.fill_range(ftpr_offset + ftpr_lenght, me_end, b"\xff")
  312. print("Removing extra partition entries in FPT...")
  313. rf.write_to(me_start + 0x30, ftpr_header)
  314. rf.write_to(me_start + 0x14, pack("<I", 1))
  315. print("Removing EFFS presence flag...")
  316. rf.seek(me_start + 0x24)
  317. flags = unpack("<I", rf.read(4))[0]
  318. flags &= ~(0x00000001)
  319. rf.write_to(me_start + 0x24, pack("<I", flags))
  320. if me11:
  321. rf.seek(me_start + 0x10)
  322. header = bytearray(rf.read(0x20))
  323. else:
  324. rf.seek(me_start)
  325. header = bytearray(rf.read(0x30))
  326. checksum = (0x100 - (sum(header) - header[0x1b]) & 0xff) & 0xff
  327. print("Correcting checksum (0x{:02x})...".format(checksum))
  328. # The checksum is just the two's complement of the sum of the first
  329. # 0x30 bytes in ME < 11 or bytes 0x10:0x30 in ME >= 11 (except for
  330. # 0x1b, the checksum itself). In other words, the sum of those bytes
  331. # must be always 0x00.
  332. rf.write_to(me_start + 0x1b, pack("B", checksum))
  333. if not me11:
  334. print("Reading FTPR modules list...")
  335. rf.seek(ftpr_offset + 0x1c)
  336. tag = rf.read(4)
  337. if tag == b"$MN2":
  338. rf.seek(ftpr_offset + 0x20)
  339. num_modules = unpack("<I", rf.read(4))[0]
  340. rf.seek(ftpr_offset + 0x290)
  341. data = rf.read(0x84)
  342. module_header_size = 0
  343. if data[0x0:0x4] == b"$MME":
  344. if data[0x60:0x64] == b"$MME" or num_modules == 1:
  345. module_header_size = 0x60
  346. elif data[0x80:0x84] == b"$MME":
  347. module_header_size = 0x80
  348. if module_header_size != 0:
  349. rf.seek(ftpr_offset + 0x290)
  350. mod_headers = [rf.read(module_header_size)
  351. for i in range(0, num_modules)]
  352. if all(hdr.startswith(b"$MME") for hdr in mod_headers):
  353. if args.keep_modules:
  354. end_addr = ftpr_offset + ftpr_lenght
  355. else:
  356. end_addr = remove_modules(rf, mod_headers,
  357. ftpr_offset, me_end)
  358. if args.relocate:
  359. new_ftpr_offset = relocate_partition(rf,
  360. me_start, me_end,
  361. me_start + 0x30,
  362. min_ftpr_offset + me_start,
  363. mod_headers)
  364. end_addr += new_ftpr_offset - ftpr_offset
  365. ftpr_offset = new_ftpr_offset
  366. end_addr = (end_addr // 0x1000 + 1) * 0x1000
  367. print("The ME minimum size is {0} bytes ({0:#x} bytes)"
  368. .format(end_addr - me_start))
  369. if me_start > 0:
  370. print("The ME region can be reduced up to:\n"
  371. " {:08x}:{:08x} me"
  372. .format(me_start, end_addr - 1))
  373. else:
  374. print("Found less modules than expected in the FTPR "
  375. "partition; skipping modules removal")
  376. else:
  377. print("Can't find the module header size; skipping "
  378. "modules removal")
  379. else:
  380. print("Wrong FTPR partition tag ({}); skipping modules removal"
  381. .format(tag))
  382. else:
  383. print("Modules removal in ME v11 or greater is not yet supported")
  384. sys.stdout.write("Checking FTPR RSA signature... ")
  385. if check_partition_signature(f, ftpr_offset + ftpr_mn2_offset):
  386. print("VALID")
  387. else:
  388. print("INVALID!!")
  389. sys.exit("The FTPR partition signature is not valid. Is the input "
  390. "ME/TXE image valid?")
  391. f.close()
  392. if not args.check:
  393. print("Done! Good luck!")