#!/usr/bin/python # me_cleaner - Tool for partial deblobbing of Intel ME/TXE firmware images # Copyright (C) 2016, 2017 Nicola Corna # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # import sys import itertools import binascii import hashlib import argparse import shutil from struct import pack, unpack min_ftpr_offset = 0x400 spared_blocks = 4 unremovable_modules = ("ROMP", "BUP") unremovable_modules_me11 = ("rbe", "kernel", "syslib", "bup") class OutOfRegionException(Exception): pass class RegionFile: def __init__(self, f, region_start, region_end): self.f = f self.region_start = region_start self.region_end = region_end def read(self, n): return self.f.read(n) def readinto(self, b): return self.f.readinto(b) def seek(self, offset): return self.f.seek(offset) def write_to(self, offset, data): if offset >= self.region_start and \ offset + len(data) <= self.region_end: self.f.seek(offset) return self.f.write(data) else: raise OutOfRegionException() def fill_range(self, start, end, fill): if start >= self.region_start and end <= self.region_end: if start < end: block = fill * 4096 self.f.seek(start) self.f.writelines(itertools.repeat(block, (end - start) // 4096)) self.f.write(block[:(end - start) % 4096]) else: raise OutOfRegionException() def move_range(self, offset_from, size, offset_to, fill): if offset_from >= self.region_start and \ offset_from + size <= self.region_end and \ offset_to >= self.region_start and \ offset_to + size <= self.region_end: for i in range(0, size, 4096): self.f.seek(offset_from + i, 0) block = self.f.read(4096 if size - i >= 4096 else size - i) self.f.seek(offset_from + i, 0) self.f.write(fill * len(block)) self.f.seek(offset_to + i, 0) self.f.write(block) else: raise OutOfRegionException() def save(self, filename, size): self.f.seek(self.region_start) copyf = open(filename, "w+b") for i in range(0, size, 4096): copyf.write(self.f.read(4096 if size - i >= 4096 else size - i)) return copyf def get_chunks_offsets(llut, me_start): chunk_count = unpack("> 4) & 7 sys.stdout.write(" {:<16} ({:<7}, ".format(name, comp_str[comp_type])) if comp_type == 0x00 or comp_type == 0x02: sys.stdout.write("0x{:06x} - 0x{:06x}): " .format(offset, offset + size)) if name in unremovable_modules: end_addr = max(end_addr, offset + size) print("NOT removed, essential") else: end = min(offset + size, me_end) f.fill_range(offset, end, b"\xff") print("removed") elif comp_type == 0x01: sys.stdout.write("fragmented data ): ") if not chunks_offsets: f.seek(offset) llut = f.read(4) if llut == b"LLUT": llut += f.read(0x3c) chunk_count = unpack(" removable_chunk[0]: end = min(removable_chunk[1], me_end) f.fill_range(removable_chunk[0], end, b"\xff") end_addr = max(end_addr, max(unremovable_huff_chunks, key=lambda x: x[1])[1]) return end_addr def check_partition_signature(f, offset): f.seek(offset) header = f.read(0x80) modulus = int(binascii.hexlify(f.read(0x100)[::-1]), 16) public_exponent = unpack("> 4) & 7 == 0x01: llut_start = unpack("> 25 modules.append((name, offset, comp_type)) modules.sort(key=lambda x: x[1]) for i in range(0, module_count): name = modules[i][0] offset = partition_offset + modules[i][1] end = partition_offset + modules[i + 1][1] removed = False if name.endswith(".man") or name.endswith(".met"): compression = "uncompressed" else: compression = comp_str[modules[i][2]] sys.stdout.write(" {:<12} ({:<12}, 0x{:06x} - 0x{:06x}): " .format(name, compression, offset, end)) if name.endswith(".man"): print("NOT removed, partition manif.") elif name.endswith(".met"): print("NOT removed, module metadata") elif any(name.startswith(m) for m in unremovable_modules_me11): print("NOT removed, essential") else: removed = True f.fill_range(offset, min(end, me_end), b"\xff") print("removed") if not removed: end_data = max(end_data, end) if relocate: new_offset = relocate_partition(f, me_start, me_end, me_start + 0x30, min_offset + me_start, []) end_data += new_offset - partition_offset partition_offset = new_offset return end_data, partition_offset def check_mn2_tag(f, offset): f.seek(offset + 0x1c) tag = f.read(4) if tag != b"$MN2": sys.exit("Wrong FTPR manifest tag ({}), this image may be corrupted" .format(tag)) def flreg_to_start_end(flreg): return (flreg & 0x7fff) << 12, (flreg >> 4 & 0x7fff000 | 0xfff) + 1 def start_end_to_flreg(start, end): return (start & 0x7fff000) >> 12 | ((end - 1) & 0x7fff000) << 4 if __name__ == "__main__": parser = argparse.ArgumentParser(description="Tool to remove as much code " "as possible from Intel ME/TXE firmware " "images") parser.add_argument("file", help="ME/TXE image or full dump") parser.add_argument("-O", "--output", help="save the modified image in a " "separate file, instead of modifying the original " "file") parser.add_argument("-r", "--relocate", help="relocate the FTPR partition " "to the top of the ME region to save even more space", action="store_true") parser.add_argument("-k", "--keep-modules", help="don't remove the FTPR " "modules, even when possible", action="store_true") parser.add_argument("-d", "--descriptor", help="remove the ME/TXE " "Read/Write permissions to the other regions on the " "flash from the Intel Flash Descriptor (requires a " "full dump)", action="store_true") parser.add_argument("-t", "--truncate", help="truncate the empty part of " "the firmware (requires a separated ME/TXE image or " "--extract-me)", action="store_true") parser.add_argument("-c", "--check", help="verify the integrity of the " "fundamental parts of the firmware and exit", action="store_true") parser.add_argument("-D", "--extract-descriptor", help="extract the " "flash descriptor from a full dump; when used with " "--truncate save a descriptor with adjusted regions " "start and end") parser.add_argument("-M", "--extract-me", help="extract the ME firmware " "from a full dump; when used with --truncate save a " "truncated ME/TXE image") args = parser.parse_args() if args.check: if args.relocate: sys.exit("-c and -r can't be used together") elif args.truncate: sys.exit("-c and -t can't be used together") f = open(args.file, "rb" if args.check or args.output else "r+b") f.seek(0x10) magic = f.read(4) if magic == b"$FPT": print("ME/TXE image detected") if args.descriptor: sys.exit("-d requires a full dump") if args.extract_descriptor: sys.exit("-D requires a full dump") if args.extract_me: sys.exit("-M requires a full dump") me_start = 0 f.seek(0, 2) me_end = f.tell() elif magic == b"\x5a\xa5\xf0\x0f": print("Full image detected") if args.truncate and not args.extract_me: sys.exit("-t requires a separated ME/TXE image (or --extract-me)") f.seek(0x14) flmap0, flmap1 = unpack("> 12 & 0xff0 fmba = (flmap1 & 0xff) << 4 f.seek(frba) flreg = unpack("= me_end: sys.exit("The ME/TXE region in this image has been disabled") f.seek(me_start + 0x10) if f.read(4) != b"$FPT": sys.exit("The ME/TXE region is corrupted or missing") print("The ME/TXE region goes from {:#x} to {:#x}" .format(me_start, me_end)) else: sys.exit("Unknown image") print("Found FPT header at {:#x}".format(me_start + 0x10)) f.seek(me_start + 0x14) entries = unpack("= 0: check_mn2_tag(f, ftpr_offset + ftpr_mn2_offset) print("Found FTPR manifest at {:#x}" .format(ftpr_offset + ftpr_mn2_offset)) else: sys.exit("Can't find the manifest of the FTPR partition") else: check_mn2_tag(f, ftpr_offset) me11 = False ftpr_mn2_offset = 0 f.seek(ftpr_offset + ftpr_mn2_offset + 0x24) version = unpack("= 11 (except for # 0x1b, the checksum itself). In other words, the sum of those bytes # must be always 0x00. mef.write_to(me_start + 0x1b, pack("B", checksum)) print("Reading FTPR modules list...") if me11: end_addr, ftpr_offset = \ check_and_remove_modules_me11(mef, me_start, me_end, ftpr_offset, ftpr_lenght, min_ftpr_offset, args.relocate, args.keep_modules) else: end_addr, ftpr_offset = \ check_and_remove_modules(mef, me_start, me_end, ftpr_offset, min_ftpr_offset, args.relocate, args.keep_modules) if end_addr > 0: end_addr = (end_addr // 0x1000 + 1) * 0x1000 end_addr += spared_blocks * 0x1000 print("The ME minimum size should be {0} bytes " "({0:#x} bytes)".format(end_addr - me_start)) if me_start > 0: print("The ME region can be reduced up to:\n" " {:08x}:{:08x} me".format(me_start, end_addr - 1)) elif args.truncate: print("Truncating file at {:#x}...".format(end_addr)) f.truncate(end_addr) if args.descriptor: print("Removing ME/TXE R/W access to the other flash regions...") fdf.write_to(fmba + 0x4, pack(" {:08x}:{:08x} me" .format(me_start, me_end - 1, me_start, end_addr - 1)) print(" {:08x}:{:08x} bios --> {:08x}:{:08x} bios" .format(bios_start, bios_end - 1, end_addr, bios_end - 1)) flreg1 = start_end_to_flreg(end_addr, bios_end) flreg2 = start_end_to_flreg(me_start, end_addr) fdf_copy.seek(frba + 0x4) fdf_copy.write(pack("