me_cleaner.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  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. from struct import pack, unpack
  21. min_ftpr_offset = 0x60
  22. unremovable_modules = ("BUP", "ROMP")
  23. class OutOfRegionException(Exception):
  24. pass
  25. class regionFile:
  26. def __init__(self, f, region_start, region_end):
  27. self.f = f
  28. self.region_start = region_start
  29. self.region_end = region_end
  30. def read(self, n):
  31. return self.f.read(n)
  32. def readinto(self, b):
  33. return self.f.readinto(b)
  34. def seek(self, offset):
  35. return self.f.seek(offset)
  36. def write_to(self, offset, data):
  37. if offset >= self.region_start and \
  38. offset + len(data) <= self.region_end:
  39. self.f.seek(offset)
  40. return self.f.write(data)
  41. else:
  42. raise OutOfRegionException()
  43. def fill_range(self, start, end, fill):
  44. if start >= self.region_start and end <= self.region_end:
  45. if start < end:
  46. block = fill * 4096
  47. self.f.seek(start)
  48. self.f.writelines(itertools.repeat(block,
  49. (end - start) // 4096))
  50. self.f.write(block[:(end - start) % 4096])
  51. else:
  52. raise OutOfRegionException()
  53. def move_range(self, offset_from, size, offset_to, fill):
  54. if offset_from >= self.region_start and \
  55. offset_from + size <= self.region_end and \
  56. offset_to >= self.region_start and \
  57. offset_to + size <= self.region_end:
  58. for i in range(0, size, 4096):
  59. self.f.seek(offset_from + i, 0)
  60. block = self.f.read(4096 if size - i >= 4096 else size - i)
  61. self.f.seek(offset_from + i, 0)
  62. self.f.write(fill * len(block))
  63. self.f.seek(offset_to + i, 0)
  64. self.f.write(block)
  65. else:
  66. raise OutOfRegionException()
  67. def get_chunks_offsets(llut, me_start):
  68. chunk_count = unpack("<I", llut[0x04:0x08])[0]
  69. huffman_stream_end = sum(unpack("<II", llut[0x10:0x18])) + me_start
  70. nonzero_offsets = [huffman_stream_end]
  71. offsets = []
  72. for i in range(0, chunk_count):
  73. chunk = llut[0x40 + i * 4:0x44 + i * 4]
  74. offset = 0
  75. if chunk[3] != 0x80:
  76. offset = unpack("<I", chunk[0:3] + b"\x00")[0] + me_start
  77. offsets.append([offset, 0])
  78. if offset != 0:
  79. nonzero_offsets.append(offset)
  80. nonzero_offsets.sort()
  81. for i in offsets:
  82. if i[0] != 0:
  83. i[1] = nonzero_offsets[nonzero_offsets.index(i[0]) + 1]
  84. return offsets
  85. def remove_modules(f, mod_headers, ftpr_offset, me_end):
  86. comp_str = ("Uncomp.", "Huffman", "LZMA")
  87. unremovable_huff_chunks = []
  88. chunks_offsets = []
  89. base = 0
  90. chunk_size = 0
  91. end_addr = 0
  92. for mod_header in mod_headers:
  93. name = mod_header[0x04:0x14].rstrip(b"\x00").decode("ascii")
  94. offset = unpack("<I", mod_header[0x38:0x3C])[0] + ftpr_offset
  95. size = unpack("<I", mod_header[0x40:0x44])[0]
  96. flags = unpack("<I", mod_header[0x50:0x54])[0]
  97. comp_type = (flags >> 4) & 7
  98. sys.stdout.write(" {:<16} ({:<7}, ".format(name, comp_str[comp_type]))
  99. if comp_type == 0x00 or comp_type == 0x02:
  100. sys.stdout.write("0x{:06x} - 0x{:06x}): "
  101. .format(offset, offset + size))
  102. if name in unremovable_modules:
  103. end_addr = max(end_addr, offset + size)
  104. print("NOT removed, essential")
  105. else:
  106. end = min(offset + size, me_end)
  107. f.fill_range(offset, end, b"\xff")
  108. print("removed")
  109. elif comp_type == 0x01:
  110. sys.stdout.write("fragmented data ): ")
  111. if not chunks_offsets:
  112. f.seek(offset)
  113. llut = f.read(4)
  114. if llut == b"LLUT":
  115. llut += f.read(0x3c)
  116. chunk_count = unpack("<I", llut[0x4:0x8])[0]
  117. base = unpack("<I", llut[0x8:0xc])[0] + 0x10000000
  118. huff_data_len = unpack("<I", llut[0x10:0x14])[0]
  119. chunk_size = unpack("<I", llut[0x30:0x34])[0]
  120. llut += f.read(chunk_count * 4 + huff_data_len)
  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("-r", "--relocate", help="relocate the FTPR partition "
  231. "to the top of the ME region", action="store_true")
  232. parser.add_argument("-k", "--keep-modules", help="don't remove the FTPR "
  233. "modules, even when possible", action="store_true")
  234. parser.add_argument("-c", "--check", help="verify the integrity of the "
  235. "fundamental parts of the firmware and exit",
  236. action="store_true")
  237. args = parser.parse_args()
  238. with open(args.file, "rb" if args.check else "r+b") as fu:
  239. fu.seek(0x10)
  240. magic = fu.read(4)
  241. if magic == b"$FPT":
  242. print("ME/TXE image detected")
  243. me_start = 0
  244. fu.seek(0, 2)
  245. me_end = fu.tell()
  246. elif magic == b"\x5a\xa5\xf0\x0f":
  247. print("Full image detected")
  248. fu.seek(0x14)
  249. flmap0 = unpack("<I", fu.read(4))[0]
  250. nr = flmap0 >> 24 & 0x7
  251. frba = flmap0 >> 12 & 0xff0
  252. if nr >= 2:
  253. fu.seek(frba + 0x8)
  254. flreg2 = unpack("<I", fu.read(4))[0]
  255. me_start = (flreg2 & 0x1fff) << 12
  256. me_end = flreg2 >> 4 & 0x1fff000 | 0xfff + 1
  257. if me_start >= me_end:
  258. sys.exit("The ME/TXE region in this image has been "
  259. "disabled")
  260. fu.seek(me_start + 0x10)
  261. if fu.read(4) != b"$FPT":
  262. sys.exit("The ME/TXE region is corrupted or missing")
  263. print("The ME/TXE region goes from {:#x} to {:#x}"
  264. .format(me_start, me_end))
  265. else:
  266. sys.exit("This image does not contains a ME/TXE firmware "
  267. "(NR = {})".format(nr))
  268. else:
  269. sys.exit("Unknown image")
  270. print("Found FPT header at {:#x}".format(me_start + 0x10))
  271. f = regionFile(fu, me_start, me_end)
  272. f.seek(me_start + 0x14)
  273. entries = unpack("<I", f.read(4))[0]
  274. print("Found {} partition(s)".format(entries))
  275. f.seek(me_start + 0x14)
  276. header_len = unpack("B", f.read(1))[0]
  277. f.seek(me_start + 0x30)
  278. partitions = f.read(entries * 0x20)
  279. ftpr_header = b""
  280. for i in range(entries):
  281. if partitions[i * 0x20:(i * 0x20) + 4] == b"FTPR":
  282. ftpr_header = partitions[i * 0x20:(i + 1) * 0x20]
  283. break
  284. if ftpr_header == b"":
  285. sys.exit("FTPR header not found, this image doesn't seem to be "
  286. "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. print("Removing extra partitions...")
  305. f.fill_range(me_start + 0x30, ftpr_offset, b"\xff")
  306. f.fill_range(ftpr_offset + ftpr_lenght, me_end, b"\xff")
  307. print("Removing extra partition entries in FPT...")
  308. f.write_to(me_start + 0x30, ftpr_header)
  309. f.write_to(me_start + 0x14, pack("<I", 1))
  310. print("Removing EFFS presence flag...")
  311. f.seek(me_start + 0x24)
  312. flags = unpack("<I", f.read(4))[0]
  313. flags &= ~(0x00000001)
  314. f.write_to(me_start + 0x24, pack("<I", flags))
  315. if me11:
  316. f.seek(me_start + 0x10)
  317. header = bytearray(f.read(0x20))
  318. else:
  319. f.seek(me_start)
  320. header = bytearray(f.read(0x30))
  321. checksum = (0x100 - (sum(header) - header[0x1b]) & 0xff) & 0xff
  322. print("Correcting checksum (0x{:02x})...".format(checksum))
  323. # The checksum is just the two's complement of the sum of the
  324. # first 0x30 bytes in ME < 11 or bytes 0x10:0x30 in ME >= 11
  325. # (except for 0x1b, the checksum itself). In other words, the sum
  326. # of those bytes must be always 0x00.
  327. f.write_to(me_start + 0x1b, pack("B", checksum))
  328. if not me11:
  329. print("Reading FTPR modules list...")
  330. f.seek(ftpr_offset + 0x1c)
  331. tag = f.read(4)
  332. if tag == b"$MN2":
  333. f.seek(ftpr_offset + 0x20)
  334. num_modules = unpack("<I", f.read(4))[0]
  335. f.seek(ftpr_offset + 0x290)
  336. data = f.read(0x84)
  337. module_header_size = 0
  338. if data[0x0:0x4] == b"$MME":
  339. if data[0x60:0x64] == b"$MME" or num_modules == 1:
  340. module_header_size = 0x60
  341. elif data[0x80:0x84] == b"$MME":
  342. module_header_size = 0x80
  343. if module_header_size != 0:
  344. f.seek(ftpr_offset + 0x290)
  345. mod_headers = [f.read(module_header_size)
  346. for i in range(0, num_modules)]
  347. if all(hdr.startswith(b"$MME") for hdr in mod_headers):
  348. if args.keep_modules:
  349. end_addr = ftpr_offset + ftpr_lenght
  350. else:
  351. end_addr = remove_modules(f, mod_headers,
  352. ftpr_offset, me_end)
  353. if args.relocate:
  354. new_ftpr_offset = relocate_partition(f,
  355. me_start, me_end,
  356. me_start + 0x30,
  357. min_ftpr_offset + me_start,
  358. mod_headers)
  359. end_addr += new_ftpr_offset - ftpr_offset
  360. ftpr_offset = new_ftpr_offset
  361. end_addr = (end_addr // 0x1000 + 1) * 0x1000
  362. print("The ME minimum size is {0} bytes "
  363. "({0:#x} bytes)".format(end_addr - me_start))
  364. if me_start > 0:
  365. print("The ME region can be reduced up to:\n"
  366. " {:08x}:{:08x} me"
  367. .format(me_start, end_addr - 1))
  368. else:
  369. print("Found less modules than expected in the "
  370. "FTPR partition; skipping modules removal")
  371. else:
  372. print("Can't find the module header size; skipping "
  373. "modules removal")
  374. else:
  375. print("Wrong FTPR partition tag ({}); skipping modules "
  376. "removal".format(tag))
  377. else:
  378. print("Modules removal in ME v11 or greater is not yet "
  379. "supported")
  380. sys.stdout.write("Checking FTPR RSA signature... ")
  381. if check_partition_signature(f, ftpr_offset + ftpr_mn2_offset):
  382. print("VALID")
  383. else:
  384. print("INVALID!!")
  385. sys.exit("The FTPR partition signature is not valid. Is the input "
  386. "ME/TXE image valid?")
  387. if not args.check:
  388. print("Done! Good luck!")