me_cleaner.py 37 KB

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