me_cleaner.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740
  1. #!/usr/bin/python
  2. # me_cleaner - Tool for partial deblobbing of Intel ME/TXE firmware images
  3. # Copyright (C) 2016, 2017 Nicola Corna <nicola@corna.info>
  4. #
  5. # This program is free software; you can redistribute it and/or modify
  6. # it under the terms of the GNU General Public License as published by
  7. # the Free Software Foundation; either version 3 of the License, or
  8. # (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. import argparse
  16. import binascii
  17. import hashlib
  18. import itertools
  19. import shutil
  20. import sys
  21. from struct import pack, unpack
  22. min_ftpr_offset = 0x400
  23. spared_blocks = 4
  24. unremovable_modules = ("ROMP", "BUP")
  25. unremovable_modules_me11 = ("rbe", "kernel", "syslib", "bup")
  26. class OutOfRegionException(Exception):
  27. pass
  28. class RegionFile:
  29. def __init__(self, f, region_start, region_end):
  30. self.f = f
  31. self.region_start = region_start
  32. self.region_end = region_end
  33. def read(self, n):
  34. return self.f.read(n)
  35. def readinto(self, b):
  36. return self.f.readinto(b)
  37. def seek(self, offset):
  38. return self.f.seek(offset)
  39. def write_to(self, offset, data):
  40. if offset >= self.region_start and \
  41. offset + len(data) <= self.region_end:
  42. self.f.seek(offset)
  43. return self.f.write(data)
  44. else:
  45. raise OutOfRegionException()
  46. def fill_range(self, start, end, fill):
  47. if start >= self.region_start and end <= self.region_end:
  48. if start < end:
  49. block = fill * 4096
  50. self.f.seek(start)
  51. self.f.writelines(itertools.repeat(block,
  52. (end - start) // 4096))
  53. self.f.write(block[:(end - start) % 4096])
  54. else:
  55. raise OutOfRegionException()
  56. def move_range(self, offset_from, size, offset_to, fill):
  57. if offset_from >= self.region_start and \
  58. offset_from + size <= self.region_end and \
  59. offset_to >= self.region_start and \
  60. offset_to + size <= self.region_end:
  61. for i in range(0, size, 4096):
  62. self.f.seek(offset_from + i, 0)
  63. block = self.f.read(min(size - i, 4096))
  64. self.f.seek(offset_from + i, 0)
  65. self.f.write(fill * len(block))
  66. self.f.seek(offset_to + i, 0)
  67. self.f.write(block)
  68. else:
  69. raise OutOfRegionException()
  70. def save(self, filename, size):
  71. self.f.seek(self.region_start)
  72. copyf = open(filename, "w+b")
  73. for i in range(0, size, 4096):
  74. copyf.write(self.f.read(min(size - i, 4096)))
  75. return copyf
  76. def get_chunks_offsets(llut, me_start):
  77. chunk_count = unpack("<I", llut[0x04:0x08])[0]
  78. huffman_stream_end = sum(unpack("<II", llut[0x10:0x18])) + me_start
  79. nonzero_offsets = [huffman_stream_end]
  80. offsets = []
  81. for i in range(0, chunk_count):
  82. chunk = llut[0x40 + i * 4:0x44 + i * 4]
  83. offset = 0
  84. if chunk[3] != 0x80:
  85. offset = unpack("<I", chunk[0:3] + b"\x00")[0] + me_start
  86. offsets.append([offset, 0])
  87. if offset != 0:
  88. nonzero_offsets.append(offset)
  89. nonzero_offsets.sort()
  90. for i in offsets:
  91. if i[0] != 0:
  92. i[1] = nonzero_offsets[nonzero_offsets.index(i[0]) + 1]
  93. return offsets
  94. def remove_modules(f, mod_headers, ftpr_offset, me_end):
  95. comp_str = ("uncomp.", "Huffman", "LZMA")
  96. unremovable_huff_chunks = []
  97. chunks_offsets = []
  98. base = 0
  99. chunk_size = 0
  100. end_addr = 0
  101. for mod_header in mod_headers:
  102. name = mod_header[0x04:0x14].rstrip(b"\x00").decode("ascii")
  103. offset = unpack("<I", mod_header[0x38:0x3C])[0] + ftpr_offset
  104. size = unpack("<I", mod_header[0x40:0x44])[0]
  105. flags = unpack("<I", mod_header[0x50:0x54])[0]
  106. comp_type = (flags >> 4) & 7
  107. sys.stdout.write(" {:<16} ({:<7}, ".format(name, comp_str[comp_type]))
  108. if comp_type == 0x00 or comp_type == 0x02:
  109. sys.stdout.write("0x{:06x} - 0x{:06x}): "
  110. .format(offset, offset + size))
  111. if name in unremovable_modules:
  112. end_addr = max(end_addr, offset + size)
  113. print("NOT removed, essential")
  114. else:
  115. end = min(offset + size, me_end)
  116. f.fill_range(offset, end, b"\xff")
  117. print("removed")
  118. elif comp_type == 0x01:
  119. sys.stdout.write("fragmented data ): ")
  120. if not chunks_offsets:
  121. f.seek(offset)
  122. llut = f.read(4)
  123. if llut == b"LLUT":
  124. llut += f.read(0x3c)
  125. chunk_count = unpack("<I", llut[0x4:0x8])[0]
  126. base = unpack("<I", llut[0x8:0xc])[0] + 0x10000000
  127. chunk_size = unpack("<I", llut[0x30:0x34])[0]
  128. llut += f.read(chunk_count * 4)
  129. chunks_offsets = get_chunks_offsets(llut, me_start)
  130. else:
  131. sys.exit("Huffman modules found, but LLUT is not present")
  132. if name in unremovable_modules:
  133. print("NOT removed, essential")
  134. module_base = unpack("<I", mod_header[0x34:0x38])[0]
  135. module_size = unpack("<I", mod_header[0x3c:0x40])[0]
  136. first_chunk_num = (module_base - base) // chunk_size
  137. last_chunk_num = first_chunk_num + module_size // chunk_size
  138. unremovable_huff_chunks += \
  139. [x for x in chunks_offsets[first_chunk_num:
  140. last_chunk_num + 1] if x[0] != 0]
  141. else:
  142. print("removed")
  143. else:
  144. sys.stdout.write("0x{:06x} - 0x{:06x}): unknown compression, "
  145. "skipping".format(offset, offset + size))
  146. if chunks_offsets:
  147. removable_huff_chunks = []
  148. for chunk in chunks_offsets:
  149. if all(not(unremovable_chk[0] <= chunk[0] < unremovable_chk[1] or
  150. unremovable_chk[0] < chunk[1] <= unremovable_chk[1])
  151. for unremovable_chk in unremovable_huff_chunks):
  152. removable_huff_chunks.append(chunk)
  153. for removable_chunk in removable_huff_chunks:
  154. if removable_chunk[1] > removable_chunk[0]:
  155. end = min(removable_chunk[1], me_end)
  156. f.fill_range(removable_chunk[0], end, b"\xff")
  157. end_addr = max(end_addr,
  158. max(unremovable_huff_chunks, key=lambda x: x[1])[1])
  159. return end_addr
  160. def check_partition_signature(f, offset):
  161. f.seek(offset)
  162. header = f.read(0x80)
  163. modulus = int(binascii.hexlify(f.read(0x100)[::-1]), 16)
  164. public_exponent = unpack("<I", f.read(4))[0]
  165. signature = int(binascii.hexlify(f.read(0x100)[::-1]), 16)
  166. header_len = unpack("<I", header[0x4:0x8])[0] * 4
  167. manifest_len = unpack("<I", header[0x18:0x1c])[0] * 4
  168. f.seek(offset + header_len)
  169. sha256 = hashlib.sha256()
  170. sha256.update(header)
  171. sha256.update(f.read(manifest_len - header_len))
  172. decrypted_sig = pow(signature, public_exponent, modulus)
  173. return "{:#x}".format(decrypted_sig).endswith(sha256.hexdigest()) # FIXME
  174. def print_check_partition_signature(f, offset):
  175. if check_partition_signature(f, offset):
  176. print("VALID")
  177. else:
  178. print("INVALID!!")
  179. sys.exit("The FTPR partition signature is not valid. Is the input "
  180. "ME/TXE image valid?")
  181. def relocate_partition(f, me_start, me_end, partition_header_offset,
  182. new_offset, mod_headers):
  183. f.seek(partition_header_offset)
  184. name = f.read(4).rstrip(b"\x00").decode("ascii")
  185. f.seek(partition_header_offset + 0x8)
  186. old_offset, partition_size = unpack("<II", f.read(0x8))
  187. old_offset += me_start
  188. llut_start = 0
  189. for mod_header in mod_headers:
  190. if (unpack("<I", mod_header[0x50:0x54])[0] >> 4) & 7 == 0x01:
  191. llut_start = unpack("<I", mod_header[0x38:0x3C])[0] + old_offset
  192. break
  193. if mod_headers and llut_start != 0:
  194. # Bytes 0x9:0xb of the LLUT (bytes 0x1:0x3 of the AddrBase) are added
  195. # to the SpiBase (bytes 0xc:0x10 of the LLUT) to compute the final
  196. # start of the LLUT. Since AddrBase is not modifiable, we can act only
  197. # on SpiBase and here we compute the minimum allowed new_offset.
  198. f.seek(llut_start + 0x9)
  199. lut_start_corr = unpack("<H", f.read(2))[0]
  200. new_offset = max(new_offset,
  201. lut_start_corr + me_start - llut_start - 0x40 +
  202. old_offset)
  203. new_offset = ((new_offset + 0x1f) // 0x20) * 0x20
  204. offset_diff = new_offset - old_offset
  205. print("Relocating {} from {:#x} - {:#x} to {:#x} - {:#x}..."
  206. .format(name, old_offset, old_offset + partition_size,
  207. new_offset, new_offset + partition_size))
  208. print(" Adjusting FPT entry...")
  209. f.write_to(partition_header_offset + 0x8,
  210. pack("<I", new_offset - me_start))
  211. if mod_headers:
  212. if llut_start != 0:
  213. f.seek(llut_start)
  214. if f.read(4) == b"LLUT":
  215. print(" Adjusting LUT start offset...")
  216. lut_offset = llut_start + offset_diff + 0x40 - \
  217. lut_start_corr - me_start
  218. f.write_to(llut_start + 0x0c, pack("<I", lut_offset))
  219. print(" Adjusting Huffman start offset...")
  220. f.seek(llut_start + 0x14)
  221. old_huff_offset = unpack("<I", f.read(4))[0]
  222. f.write_to(llut_start + 0x14,
  223. pack("<I", old_huff_offset + offset_diff))
  224. print(" Adjusting chunks offsets...")
  225. f.seek(llut_start + 0x4)
  226. chunk_count = unpack("<I", f.read(4))[0]
  227. f.seek(llut_start + 0x40)
  228. chunks = bytearray(chunk_count * 4)
  229. f.readinto(chunks)
  230. for i in range(0, chunk_count * 4, 4):
  231. if chunks[i + 3] != 0x80:
  232. chunks[i:i + 3] = \
  233. pack("<I", unpack("<I", chunks[i:i + 3] +
  234. b"\x00")[0] + offset_diff)[0:3]
  235. f.write_to(llut_start + 0x40, chunks)
  236. else:
  237. sys.exit("Huffman modules present but no LLUT found!")
  238. else:
  239. print(" No Huffman modules found")
  240. print(" Moving data...")
  241. partition_size = min(partition_size, me_end - old_offset)
  242. f.move_range(old_offset, partition_size, new_offset, b"\xff")
  243. return new_offset
  244. def check_and_remove_modules(f, me_start, me_end, offset, min_offset,
  245. relocate, keep_modules):
  246. f.seek(offset + 0x20)
  247. num_modules = unpack("<I", f.read(4))[0]
  248. f.seek(offset + 0x290)
  249. data = f.read(0x84)
  250. module_header_size = 0
  251. if data[0x0:0x4] == b"$MME":
  252. if data[0x60:0x64] == b"$MME" or num_modules == 1:
  253. module_header_size = 0x60
  254. elif data[0x80:0x84] == b"$MME":
  255. module_header_size = 0x80
  256. if module_header_size != 0:
  257. f.seek(offset + 0x290)
  258. mod_headers = [f.read(module_header_size)
  259. for i in range(0, num_modules)]
  260. if all(hdr.startswith(b"$MME") for hdr in mod_headers):
  261. if args.keep_modules:
  262. end_addr = offset + ftpr_lenght
  263. else:
  264. end_addr = remove_modules(f, mod_headers,
  265. offset, me_end)
  266. if args.relocate:
  267. new_offset = relocate_partition(f, me_start, me_end,
  268. me_start + 0x30,
  269. min_offset + me_start,
  270. mod_headers)
  271. end_addr += new_offset - offset
  272. offset = new_offset
  273. return end_addr, offset
  274. else:
  275. print("Found less modules than expected in the FTPR "
  276. "partition; skipping modules removal")
  277. else:
  278. print("Can't find the module header size; skipping "
  279. "modules removal")
  280. return -1, offset
  281. def check_and_remove_modules_me11(f, me_start, me_end, partition_offset,
  282. partition_lenght, min_offset, relocate,
  283. keep_modules):
  284. comp_str = ("LZMA/uncomp.", "Huffman")
  285. if keep_modules:
  286. end_data = partition_offset + partition_lenght
  287. else:
  288. end_data = 0
  289. f.seek(partition_offset + 0x4)
  290. module_count = unpack("<I", f.read(4))[0]
  291. modules = []
  292. modules.append(("end", partition_lenght, 0))
  293. f.seek(partition_offset + 0x10)
  294. for i in range(0, module_count):
  295. data = f.read(0x18)
  296. name = data[0x0:0xc].rstrip(b"\x00").decode("ascii")
  297. offset_block = unpack("<I", data[0xc:0x10])[0]
  298. offset = offset_block & 0x01ffffff
  299. comp_type = (offset_block & 0x02000000) >> 25
  300. modules.append((name, offset, comp_type))
  301. modules.sort(key=lambda x: x[1])
  302. for i in range(0, module_count):
  303. name = modules[i][0]
  304. offset = partition_offset + modules[i][1]
  305. end = partition_offset + modules[i + 1][1]
  306. removed = False
  307. if name.endswith(".man") or name.endswith(".met"):
  308. compression = "uncompressed"
  309. else:
  310. compression = comp_str[modules[i][2]]
  311. sys.stdout.write(" {:<12} ({:<12}, 0x{:06x} - 0x{:06x}): "
  312. .format(name, compression, offset, end))
  313. if name.endswith(".man"):
  314. print("NOT removed, partition manif.")
  315. elif name.endswith(".met"):
  316. print("NOT removed, module metadata")
  317. elif any(name.startswith(m) for m in unremovable_modules_me11):
  318. print("NOT removed, essential")
  319. else:
  320. removed = True
  321. f.fill_range(offset, min(end, me_end), b"\xff")
  322. print("removed")
  323. if not removed:
  324. end_data = max(end_data, end)
  325. if relocate:
  326. new_offset = relocate_partition(f, me_start, me_end, me_start + 0x30,
  327. min_offset + me_start, [])
  328. end_data += new_offset - partition_offset
  329. partition_offset = new_offset
  330. return end_data, partition_offset
  331. def check_mn2_tag(f, offset):
  332. f.seek(offset + 0x1c)
  333. tag = f.read(4)
  334. if tag != b"$MN2":
  335. sys.exit("Wrong FTPR manifest tag ({}), this image may be corrupted"
  336. .format(tag))
  337. def flreg_to_start_end(flreg):
  338. return (flreg & 0x7fff) << 12, (flreg >> 4 & 0x7fff000 | 0xfff) + 1
  339. def start_end_to_flreg(start, end):
  340. return (start & 0x7fff000) >> 12 | ((end - 1) & 0x7fff000) << 4
  341. if __name__ == "__main__":
  342. parser = argparse.ArgumentParser(description="Tool to remove as much code "
  343. "as possible from Intel ME/TXE firmware "
  344. "images")
  345. softdis = parser.add_mutually_exclusive_group()
  346. parser.add_argument("file", help="ME/TXE image or full dump")
  347. parser.add_argument("-O", "--output", metavar='output_file', help="save "
  348. "the modified image in a separate file, instead of "
  349. "modifying the original file")
  350. softdis.add_argument("-S", "--soft-disable", help="in addition to the "
  351. "usual operations on the ME/TXE firmware, set the "
  352. "MeAltDisable bit or the HAP bit to ask Intel ME/TXE "
  353. "to disable itself after the hardware initialization "
  354. "(requires a full dump)", action="store_true")
  355. softdis.add_argument("-s", "--soft-disable-only", help="instead of the "
  356. "usual operations on the ME/TXE firmware, just set "
  357. "the MeAltDisable bit or the HAP bit to ask Intel "
  358. "ME/TXE to disable itself after the hardware "
  359. "initialization (requires a full dump)",
  360. action="store_true")
  361. parser.add_argument("-r", "--relocate", help="relocate the FTPR partition "
  362. "to the top of the ME region to save even more space",
  363. action="store_true")
  364. parser.add_argument("-k", "--keep-modules", help="don't remove the FTPR "
  365. "modules, even when possible", action="store_true")
  366. parser.add_argument("-d", "--descriptor", help="remove the ME/TXE "
  367. "Read/Write permissions to the other regions on the "
  368. "flash from the Intel Flash Descriptor (requires a "
  369. "full dump)", action="store_true")
  370. parser.add_argument("-t", "--truncate", help="truncate the empty part of "
  371. "the firmware (requires a separated ME/TXE image or "
  372. "--extract-me)", action="store_true")
  373. parser.add_argument("-c", "--check", help="verify the integrity of the "
  374. "fundamental parts of the firmware and exit",
  375. action="store_true")
  376. parser.add_argument("-D", "--extract-descriptor",
  377. metavar='output_descriptor', help="extract the flash "
  378. "descriptor from a full dump; when used with "
  379. "--truncate save a descriptor with adjusted regions "
  380. "start and end")
  381. parser.add_argument("-M", "--extract-me", metavar='output_me_image',
  382. help="extract the ME firmware from a full dump; when "
  383. "used with --truncate save a truncated ME/TXE image")
  384. args = parser.parse_args()
  385. if args.check and (args.soft_disable_only or args.soft_disable or \
  386. args.relocate or args.descriptor or args.truncate or args.output):
  387. sys.exit("-c can't be used with -S, -s, -r, -d, -t or -O")
  388. if args.soft_disable_only and (args.relocate or args.truncate):
  389. sys.exit("-s can't be used with -r or -t")
  390. f = open(args.file, "rb" if args.check or args.output else "r+b")
  391. f.seek(0x10)
  392. magic = f.read(4)
  393. if magic == b"$FPT":
  394. print("ME/TXE image detected")
  395. if args.descriptor or args.extract_descriptor or args.extract_me or \
  396. args.soft_disable or args.soft_disable_only:
  397. sys.exit("-d, -D, -M, -S and -s require a full dump")
  398. me_start = 0
  399. f.seek(0, 2)
  400. me_end = f.tell()
  401. elif magic == b"\x5a\xa5\xf0\x0f":
  402. print("Full image detected")
  403. if args.truncate and not args.extract_me:
  404. sys.exit("-t requires a separated ME/TXE image (or --extract-me)")
  405. f.seek(0x14)
  406. flmap0, flmap1 = unpack("<II", f.read(8))
  407. frba = flmap0 >> 12 & 0xff0
  408. fmba = (flmap1 & 0xff) << 4
  409. fpsba = flmap1 >> 12 & 0xff0
  410. f.seek(frba)
  411. flreg = unpack("<III", f.read(12))
  412. fd_start, fd_end = flreg_to_start_end(flreg[0])
  413. bios_start, bios_end = flreg_to_start_end(flreg[1])
  414. me_start, me_end = flreg_to_start_end(flreg[2])
  415. if me_start >= me_end:
  416. sys.exit("The ME/TXE region in this image has been disabled")
  417. f.seek(me_start + 0x10)
  418. if f.read(4) != b"$FPT":
  419. sys.exit("The ME/TXE region is corrupted or missing")
  420. print("The ME/TXE region goes from {:#x} to {:#x}"
  421. .format(me_start, me_end))
  422. else:
  423. sys.exit("Unknown image")
  424. end_addr = me_end
  425. print("Found FPT header at {:#x}".format(me_start + 0x10))
  426. f.seek(me_start + 0x14)
  427. entries = unpack("<I", f.read(4))[0]
  428. print("Found {} partition(s)".format(entries))
  429. f.seek(me_start + 0x14)
  430. header_len = unpack("B", f.read(1))[0]
  431. f.seek(me_start + 0x30)
  432. partitions = f.read(entries * 0x20)
  433. ftpr_header = b""
  434. for i in range(entries):
  435. if partitions[i * 0x20:(i * 0x20) + 4] == b"FTPR":
  436. ftpr_header = partitions[i * 0x20:(i + 1) * 0x20]
  437. break
  438. if ftpr_header == b"":
  439. sys.exit("FTPR header not found, this image doesn't seem to be valid")
  440. ftpr_offset, ftpr_lenght = unpack("<II", ftpr_header[0x08:0x10])
  441. ftpr_offset += me_start
  442. print("Found FTPR header: FTPR partition spans from {:#x} to {:#x}"
  443. .format(ftpr_offset, ftpr_offset + ftpr_lenght))
  444. f.seek(ftpr_offset)
  445. if f.read(4) == b"$CPD":
  446. me11 = True
  447. num_entries = unpack("<I", f.read(4))[0]
  448. f.seek(ftpr_offset + 0x10)
  449. ftpr_mn2_offset = -1
  450. for i in range(0, num_entries):
  451. data = f.read(0x18)
  452. name = data[0x0:0xc].rstrip(b"\x00").decode("ascii")
  453. offset = unpack("<I", data[0xc:0xf] + b"\x00")[0]
  454. if name == "FTPR.man":
  455. ftpr_mn2_offset = offset
  456. break
  457. if ftpr_mn2_offset >= 0:
  458. check_mn2_tag(f, ftpr_offset + ftpr_mn2_offset)
  459. print("Found FTPR manifest at {:#x}"
  460. .format(ftpr_offset + ftpr_mn2_offset))
  461. else:
  462. sys.exit("Can't find the manifest of the FTPR partition")
  463. else:
  464. check_mn2_tag(f, ftpr_offset)
  465. me11 = False
  466. ftpr_mn2_offset = 0
  467. f.seek(ftpr_offset + ftpr_mn2_offset + 0x24)
  468. version = unpack("<HHHH", f.read(0x08))
  469. print("ME/TXE firmware version {}"
  470. .format('.'.join(str(i) for i in version)))
  471. if not args.check and args.output:
  472. f.close()
  473. shutil.copy(args.file, args.output)
  474. f = open(args.output, "r+b")
  475. mef = RegionFile(f, me_start, me_end)
  476. if me_start > 0:
  477. fdf = RegionFile(f, fd_start, fd_end)
  478. if not args.check:
  479. if not args.soft_disable_only:
  480. print("Removing extra partitions...")
  481. mef.fill_range(me_start + 0x30, ftpr_offset, b"\xff")
  482. mef.fill_range(ftpr_offset + ftpr_lenght, me_end, b"\xff")
  483. print("Removing extra partition entries in FPT...")
  484. mef.write_to(me_start + 0x30, ftpr_header)
  485. mef.write_to(me_start + 0x14, pack("<I", 1))
  486. print("Removing EFFS presence flag...")
  487. mef.seek(me_start + 0x24)
  488. flags = unpack("<I", mef.read(4))[0]
  489. flags &= ~(0x00000001)
  490. mef.write_to(me_start + 0x24, pack("<I", flags))
  491. if me11:
  492. mef.seek(me_start + 0x10)
  493. header = bytearray(mef.read(0x20))
  494. header[0x0b] = 0x00
  495. else:
  496. mef.seek(me_start)
  497. header = bytearray(mef.read(0x30))
  498. header[0x1b] = 0x00
  499. checksum = (0x100 - sum(header) & 0xff) & 0xff
  500. print("Correcting checksum (0x{:02x})...".format(checksum))
  501. # The checksum is just the two's complement of the sum of the first
  502. # 0x30 bytes in ME < 11 or bytes 0x10:0x30 in ME >= 11 (except for
  503. # 0x1b, the checksum itself). In other words, the sum of those
  504. # bytes must be always 0x00.
  505. mef.write_to(me_start + 0x1b, pack("B", checksum))
  506. print("Reading FTPR modules list...")
  507. if me11:
  508. end_addr, ftpr_offset = \
  509. check_and_remove_modules_me11(mef, me_start, me_end,
  510. ftpr_offset, ftpr_lenght,
  511. min_ftpr_offset,
  512. args.relocate,
  513. args.keep_modules)
  514. else:
  515. end_addr, ftpr_offset = \
  516. check_and_remove_modules(mef, me_start, me_end, ftpr_offset,
  517. min_ftpr_offset, args.relocate,
  518. args.keep_modules)
  519. if end_addr > 0:
  520. end_addr = (end_addr // 0x1000 + 1) * 0x1000
  521. end_addr += spared_blocks * 0x1000
  522. print("The ME minimum size should be {0} bytes "
  523. "({0:#x} bytes)".format(end_addr - me_start))
  524. if me_start > 0:
  525. print("The ME region can be reduced up to:\n"
  526. " {:08x}:{:08x} me".format(me_start, end_addr - 1))
  527. elif args.truncate:
  528. print("Truncating file at {:#x}...".format(end_addr))
  529. f.truncate(end_addr)
  530. if args.soft_disable or args.soft_disable_only:
  531. if me11:
  532. print("Setting the HAP bit in PCHSTRP0 to disable Intel ME...")
  533. fdf.seek(fpsba)
  534. pchstrp0 = unpack("<I", fdf.read(4))[0]
  535. pchstrp0 |= (1 << 16)
  536. fdf.write_to(fpsba, pack("<I", pchstrp0))
  537. else:
  538. print("Setting the AltMeDisable bit in PCHSTRP10 to disable "
  539. "Intel ME...")
  540. fdf.seek(fpsba + 0x28)
  541. pchstrp10 = unpack("<I", fdf.read(4))[0]
  542. pchstrp10 |= (1 << 7)
  543. fdf.write_to(fpsba + 0x28, pack("<I", pchstrp10))
  544. if args.descriptor:
  545. print("Removing ME/TXE R/W access to the other flash regions...")
  546. fdf.write_to(fmba + 0x4, pack("<I", 0x04040000))
  547. if args.extract_descriptor:
  548. if args.truncate:
  549. print("Extracting the descriptor to \"{}\"..."
  550. .format(args.extract_descriptor))
  551. fdf_copy = fdf.save(args.extract_descriptor, fd_end - fd_start)
  552. if bios_start == me_end:
  553. print("Modifying the regions of the extracted descriptor...")
  554. print(" {:08x}:{:08x} me --> {:08x}:{:08x} me"
  555. .format(me_start, me_end - 1, me_start, end_addr - 1))
  556. print(" {:08x}:{:08x} bios --> {:08x}:{:08x} bios"
  557. .format(bios_start, bios_end - 1, end_addr, bios_end - 1))
  558. flreg1 = start_end_to_flreg(end_addr, bios_end)
  559. flreg2 = start_end_to_flreg(me_start, end_addr)
  560. fdf_copy.seek(frba + 0x4)
  561. fdf_copy.write(pack("<II", flreg1, flreg2))
  562. else:
  563. print("\nWARNING:\n The start address of the BIOS region "
  564. "isn't equal to the end address of the ME\n region: if "
  565. "you want to recover the space from the ME region you "
  566. "have to\n manually modify the descriptor.\n")
  567. else:
  568. print("Extracting the descriptor to \"{}\"..."
  569. .format(args.extract_descriptor))
  570. fdf_copy = fdf.save(args.extract_descriptor, fd_end - fd_start)
  571. fdf_copy.close()
  572. if args.extract_me:
  573. if args.truncate:
  574. print("Extracting and truncating the ME image to \"{}\"..."
  575. .format(args.extract_me))
  576. mef_copy = mef.save(args.extract_me, end_addr - me_start)
  577. else:
  578. print("Extracting the ME image to \"{}\"..."
  579. .format(args.extract_me))
  580. mef_copy = mef.save(args.extract_me, me_end - me_start)
  581. sys.stdout.write("Checking the FTPR RSA signature of the extracted ME "
  582. "image... ")
  583. print_check_partition_signature(mef_copy, ftpr_offset +
  584. ftpr_mn2_offset - me_start)
  585. mef_copy.close()
  586. sys.stdout.write("Checking the FTPR RSA signature... ")
  587. print_check_partition_signature(f, ftpr_offset + ftpr_mn2_offset)
  588. f.close()
  589. if not args.check:
  590. print("Done! Good luck!")