me_cleaner.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887
  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. from __future__ import division, print_function
  16. import argparse
  17. import binascii
  18. import hashlib
  19. import itertools
  20. import shutil
  21. import sys
  22. from struct import pack, unpack
  23. min_ftpr_offset = 0x400
  24. spared_blocks = 4
  25. unremovable_modules = ("ROMP", "BUP")
  26. unremovable_modules_me11 = ("rbe", "kernel", "syslib", "bup")
  27. unremovable_partitions = ("FTPR",)
  28. pubkeys_md5 = {
  29. "763e59ebe235e45a197a5b1a378dfa04": ("ME", ("6.x.x.x",)),
  30. "3a98c847d609c253e145bd36512629cb": ("ME", ("6.0.50.x",)),
  31. "0903fc25b0f6bed8c4ed724aca02124c": ("ME", ("7.x.x.x", "8.x.x.x")),
  32. "2011ae6df87c40fba09e3f20459b1ce0": ("ME", ("9.0.x.x", "9.1.x.x")),
  33. "e8427c5691cf8b56bc5cdd82746957ed": ("ME", ("9.5.x.x", "10.x.x.x")),
  34. "986a78e481f185f7d54e4af06eb413f6": ("ME", ("11.x.x.x",)),
  35. "bda0b6bb8ca0bf0cac55ac4c4d55e0f2": ("TXE", ("1.x.x.x",)),
  36. "b726a2ab9cd59d4e62fe2bead7cf6997": ("TXE", ("1.x.x.x",)),
  37. "0633d7f951a3e7968ae7460861be9cfb": ("TXE", ("2.x.x.x",)),
  38. "1d0a36e9f5881540d8e4b382c6612ed8": ("TXE", ("3.x.x.x",)),
  39. "be900fef868f770d266b1fc67e887e69": ("SPS", ("2.x.x.x",)),
  40. "4622e3f2cb212a89c90a4de3336d88d2": ("SPS", ("3.x.x.x",)),
  41. "31ef3d950eac99d18e187375c0764ca4": ("SPS", ("4.x.x.x",))
  42. }
  43. class OutOfRegionException(Exception):
  44. pass
  45. class RegionFile:
  46. def __init__(self, f, region_start, region_end):
  47. self.f = f
  48. self.region_start = region_start
  49. self.region_end = region_end
  50. def read(self, n):
  51. if f.tell() + n <= self.region_end:
  52. return self.f.read(n)
  53. else:
  54. raise OutOfRegionException()
  55. def readinto(self, b):
  56. if f.tell() + len(b) <= self.region_end:
  57. return self.f.readinto(b)
  58. else:
  59. raise OutOfRegionException()
  60. def seek(self, offset):
  61. if self.region_start + offset <= self.region_end:
  62. return self.f.seek(self.region_start + offset)
  63. else:
  64. raise OutOfRegionException()
  65. def write_to(self, offset, data):
  66. if self.region_start + offset + len(data) <= self.region_end:
  67. self.f.seek(self.region_start + offset)
  68. return self.f.write(data)
  69. else:
  70. raise OutOfRegionException()
  71. def fill_range(self, start, end, fill):
  72. if self.region_start + end <= self.region_end:
  73. if start < end:
  74. block = fill * 4096
  75. self.f.seek(self.region_start + start)
  76. self.f.writelines(itertools.repeat(block,
  77. (end - start) // 4096))
  78. self.f.write(block[:(end - start) % 4096])
  79. else:
  80. raise OutOfRegionException()
  81. def fill_all(self, fill):
  82. self.fill_range(0, self.region_end - self.region_start, fill)
  83. def move_range(self, offset_from, size, offset_to, fill):
  84. if self.region_start + offset_from + size <= self.region_end and \
  85. self.region_start + offset_to + size <= self.region_end:
  86. for i in range(0, size, 4096):
  87. self.f.seek(self.region_start + offset_from + i, 0)
  88. block = self.f.read(min(size - i, 4096))
  89. self.f.seek(self.region_start + offset_from + i, 0)
  90. self.f.write(fill * len(block))
  91. self.f.seek(self.region_start + offset_to + i, 0)
  92. self.f.write(block)
  93. else:
  94. raise OutOfRegionException()
  95. def save(self, filename, size):
  96. if self.region_start + size <= self.region_end:
  97. self.f.seek(self.region_start)
  98. copyf = open(filename, "w+b")
  99. for i in range(0, size, 4096):
  100. copyf.write(self.f.read(min(size - i, 4096)))
  101. return copyf
  102. else:
  103. raise OutOfRegionException()
  104. def get_chunks_offsets(llut):
  105. chunk_count = unpack("<I", llut[0x04:0x08])[0]
  106. huffman_stream_end = sum(unpack("<II", llut[0x10:0x18]))
  107. nonzero_offsets = [huffman_stream_end]
  108. offsets = []
  109. for i in range(0, chunk_count):
  110. chunk = llut[0x40 + i * 4:0x44 + i * 4]
  111. offset = 0
  112. if chunk[3] != 0x80:
  113. offset = unpack("<I", chunk[0:3] + b"\x00")[0]
  114. offsets.append([offset, 0])
  115. if offset != 0:
  116. nonzero_offsets.append(offset)
  117. nonzero_offsets.sort()
  118. for i in offsets:
  119. if i[0] != 0:
  120. i[1] = nonzero_offsets[nonzero_offsets.index(i[0]) + 1]
  121. return offsets
  122. def remove_modules(f, mod_headers, ftpr_offset, me_end):
  123. comp_str = ("uncomp.", "Huffman", "LZMA")
  124. unremovable_huff_chunks = []
  125. chunks_offsets = []
  126. base = 0
  127. chunk_size = 0
  128. end_addr = 0
  129. for mod_header in mod_headers:
  130. name = mod_header[0x04:0x14].rstrip(b"\x00").decode("ascii")
  131. offset = unpack("<I", mod_header[0x38:0x3C])[0] + ftpr_offset
  132. size = unpack("<I", mod_header[0x40:0x44])[0]
  133. flags = unpack("<I", mod_header[0x50:0x54])[0]
  134. comp_type = (flags >> 4) & 7
  135. print(" {:<16} ({:<7}, ".format(name, comp_str[comp_type]), end="")
  136. if comp_type == 0x00 or comp_type == 0x02:
  137. print("0x{:06x} - 0x{:06x} ): "
  138. .format(offset, offset + size), end="")
  139. if name in unremovable_modules:
  140. end_addr = max(end_addr, offset + size)
  141. print("NOT removed, essential")
  142. else:
  143. end = min(offset + size, me_end)
  144. f.fill_range(offset, end, b"\xff")
  145. print("removed")
  146. elif comp_type == 0x01:
  147. if not chunks_offsets:
  148. f.seek(offset)
  149. llut = f.read(4)
  150. if llut == b"LLUT":
  151. llut += f.read(0x3c)
  152. chunk_count = unpack("<I", llut[0x4:0x8])[0]
  153. base = unpack("<I", llut[0x8:0xc])[0] + 0x10000000
  154. chunk_size = unpack("<I", llut[0x30:0x34])[0]
  155. llut += f.read(chunk_count * 4)
  156. chunks_offsets = get_chunks_offsets(llut)
  157. else:
  158. sys.exit("Huffman modules found, but LLUT is not present")
  159. module_base = unpack("<I", mod_header[0x34:0x38])[0]
  160. module_size = unpack("<I", mod_header[0x3c:0x40])[0]
  161. first_chunk_num = (module_base - base) // chunk_size
  162. last_chunk_num = first_chunk_num + module_size // chunk_size
  163. huff_size = 0
  164. for chunk in chunks_offsets[first_chunk_num:last_chunk_num + 1]:
  165. huff_size += chunk[1] - chunk[0]
  166. print("fragmented data, {:<9}): "
  167. .format("~" + str(int(round(huff_size / 1024))) + " KiB"),
  168. end="")
  169. if name in unremovable_modules:
  170. print("NOT removed, essential")
  171. unremovable_huff_chunks += \
  172. [x for x in chunks_offsets[first_chunk_num:
  173. last_chunk_num + 1] if x[0] != 0]
  174. else:
  175. print("removed")
  176. else:
  177. print("0x{:06x} - 0x{:06x}): unknown compression, skipping"
  178. .format(offset, offset + size), end="")
  179. if chunks_offsets:
  180. removable_huff_chunks = []
  181. for chunk in chunks_offsets:
  182. if all(not(unremovable_chk[0] <= chunk[0] < unremovable_chk[1] or
  183. unremovable_chk[0] < chunk[1] <= unremovable_chk[1])
  184. for unremovable_chk in unremovable_huff_chunks):
  185. removable_huff_chunks.append(chunk)
  186. for removable_chunk in removable_huff_chunks:
  187. if removable_chunk[1] > removable_chunk[0]:
  188. end = min(removable_chunk[1], me_end)
  189. f.fill_range(removable_chunk[0], end, b"\xff")
  190. end_addr = max(end_addr,
  191. max(unremovable_huff_chunks, key=lambda x: x[1])[1])
  192. return end_addr
  193. def check_partition_signature(f, offset):
  194. f.seek(offset)
  195. header = f.read(0x80)
  196. modulus = int(binascii.hexlify(f.read(0x100)[::-1]), 16)
  197. public_exponent = unpack("<I", f.read(4))[0]
  198. signature = int(binascii.hexlify(f.read(0x100)[::-1]), 16)
  199. header_len = unpack("<I", header[0x4:0x8])[0] * 4
  200. manifest_len = unpack("<I", header[0x18:0x1c])[0] * 4
  201. f.seek(offset + header_len)
  202. sha256 = hashlib.sha256()
  203. sha256.update(header)
  204. sha256.update(f.read(manifest_len - header_len))
  205. decrypted_sig = pow(signature, public_exponent, modulus)
  206. return "{:#x}".format(decrypted_sig).endswith(sha256.hexdigest()) # FIXME
  207. def print_check_partition_signature(f, offset):
  208. if check_partition_signature(f, offset):
  209. print("VALID")
  210. else:
  211. print("INVALID!!")
  212. sys.exit("The FTPR partition signature is not valid. Is the input "
  213. "ME/TXE image valid?")
  214. def relocate_partition(f, me_end, partition_header_offset,
  215. new_offset, mod_headers):
  216. f.seek(partition_header_offset)
  217. name = f.read(4).rstrip(b"\x00").decode("ascii")
  218. f.seek(partition_header_offset + 0x8)
  219. old_offset, partition_size = unpack("<II", f.read(0x8))
  220. llut_start = 0
  221. for mod_header in mod_headers:
  222. if (unpack("<I", mod_header[0x50:0x54])[0] >> 4) & 7 == 0x01:
  223. llut_start = unpack("<I", mod_header[0x38:0x3C])[0] + old_offset
  224. break
  225. if mod_headers and llut_start != 0:
  226. # Bytes 0x9:0xb of the LLUT (bytes 0x1:0x3 of the AddrBase) are added
  227. # to the SpiBase (bytes 0xc:0x10 of the LLUT) to compute the final
  228. # start of the LLUT. Since AddrBase is not modifiable, we can act only
  229. # on SpiBase and here we compute the minimum allowed new_offset.
  230. f.seek(llut_start + 0x9)
  231. lut_start_corr = unpack("<H", f.read(2))[0]
  232. new_offset = max(new_offset,
  233. lut_start_corr - llut_start - 0x40 + old_offset)
  234. new_offset = ((new_offset + 0x1f) // 0x20) * 0x20
  235. offset_diff = new_offset - old_offset
  236. print("Relocating {} from {:#x} - {:#x} to {:#x} - {:#x}..."
  237. .format(name, old_offset, old_offset + partition_size,
  238. new_offset, new_offset + partition_size))
  239. print(" Adjusting FPT entry...")
  240. f.write_to(partition_header_offset + 0x8,
  241. pack("<I", new_offset))
  242. if mod_headers:
  243. if llut_start != 0:
  244. f.seek(llut_start)
  245. if f.read(4) == b"LLUT":
  246. print(" Adjusting LUT start offset...")
  247. lut_offset = llut_start + offset_diff + 0x40 - lut_start_corr
  248. f.write_to(llut_start + 0x0c, pack("<I", lut_offset))
  249. print(" Adjusting Huffman start offset...")
  250. f.seek(llut_start + 0x14)
  251. old_huff_offset = unpack("<I", f.read(4))[0]
  252. f.write_to(llut_start + 0x14,
  253. pack("<I", old_huff_offset + offset_diff))
  254. print(" Adjusting chunks offsets...")
  255. f.seek(llut_start + 0x4)
  256. chunk_count = unpack("<I", f.read(4))[0]
  257. f.seek(llut_start + 0x40)
  258. chunks = bytearray(chunk_count * 4)
  259. f.readinto(chunks)
  260. for i in range(0, chunk_count * 4, 4):
  261. if chunks[i + 3] != 0x80:
  262. chunks[i:i + 3] = \
  263. pack("<I", unpack("<I", chunks[i:i + 3] +
  264. b"\x00")[0] + offset_diff)[0:3]
  265. f.write_to(llut_start + 0x40, chunks)
  266. else:
  267. sys.exit("Huffman modules present but no LLUT found!")
  268. else:
  269. print(" No Huffman modules found")
  270. print(" Moving data...")
  271. partition_size = min(partition_size, me_end - old_offset)
  272. f.move_range(old_offset, partition_size, new_offset, b"\xff")
  273. return new_offset
  274. def check_and_remove_modules(f, me_end, offset, min_offset,
  275. relocate, keep_modules):
  276. f.seek(offset + 0x20)
  277. num_modules = unpack("<I", f.read(4))[0]
  278. f.seek(offset + 0x290)
  279. data = f.read(0x84)
  280. mod_header_size = 0
  281. if data[0x0:0x4] == b"$MME":
  282. if data[0x60:0x64] == b"$MME" or num_modules == 1:
  283. mod_header_size = 0x60
  284. elif data[0x80:0x84] == b"$MME":
  285. mod_header_size = 0x80
  286. if mod_header_size != 0:
  287. f.seek(offset + 0x290)
  288. data = f.read(mod_header_size * num_modules)
  289. mod_headers = [data[i * mod_header_size:(i + 1) * mod_header_size]
  290. for i in range(0, num_modules)]
  291. if all(hdr.startswith(b"$MME") for hdr in mod_headers):
  292. if args.keep_modules:
  293. end_addr = offset + ftpr_length
  294. else:
  295. end_addr = remove_modules(f, mod_headers, offset, me_end)
  296. if args.relocate:
  297. new_offset = relocate_partition(f, me_end, 0x30, min_offset,
  298. mod_headers)
  299. end_addr += new_offset - offset
  300. offset = new_offset
  301. return end_addr, offset
  302. else:
  303. print("Found less modules than expected in the FTPR "
  304. "partition; skipping modules removal")
  305. else:
  306. print("Can't find the module header size; skipping "
  307. "modules removal")
  308. return -1, offset
  309. def check_and_remove_modules_me11(f, me_end, partition_offset,
  310. partition_length, min_offset, relocate,
  311. keep_modules):
  312. comp_str = ("LZMA/uncomp.", "Huffman")
  313. if keep_modules:
  314. end_data = partition_offset + partition_length
  315. else:
  316. end_data = 0
  317. f.seek(partition_offset + 0x4)
  318. module_count = unpack("<I", f.read(4))[0]
  319. modules = []
  320. modules.append(("end", partition_length, 0))
  321. f.seek(partition_offset + 0x10)
  322. for i in range(0, module_count):
  323. data = f.read(0x18)
  324. name = data[0x0:0xc].rstrip(b"\x00").decode("ascii")
  325. offset_block = unpack("<I", data[0xc:0x10])[0]
  326. offset = offset_block & 0x01ffffff
  327. comp_type = (offset_block & 0x02000000) >> 25
  328. modules.append((name, offset, comp_type))
  329. modules.sort(key=lambda x: x[1])
  330. for i in range(0, module_count):
  331. name = modules[i][0]
  332. offset = partition_offset + modules[i][1]
  333. end = partition_offset + modules[i + 1][1]
  334. removed = False
  335. if name.endswith(".man") or name.endswith(".met"):
  336. compression = "uncompressed"
  337. else:
  338. compression = comp_str[modules[i][2]]
  339. print(" {:<12} ({:<12}, 0x{:06x} - 0x{:06x}): "
  340. .format(name, compression, offset, end), end="")
  341. if name.endswith(".man"):
  342. print("NOT removed, partition manif.")
  343. elif name.endswith(".met"):
  344. print("NOT removed, module metadata")
  345. elif any(name.startswith(m) for m in unremovable_modules_me11):
  346. print("NOT removed, essential")
  347. else:
  348. removed = True
  349. f.fill_range(offset, min(end, me_end), b"\xff")
  350. print("removed")
  351. if not removed:
  352. end_data = max(end_data, end)
  353. if relocate:
  354. new_offset = relocate_partition(f, me_end, 0x30, min_offset, [])
  355. end_data += new_offset - partition_offset
  356. partition_offset = new_offset
  357. return end_data, partition_offset
  358. def check_mn2_tag(f, offset):
  359. f.seek(offset + 0x1c)
  360. tag = f.read(4)
  361. if tag != b"$MN2":
  362. sys.exit("Wrong FTPR manifest tag ({}), this image may be corrupted"
  363. .format(tag))
  364. def flreg_to_start_end(flreg):
  365. return (flreg & 0x7fff) << 12, (flreg >> 4 & 0x7fff000 | 0xfff) + 1
  366. def start_end_to_flreg(start, end):
  367. return (start & 0x7fff000) >> 12 | ((end - 1) & 0x7fff000) << 4
  368. if __name__ == "__main__":
  369. parser = argparse.ArgumentParser(description="Tool to remove as much code "
  370. "as possible from Intel ME/TXE firmware "
  371. "images")
  372. softdis = parser.add_mutually_exclusive_group()
  373. bw_list = parser.add_mutually_exclusive_group()
  374. parser.add_argument("file", help="ME/TXE image or full dump")
  375. parser.add_argument("-O", "--output", metavar='output_file', help="save "
  376. "the modified image in a separate file, instead of "
  377. "modifying the original file")
  378. softdis.add_argument("-S", "--soft-disable", help="in addition to the "
  379. "usual operations on the ME/TXE firmware, set the "
  380. "MeAltDisable bit or the HAP bit to ask Intel ME/TXE "
  381. "to disable itself after the hardware initialization "
  382. "(requires a full dump)", action="store_true")
  383. softdis.add_argument("-s", "--soft-disable-only", help="instead of the "
  384. "usual operations on the ME/TXE firmware, just set "
  385. "the MeAltDisable bit or the HAP bit to ask Intel "
  386. "ME/TXE to disable itself after the hardware "
  387. "initialization (requires a full dump)",
  388. action="store_true")
  389. parser.add_argument("-r", "--relocate", help="relocate the FTPR partition "
  390. "to the top of the ME region to save even more space",
  391. action="store_true")
  392. parser.add_argument("-k", "--keep-modules", help="don't remove the FTPR "
  393. "modules, even when possible", action="store_true")
  394. bw_list.add_argument("-w", "--whitelist", metavar="whitelist",
  395. help="Comma separated list of additional partitions "
  396. "to keep in the final image. This can be used to "
  397. "specify the MFS partition for example, which stores "
  398. "PCIe and clock settings.")
  399. bw_list.add_argument("-b", "--blacklist", metavar="blacklist",
  400. help="Comma separated list of partitions to remove "
  401. "from the image. This option overrides the default "
  402. "removal list.")
  403. parser.add_argument("-d", "--descriptor", help="remove the ME/TXE "
  404. "Read/Write permissions to the other regions on the "
  405. "flash from the Intel Flash Descriptor (requires a "
  406. "full dump)", action="store_true")
  407. parser.add_argument("-t", "--truncate", help="truncate the empty part of "
  408. "the firmware (requires a separated ME/TXE image or "
  409. "--extract-me)", action="store_true")
  410. parser.add_argument("-c", "--check", help="verify the integrity of the "
  411. "fundamental parts of the firmware and exit",
  412. action="store_true")
  413. parser.add_argument("-D", "--extract-descriptor",
  414. metavar='output_descriptor', help="extract the flash "
  415. "descriptor from a full dump; when used with "
  416. "--truncate save a descriptor with adjusted regions "
  417. "start and end")
  418. parser.add_argument("-M", "--extract-me", metavar='output_me_image',
  419. help="extract the ME firmware from a full dump; when "
  420. "used with --truncate save a truncated ME/TXE image")
  421. args = parser.parse_args()
  422. if args.check and (args.soft_disable_only or args.soft_disable or
  423. args.relocate or args.descriptor or args.truncate or args.output):
  424. sys.exit("-c can't be used with -S, -s, -r, -d, -t or -O")
  425. if args.soft_disable_only and (args.relocate or args.truncate):
  426. sys.exit("-s can't be used with -r or -t")
  427. if (args.whitelist or args.blacklist) and args.relocate:
  428. sys.exit("Relocation is not yet supported with custom whitelist or "
  429. "blacklist")
  430. f = open(args.file, "rb" if args.check or args.output else "r+b")
  431. f.seek(0x10)
  432. magic = f.read(4)
  433. if magic == b"$FPT":
  434. print("ME/TXE image detected")
  435. if args.descriptor or args.extract_descriptor or args.extract_me or \
  436. args.soft_disable or args.soft_disable_only:
  437. sys.exit("-d, -D, -M, -S and -s require a full dump")
  438. f.seek(0, 2)
  439. me_start = 0
  440. me_end = f.tell()
  441. mef = RegionFile(f, me_start, me_end)
  442. elif magic == b"\x5a\xa5\xf0\x0f":
  443. print("Full image detected")
  444. if args.truncate and not args.extract_me:
  445. sys.exit("-t requires a separated ME/TXE image (or --extract-me)")
  446. f.seek(0x14)
  447. flmap0, flmap1 = unpack("<II", f.read(8))
  448. frba = flmap0 >> 12 & 0xff0
  449. fmba = (flmap1 & 0xff) << 4
  450. fpsba = flmap1 >> 12 & 0xff0
  451. f.seek(frba)
  452. flreg = unpack("<III", f.read(12))
  453. fd_start, fd_end = flreg_to_start_end(flreg[0])
  454. bios_start, bios_end = flreg_to_start_end(flreg[1])
  455. me_start, me_end = flreg_to_start_end(flreg[2])
  456. if me_start >= me_end:
  457. sys.exit("The ME/TXE region in this image has been disabled")
  458. mef = RegionFile(f, me_start, me_end)
  459. mef.seek(0x10)
  460. if mef.read(4) != b"$FPT":
  461. sys.exit("The ME/TXE region is corrupted or missing")
  462. print("The ME/TXE region goes from {:#x} to {:#x}"
  463. .format(me_start, me_end))
  464. else:
  465. sys.exit("Unknown image")
  466. end_addr = me_end
  467. print("Found FPT header at {:#x}".format(mef.region_start + 0x10))
  468. mef.seek(0x14)
  469. entries = unpack("<I", mef.read(4))[0]
  470. print("Found {} partition(s)".format(entries))
  471. mef.seek(0x30)
  472. partitions = mef.read(entries * 0x20)
  473. ftpr_header = b""
  474. for i in range(entries):
  475. if partitions[i * 0x20:(i * 0x20) + 4] == b"FTPR":
  476. ftpr_header = partitions[i * 0x20:(i + 1) * 0x20]
  477. break
  478. if ftpr_header == b"":
  479. sys.exit("FTPR header not found, this image doesn't seem to be valid")
  480. ftpr_offset, ftpr_length = unpack("<II", ftpr_header[0x08:0x10])
  481. print("Found FTPR header: FTPR partition spans from {:#x} to {:#x}"
  482. .format(ftpr_offset, ftpr_offset + ftpr_length))
  483. mef.seek(ftpr_offset)
  484. if mef.read(4) == b"$CPD":
  485. me11 = True
  486. num_entries = unpack("<I", mef.read(4))[0]
  487. mef.seek(ftpr_offset + 0x10)
  488. ftpr_mn2_offset = -1
  489. for i in range(0, num_entries):
  490. data = mef.read(0x18)
  491. name = data[0x0:0xc].rstrip(b"\x00").decode("ascii")
  492. offset = unpack("<I", data[0xc:0xf] + b"\x00")[0]
  493. if name == "FTPR.man":
  494. ftpr_mn2_offset = offset
  495. break
  496. if ftpr_mn2_offset >= 0:
  497. check_mn2_tag(mef, ftpr_offset + ftpr_mn2_offset)
  498. print("Found FTPR manifest at {:#x}"
  499. .format(ftpr_offset + ftpr_mn2_offset))
  500. else:
  501. sys.exit("Can't find the manifest of the FTPR partition")
  502. else:
  503. check_mn2_tag(mef, ftpr_offset)
  504. me11 = False
  505. ftpr_mn2_offset = 0
  506. mef.seek(ftpr_offset + ftpr_mn2_offset + 0x24)
  507. version = unpack("<HHHH", mef.read(0x08))
  508. print("ME/TXE firmware version {}"
  509. .format('.'.join(str(i) for i in version)))
  510. mef.seek(ftpr_offset + ftpr_mn2_offset + 0x80)
  511. pubkey_md5 = hashlib.md5(mef.read(0x104)).hexdigest()
  512. if pubkey_md5 in pubkeys_md5:
  513. variant, pubkey_versions = pubkeys_md5[pubkey_md5]
  514. print("Public key match: Intel {}, firmware versions {}"
  515. .format(variant, ", ".join(pubkey_versions)))
  516. else:
  517. if version[0] >= 6:
  518. variant = "ME"
  519. else:
  520. variant = "TXE"
  521. print("WARNING Unknown public key {}\n"
  522. " Assuming Intel {}\n"
  523. " Please report this warning to the project's maintainer!"
  524. .format(pubkey_md5, variant))
  525. if not args.check and args.output:
  526. f.close()
  527. shutil.copy(args.file, args.output)
  528. f = open(args.output, "r+b")
  529. mef = RegionFile(f, me_start, me_end)
  530. if me_start > 0:
  531. fdf = RegionFile(f, fd_start, fd_end)
  532. # ME 6 Ignition: wipe everything
  533. me6_ignition = False
  534. if not args.check and not args.soft_disable_only and \
  535. variant == "ME" and version[0] == 6:
  536. mef.seek(ftpr_offset + 0x20)
  537. num_modules = unpack("<I", mef.read(4))[0]
  538. mef.seek(ftpr_offset + 0x290 + (num_modules + 1) * 0x60)
  539. data = mef.read(0xc)
  540. if data[0x0:0x4] == b"$SKU" and data[0x8:0xc] == b"\x00\x00\x00\x00":
  541. print("ME 6 Ignition firmware detected, removing everything...")
  542. mef.fill_all(b"\xff")
  543. me6_ignition = True
  544. if not args.check:
  545. if not args.soft_disable_only and not me6_ignition:
  546. print("Reading partitions list...")
  547. unremovable_part_fpt = b""
  548. extra_part_end = 0
  549. whitelist = []
  550. blacklist = []
  551. whitelist += unremovable_partitions
  552. if args.blacklist:
  553. blacklist = args.blacklist.split(",")
  554. elif args.whitelist:
  555. whitelist += args.whitelist.split(",")
  556. for i in range(entries):
  557. partition = partitions[i * 0x20:(i + 1) * 0x20]
  558. flags = unpack("<I", partition[0x1c:0x20])[0]
  559. try:
  560. part_name = \
  561. partition[0x0:0x4].rstrip(b"\x00").decode("ascii")
  562. except UnicodeDecodeError:
  563. part_name = "????"
  564. part_start, part_length = unpack("<II", partition[0x08:0x10])
  565. # ME 6: the last partition has 0xffffffff as size
  566. if variant == "ME" and version[0] == 6 and \
  567. i == entries - 1 and part_length == 0xffffffff:
  568. part_length = me_end - me_start - part_start
  569. part_end = part_start + part_length
  570. if flags & 0x7f == 2:
  571. print(" {:<4} ({:^24}, 0x{:08x} total bytes): nothing to "
  572. "remove"
  573. .format(part_name, "NVRAM partition, no data",
  574. part_length))
  575. elif part_start == 0 or part_length == 0 or part_end > me_end:
  576. print(" {:<4} ({:^24}, 0x{:08x} total bytes): nothing to "
  577. "remove"
  578. .format(part_name, "no data here", part_length))
  579. else:
  580. print(" {:<4} (0x{:08x} - 0x{:09x}, 0x{:08x} total bytes): "
  581. .format(part_name, part_start, part_end, part_length),
  582. end="")
  583. if part_name in whitelist or (blacklist and
  584. part_name not in blacklist):
  585. unremovable_part_fpt += partition
  586. if part_name != "FTPR":
  587. extra_part_end = max(extra_part_end, part_end)
  588. print("NOT removed")
  589. else:
  590. mef.fill_range(part_start, part_end, b"\xff")
  591. print("removed")
  592. print("Removing partition entries in FPT...")
  593. mef.write_to(0x30, unremovable_part_fpt)
  594. mef.write_to(0x14,
  595. pack("<I", len(unremovable_part_fpt) // 0x20))
  596. mef.fill_range(0x30 + len(unremovable_part_fpt),
  597. 0x30 + len(partitions), b"\xff")
  598. if (not blacklist and "EFFS" not in whitelist) or \
  599. "EFFS" in blacklist:
  600. print("Removing EFFS presence flag...")
  601. mef.seek(0x24)
  602. flags = unpack("<I", mef.read(4))[0]
  603. flags &= ~(0x00000001)
  604. mef.write_to(0x24, pack("<I", flags))
  605. if me11:
  606. mef.seek(0x10)
  607. header = bytearray(mef.read(0x20))
  608. header[0x0b] = 0x00
  609. else:
  610. mef.seek(0)
  611. header = bytearray(mef.read(0x30))
  612. header[0x1b] = 0x00
  613. checksum = (0x100 - sum(header) & 0xff) & 0xff
  614. print("Correcting checksum (0x{:02x})...".format(checksum))
  615. # The checksum is just the two's complement of the sum of the first
  616. # 0x30 bytes in ME < 11 or bytes 0x10:0x30 in ME >= 11 (except for
  617. # 0x1b, the checksum itself). In other words, the sum of those
  618. # bytes must be always 0x00.
  619. mef.write_to(0x1b, pack("B", checksum))
  620. print("Reading FTPR modules list...")
  621. if me11:
  622. end_addr, ftpr_offset = \
  623. check_and_remove_modules_me11(mef, me_end,
  624. ftpr_offset, ftpr_length,
  625. min_ftpr_offset,
  626. args.relocate,
  627. args.keep_modules)
  628. else:
  629. end_addr, ftpr_offset = \
  630. check_and_remove_modules(mef, me_end, ftpr_offset,
  631. min_ftpr_offset, args.relocate,
  632. args.keep_modules)
  633. if end_addr > 0:
  634. end_addr = max(end_addr, extra_part_end)
  635. end_addr = (end_addr // 0x1000 + 1) * 0x1000
  636. end_addr += spared_blocks * 0x1000
  637. print("The ME minimum size should be {0} bytes "
  638. "({0:#x} bytes)".format(end_addr))
  639. if me_start > 0:
  640. print("The ME region can be reduced up to:\n"
  641. " {:08x}:{:08x} me"
  642. .format(me_start, me_start + end_addr - 1))
  643. elif args.truncate:
  644. print("Truncating file at {:#x}...".format(end_addr))
  645. f.truncate(end_addr)
  646. if args.soft_disable or args.soft_disable_only:
  647. if me11:
  648. print("Setting the HAP bit in PCHSTRP0 to disable Intel ME...")
  649. fdf.seek(fpsba)
  650. pchstrp0 = unpack("<I", fdf.read(4))[0]
  651. pchstrp0 |= (1 << 16)
  652. fdf.write_to(fpsba, pack("<I", pchstrp0))
  653. else:
  654. print("Setting the AltMeDisable bit in PCHSTRP10 to disable "
  655. "Intel ME...")
  656. fdf.seek(fpsba + 0x28)
  657. pchstrp10 = unpack("<I", fdf.read(4))[0]
  658. pchstrp10 |= (1 << 7)
  659. fdf.write_to(fpsba + 0x28, pack("<I", pchstrp10))
  660. if args.descriptor:
  661. print("Removing ME/TXE R/W access to the other flash regions...")
  662. if me11:
  663. flmstr2 = 0x00400500
  664. else:
  665. fdf.seek(fmba + 0x4)
  666. flmstr2 = (unpack("<I", fdf.read(4))[0] | 0x04040000) & 0x0404ffff
  667. fdf.write_to(fmba + 0x4, pack("<I", flmstr2))
  668. if args.extract_descriptor:
  669. if args.truncate:
  670. print("Extracting the descriptor to \"{}\"..."
  671. .format(args.extract_descriptor))
  672. fdf_copy = fdf.save(args.extract_descriptor, fd_end - fd_start)
  673. if bios_start == me_end:
  674. print("Modifying the regions of the extracted descriptor...")
  675. print(" {:08x}:{:08x} me --> {:08x}:{:08x} me"
  676. .format(me_start, me_end - 1,
  677. me_start, me_start + end_addr - 1))
  678. print(" {:08x}:{:08x} bios --> {:08x}:{:08x} bios"
  679. .format(bios_start, bios_end - 1,
  680. me_start + end_addr, bios_end - 1))
  681. flreg1 = start_end_to_flreg(me_start + end_addr, bios_end)
  682. flreg2 = start_end_to_flreg(me_start, me_start + end_addr)
  683. fdf_copy.seek(frba + 0x4)
  684. fdf_copy.write(pack("<II", flreg1, flreg2))
  685. else:
  686. print("\nWARNING:\n The start address of the BIOS region "
  687. "isn't equal to the end address of the ME\n region: if "
  688. "you want to recover the space from the ME region you "
  689. "have to\n manually modify the descriptor.\n")
  690. else:
  691. print("Extracting the descriptor to \"{}\"..."
  692. .format(args.extract_descriptor))
  693. fdf_copy = fdf.save(args.extract_descriptor, fd_end - fd_start)
  694. fdf_copy.close()
  695. if args.extract_me:
  696. if args.truncate:
  697. print("Extracting and truncating the ME image to \"{}\"..."
  698. .format(args.extract_me))
  699. mef_copy = mef.save(args.extract_me, end_addr)
  700. else:
  701. print("Extracting the ME image to \"{}\"..."
  702. .format(args.extract_me))
  703. mef_copy = mef.save(args.extract_me, me_end - me_start)
  704. if not me6_ignition:
  705. print("Checking the FTPR RSA signature of the extracted ME "
  706. "image... ", end="")
  707. print_check_partition_signature(mef_copy,
  708. ftpr_offset + ftpr_mn2_offset)
  709. mef_copy.close()
  710. if not me6_ignition:
  711. print("Checking the FTPR RSA signature... ", end="")
  712. print_check_partition_signature(mef, ftpr_offset + ftpr_mn2_offset)
  713. f.close()
  714. if not args.check:
  715. print("Done! Good luck!")