You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

897 lines
34 KiB

  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_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("-v", "--version", action="version",
  375. version="%(prog)s 1.2")
  376. parser.add_argument("file", help="ME/TXE image or full dump")
  377. parser.add_argument("-O", "--output", metavar='output_file', help="save "
  378. "the modified image in a separate file, instead of "
  379. "modifying the original file")
  380. softdis.add_argument("-S", "--soft-disable", help="in addition to the "
  381. "usual operations on the ME/TXE firmware, set the "
  382. "MeAltDisable bit or the HAP bit to ask Intel ME/TXE "
  383. "to disable itself after the hardware initialization "
  384. "(requires a full dump)", action="store_true")
  385. softdis.add_argument("-s", "--soft-disable-only", help="instead of the "
  386. "usual operations on the ME/TXE firmware, just set "
  387. "the MeAltDisable bit or the HAP bit to ask Intel "
  388. "ME/TXE to disable itself after the hardware "
  389. "initialization (requires a full dump)",
  390. action="store_true")
  391. parser.add_argument("-r", "--relocate", help="relocate the FTPR partition "
  392. "to the top of the ME region to save even more space",
  393. action="store_true")
  394. parser.add_argument("-t", "--truncate", help="truncate the empty part of "
  395. "the firmware (requires a separated ME/TXE image or "
  396. "--extract-me)", action="store_true")
  397. parser.add_argument("-k", "--keep-modules", help="don't remove the FTPR "
  398. "modules, even when possible", action="store_true")
  399. bw_list.add_argument("-w", "--whitelist", metavar="whitelist",
  400. help="Comma separated list of additional partitions "
  401. "to keep in the final image. This can be used to "
  402. "specify the MFS partition for example, which stores "
  403. "PCIe and clock settings.")
  404. bw_list.add_argument("-b", "--blacklist", metavar="blacklist",
  405. help="Comma separated list of partitions to remove "
  406. "from the image. This option overrides the default "
  407. "removal list.")
  408. parser.add_argument("-d", "--descriptor", help="remove the ME/TXE "
  409. "Read/Write permissions to the other regions on the "
  410. "flash from the Intel Flash Descriptor (requires a "
  411. "full dump)", action="store_true")
  412. parser.add_argument("-D", "--extract-descriptor",
  413. metavar='output_descriptor', help="extract the flash "
  414. "descriptor from a full dump; when used with "
  415. "--truncate save a descriptor with adjusted regions "
  416. "start and end")
  417. parser.add_argument("-M", "--extract-me", metavar='output_me_image',
  418. help="extract the ME firmware from a full dump; when "
  419. "used with --truncate save a truncated ME/TXE image")
  420. parser.add_argument("-c", "--check", help="verify the integrity of the "
  421. "fundamental parts of the firmware and exit",
  422. action="store_true")
  423. args = parser.parse_args()
  424. if args.check and (args.soft_disable_only or args.soft_disable or
  425. args.relocate or args.descriptor or args.truncate or args.output):
  426. sys.exit("-c can't be used with -S, -s, -r, -d, -t or -O")
  427. if args.soft_disable_only and (args.relocate or args.truncate):
  428. sys.exit("-s can't be used with -r or -t")
  429. if (args.whitelist or args.blacklist) and args.relocate:
  430. sys.exit("Relocation is not yet supported with custom whitelist or "
  431. "blacklist")
  432. f = open(args.file, "rb" if args.check or args.output else "r+b")
  433. f.seek(0x10)
  434. magic = f.read(4)
  435. if magic == b"$FPT":
  436. print("ME/TXE image detected")
  437. if args.descriptor or args.extract_descriptor or args.extract_me or \
  438. args.soft_disable or args.soft_disable_only:
  439. sys.exit("-d, -D, -M, -S and -s require a full dump")
  440. f.seek(0, 2)
  441. me_start = 0
  442. me_end = f.tell()
  443. mef = RegionFile(f, me_start, me_end)
  444. elif magic == b"\x5a\xa5\xf0\x0f":
  445. print("Full image detected")
  446. if args.truncate and not args.extract_me:
  447. sys.exit("-t requires a separated ME/TXE image (or --extract-me)")
  448. f.seek(0x14)
  449. flmap0, flmap1 = unpack("<II", f.read(8))
  450. frba = flmap0 >> 12 & 0xff0
  451. fmba = (flmap1 & 0xff) << 4
  452. fpsba = flmap1 >> 12 & 0xff0
  453. f.seek(frba)
  454. flreg = unpack("<III", f.read(12))
  455. fd_start, fd_end = flreg_to_start_end(flreg[0])
  456. bios_start, bios_end = flreg_to_start_end(flreg[1])
  457. me_start, me_end = flreg_to_start_end(flreg[2])
  458. if me_start >= me_end:
  459. sys.exit("The ME/TXE region in this image has been disabled")
  460. mef = RegionFile(f, me_start, me_end)
  461. mef.seek(0x10)
  462. if mef.read(4) != b"$FPT":
  463. sys.exit("The ME/TXE region is corrupted or missing")
  464. print("The ME/TXE region goes from {:#x} to {:#x}"
  465. .format(me_start, me_end))
  466. else:
  467. sys.exit("Unknown image")
  468. end_addr = me_end
  469. print("Found FPT header at {:#x}".format(mef.region_start + 0x10))
  470. mef.seek(0x14)
  471. entries = unpack("<I", mef.read(4))[0]
  472. print("Found {} partition(s)".format(entries))
  473. mef.seek(0x30)
  474. partitions = mef.read(entries * 0x20)
  475. ftpr_header = b""
  476. for i in range(entries):
  477. if partitions[i * 0x20:(i * 0x20) + 4] == b"FTPR":
  478. ftpr_header = partitions[i * 0x20:(i + 1) * 0x20]
  479. break
  480. if ftpr_header == b"":
  481. sys.exit("FTPR header not found, this image doesn't seem to be valid")
  482. ftpr_offset, ftpr_length = unpack("<II", ftpr_header[0x08:0x10])
  483. print("Found FTPR header: FTPR partition spans from {:#x} to {:#x}"
  484. .format(ftpr_offset, ftpr_offset + ftpr_length))
  485. mef.seek(ftpr_offset)
  486. if mef.read(4) == b"$CPD":
  487. me11 = True
  488. num_entries = unpack("<I", mef.read(4))[0]
  489. mef.seek(ftpr_offset + 0x10)
  490. ftpr_mn2_offset = -1
  491. for i in range(0, num_entries):
  492. data = mef.read(0x18)
  493. name = data[0x0:0xc].rstrip(b"\x00").decode("ascii")
  494. offset = unpack("<I", data[0xc:0xf] + b"\x00")[0]
  495. if name == "FTPR.man":
  496. ftpr_mn2_offset = offset
  497. break
  498. if ftpr_mn2_offset >= 0:
  499. check_mn2_tag(mef, ftpr_offset + ftpr_mn2_offset)
  500. print("Found FTPR manifest at {:#x}"
  501. .format(ftpr_offset + ftpr_mn2_offset))
  502. else:
  503. sys.exit("Can't find the manifest of the FTPR partition")
  504. else:
  505. check_mn2_tag(mef, ftpr_offset)
  506. me11 = False
  507. ftpr_mn2_offset = 0
  508. mef.seek(ftpr_offset + ftpr_mn2_offset + 0x24)
  509. version = unpack("<HHHH", mef.read(0x08))
  510. print("ME/TXE firmware version {}"
  511. .format('.'.join(str(i) for i in version)))
  512. mef.seek(ftpr_offset + ftpr_mn2_offset + 0x80)
  513. pubkey_md5 = hashlib.md5(mef.read(0x104)).hexdigest()
  514. if pubkey_md5 in pubkeys_md5:
  515. variant, pubkey_versions = pubkeys_md5[pubkey_md5]
  516. print("Public key match: Intel {}, firmware versions {}"
  517. .format(variant, ", ".join(pubkey_versions)))
  518. else:
  519. if version[0] >= 6:
  520. variant = "ME"
  521. else:
  522. variant = "TXE"
  523. print("WARNING Unknown public key {}\n"
  524. " Assuming Intel {}\n"
  525. " Please report this warning to the project's maintainer!"
  526. .format(pubkey_md5, variant))
  527. if not args.check and args.output:
  528. f.close()
  529. shutil.copy(args.file, args.output)
  530. f = open(args.output, "r+b")
  531. mef = RegionFile(f, me_start, me_end)
  532. if me_start > 0:
  533. fdf = RegionFile(f, fd_start, fd_end)
  534. if me11:
  535. fdf.seek(fpsba)
  536. pchstrp0 = unpack("<I", fdf.read(4))[0]
  537. print("The HAP bit is " +
  538. ("SET" if pchstrp0 & 1 << 16 else "NOT SET"))
  539. else:
  540. fdf.seek(fpsba + 0x28)
  541. pchstrp10 = unpack("<I", fdf.read(4))[0]
  542. print("The AltMeDisable bit is " +
  543. ("SET" if pchstrp10 & 1 << 7 else "NOT SET"))
  544. # ME 6 Ignition: wipe everything
  545. me6_ignition = False
  546. if not args.check and not args.soft_disable_only and \
  547. variant == "ME" and version[0] == 6:
  548. mef.seek(ftpr_offset + 0x20)
  549. num_modules = unpack("<I", mef.read(4))[0]
  550. mef.seek(ftpr_offset + 0x290 + (num_modules + 1) * 0x60)
  551. data = mef.read(0xc)
  552. if data[0x0:0x4] == b"$SKU" and data[0x8:0xc] == b"\x00\x00\x00\x00":
  553. print("ME 6 Ignition firmware detected, removing everything...")
  554. mef.fill_all(b"\xff")
  555. me6_ignition = True
  556. if not args.check:
  557. if not args.soft_disable_only and not me6_ignition:
  558. print("Reading partitions list...")
  559. unremovable_part_fpt = b""
  560. extra_part_end = 0
  561. whitelist = []
  562. blacklist = []
  563. whitelist += unremovable_partitions
  564. if args.blacklist:
  565. blacklist = args.blacklist.split(",")
  566. elif args.whitelist:
  567. whitelist += args.whitelist.split(",")
  568. for i in range(entries):
  569. partition = partitions[i * 0x20:(i + 1) * 0x20]
  570. flags = unpack("<I", partition[0x1c:0x20])[0]
  571. try:
  572. part_name = \
  573. partition[0x0:0x4].rstrip(b"\x00").decode("ascii")
  574. except UnicodeDecodeError:
  575. part_name = "????"
  576. part_start, part_length = unpack("<II", partition[0x08:0x10])
  577. # ME 6: the last partition has 0xffffffff as size
  578. if variant == "ME" and version[0] == 6 and \
  579. i == entries - 1 and part_length == 0xffffffff:
  580. part_length = me_end - me_start - part_start
  581. part_end = part_start + part_length
  582. if flags & 0x7f == 2:
  583. print(" {:<4} ({:^24}, 0x{:08x} total bytes): nothing to "
  584. "remove"
  585. .format(part_name, "NVRAM partition, no data",
  586. part_length))
  587. elif part_start == 0 or part_length == 0 or part_end > me_end:
  588. print(" {:<4} ({:^24}, 0x{:08x} total bytes): nothing to "
  589. "remove"
  590. .format(part_name, "no data here", part_length))
  591. else:
  592. print(" {:<4} (0x{:08x} - 0x{:09x}, 0x{:08x} total bytes): "
  593. .format(part_name, part_start, part_end, part_length),
  594. end="")
  595. if part_name in whitelist or (blacklist and
  596. part_name not in blacklist):
  597. unremovable_part_fpt += partition
  598. if part_name != "FTPR":
  599. extra_part_end = max(extra_part_end, part_end)
  600. print("NOT removed")
  601. else:
  602. mef.fill_range(part_start, part_end, b"\xff")
  603. print("removed")
  604. print("Removing partition entries in FPT...")
  605. mef.write_to(0x30, unremovable_part_fpt)
  606. mef.write_to(0x14,
  607. pack("<I", len(unremovable_part_fpt) // 0x20))
  608. mef.fill_range(0x30 + len(unremovable_part_fpt),
  609. 0x30 + len(partitions), b"\xff")
  610. if (not blacklist and "EFFS" not in whitelist) or \
  611. "EFFS" in blacklist:
  612. print("Removing EFFS presence flag...")
  613. mef.seek(0x24)
  614. flags = unpack("<I", mef.read(4))[0]
  615. flags &= ~(0x00000001)
  616. mef.write_to(0x24, pack("<I", flags))
  617. if me11:
  618. mef.seek(0x10)
  619. header = bytearray(mef.read(0x20))
  620. header[0x0b] = 0x00
  621. else:
  622. mef.seek(0)
  623. header = bytearray(mef.read(0x30))
  624. header[0x1b] = 0x00
  625. checksum = (0x100 - sum(header) & 0xff) & 0xff
  626. print("Correcting checksum (0x{:02x})...".format(checksum))
  627. # The checksum is just the two's complement of the sum of the first
  628. # 0x30 bytes in ME < 11 or bytes 0x10:0x30 in ME >= 11 (except for
  629. # 0x1b, the checksum itself). In other words, the sum of those
  630. # bytes must be always 0x00.
  631. mef.write_to(0x1b, pack("B", checksum))
  632. print("Reading FTPR modules list...")
  633. if me11:
  634. end_addr, ftpr_offset = \
  635. check_and_remove_modules_me11(mef, me_end,
  636. ftpr_offset, ftpr_length,
  637. min_ftpr_offset,
  638. args.relocate,
  639. args.keep_modules)
  640. else:
  641. end_addr, ftpr_offset = \
  642. check_and_remove_modules(mef, me_end, ftpr_offset,
  643. min_ftpr_offset, args.relocate,
  644. args.keep_modules)
  645. if end_addr > 0:
  646. end_addr = max(end_addr, extra_part_end)
  647. end_addr = (end_addr // 0x1000 + 1) * 0x1000
  648. end_addr += spared_blocks * 0x1000
  649. print("The ME minimum size should be {0} bytes "
  650. "({0:#x} bytes)".format(end_addr))
  651. if me_start > 0:
  652. print("The ME region can be reduced up to:\n"
  653. " {:08x}:{:08x} me"
  654. .format(me_start, me_start + end_addr - 1))
  655. elif args.truncate:
  656. print("Truncating file at {:#x}...".format(end_addr))
  657. f.truncate(end_addr)
  658. if args.soft_disable or args.soft_disable_only:
  659. if me11:
  660. print("Setting the HAP bit in PCHSTRP0 to disable Intel ME...")
  661. pchstrp0 |= (1 << 16)
  662. fdf.write_to(fpsba, pack("<I", pchstrp0))
  663. else:
  664. print("Setting the AltMeDisable bit in PCHSTRP10 to disable "
  665. "Intel ME...")
  666. pchstrp10 |= (1 << 7)
  667. fdf.write_to(fpsba + 0x28, pack("<I", pchstrp10))
  668. if args.descriptor:
  669. print("Removing ME/TXE R/W access to the other flash regions...")
  670. if me11:
  671. flmstr2 = 0x00400500
  672. else:
  673. fdf.seek(fmba + 0x4)
  674. flmstr2 = (unpack("<I", fdf.read(4))[0] | 0x04040000) & 0x0404ffff
  675. fdf.write_to(fmba + 0x4, pack("<I", flmstr2))
  676. if args.extract_descriptor:
  677. if args.truncate:
  678. print("Extracting the descriptor to \"{}\"..."
  679. .format(args.extract_descriptor))
  680. fdf_copy = fdf.save(args.extract_descriptor, fd_end - fd_start)
  681. if bios_start == me_end:
  682. print("Modifying the regions of the extracted descriptor...")
  683. print(" {:08x}:{:08x} me --> {:08x}:{:08x} me"
  684. .format(me_start, me_end - 1,
  685. me_start, me_start + end_addr - 1))
  686. print(" {:08x}:{:08x} bios --> {:08x}:{:08x} bios"
  687. .format(bios_start, bios_end - 1,
  688. me_start + end_addr, bios_end - 1))
  689. flreg1 = start_end_to_flreg(me_start + end_addr, bios_end)
  690. flreg2 = start_end_to_flreg(me_start, me_start + end_addr)
  691. fdf_copy.seek(frba + 0x4)
  692. fdf_copy.write(pack("<II", flreg1, flreg2))
  693. else:
  694. print("\nWARNING:\n The start address of the BIOS region "
  695. "isn't equal to the end address of the ME\n region: if "
  696. "you want to recover the space from the ME region you "
  697. "have to\n manually modify the descriptor.\n")
  698. else:
  699. print("Extracting the descriptor to \"{}\"..."
  700. .format(args.extract_descriptor))
  701. fdf_copy = fdf.save(args.extract_descriptor, fd_end - fd_start)
  702. fdf_copy.close()
  703. if args.extract_me:
  704. if args.truncate:
  705. print("Extracting and truncating the ME image to \"{}\"..."
  706. .format(args.extract_me))
  707. mef_copy = mef.save(args.extract_me, end_addr)
  708. else:
  709. print("Extracting the ME image to \"{}\"..."
  710. .format(args.extract_me))
  711. mef_copy = mef.save(args.extract_me, me_end - me_start)
  712. if not me6_ignition:
  713. print("Checking the FTPR RSA signature of the extracted ME "
  714. "image... ", end="")
  715. print_check_partition_signature(mef_copy,
  716. ftpr_offset + ftpr_mn2_offset)
  717. mef_copy.close()
  718. if not me6_ignition:
  719. print("Checking the FTPR RSA signature... ", end="")
  720. print_check_partition_signature(mef, ftpr_offset + ftpr_mn2_offset)
  721. f.close()
  722. if not args.check:
  723. print("Done! Good luck!")