def decode_rom(self): _uefi = UEFI(self.cs) self.logger.log( "[CHIPSEC] Decoding SPI ROM image from a file '{}'".format( self._rom)) f = read_file(self._rom) if not f: return False (fd_off, fd) = get_spi_flash_descriptor(f) if (-1 == fd_off) or (fd is None): self.logger.error( "Could not find SPI Flash descriptor in the binary '{}'". format(self._rom)) self.logger.log_information( "To decode an image without a flash decriptor try chipsec_util uefi decode" ) return False self.logger.log( "[CHIPSEC] Found SPI Flash descriptor at offset 0x{:X} in the binary '{}'" .format(fd_off, self._rom)) rom = f[fd_off:] # Decoding SPI Flash Regions flregs = get_spi_regions(fd) if flregs is None: self.logger.error("SPI Flash descriptor region is not valid") self.logger.log_information( "To decode an image with an invalid flash decriptor try chipsec_util uefi decode" ) return False _orig_logname = self.logger.LOG_FILE_NAME pth = os.path.join(self.cs.helper.getcwd(), self._rom + ".dir") if not os.path.exists(pth): os.makedirs(pth) for r in flregs: idx = r[0] name = r[1] base = r[3] limit = r[4] notused = r[5] if not notused: region_data = rom[base:limit + 1] fname = os.path.join( pth, '{:d}_{:04X}-{:04X}_{}.bin'.format(idx, base, limit, name)) write_file(fname, region_data) if FLASH_DESCRIPTOR == idx: # Decoding Flash Descriptor self.logger.set_log_file(os.path.join(pth, fname + '.log')) parse_spi_flash_descriptor(self.cs, region_data) elif BIOS == idx: # Decoding EFI Firmware Volumes self.logger.set_log_file(os.path.join(pth, fname + '.log')) decode_uefi_region(_uefi, pth, fname, self._fwtype) self.logger.set_log_file(_orig_logname)
def vmem_write(self): if not os.path.exists(self.buf_file): try: buffer = bytearray.fromhex(self.buf_file) except ValueError as e: self.logger.error("Incorrect <value> specified: '{}'".format( self.buf_file)) self.logger.error(str(e)) return self.logger.log( "[CHIPSEC] Read 0x{:X} hex bytes from command-line: {}'". format(len(buffer), self.buf_file)) else: buffer = read_file(self.buf_file) self.logger.log( "[CHIPSEC] Read 0x{:X} bytes from file '{}'".format( len(buffer), self.buf_file)) if len(buffer) < self.size: self.logger.error( "Number of bytes read (0x{:X}) is less than the specified <length> (0x{:X})" .format(len(buffer), self.size)) return self.logger.log( '[CHIPSEC] Writing buffer to memory: VA = 0x{:016X}, len = 0x{:X}.' .format(self.virt_address, self.size)) self._vmem.write_virtual_mem(self.virt_address, self.size, buffer)
def parse_uefi_region_from_file(_uefi, filename, fwtype, outpath=None, filetype=[]): # Create an output folder to dump EFI module tree if outpath is None: outpath = "{}.dir".format(filename) if not os.path.exists(outpath): os.makedirs(outpath) # Read UEFI image binary to parse rom = read_file(filename) # Parse UEFI image binary and build a tree hierarchy of EFI modules tree = build_efi_model(_uefi, rom, fwtype) # Save entire EFI module hierarchy on a file-system and export into JSON if filetype: tree_json = save_efi_tree_filetype(tree, path=outpath, filetype=filetype) else: tree_json = save_efi_tree(_uefi, tree, path=outpath) write_file( "{}.UEFI.json".format(filename), json.dumps(tree_json, indent=2, separators=(',', ': '), cls=UUIDEncoder))
def get_ACPI_table(self, name, isfile=False): acpi_tables_data = [] if isfile: acpi_tables_data.append(read_file(name)) else: try: # 1. Try to extract ACPI table(s) from physical memory # read_physical_mem can be implemented using both # CHIPSEC kernel module and OS native API if logger().HAL: logger().log( "[acpi] trying to extract ACPI table from physical memory..." ) for table_address in self.tableList[name]: t_size = self.cs.mem.read_physical_mem_dword( table_address + 4) t_data = self.cs.mem.read_physical_mem( table_address, t_size) acpi_tables_data.append(t_data) except UnimplementedNativeAPIError: # 2. If didn't work, try using get_ACPI_table if a helper implemented # reading ACPI tables via native API which some OS may provide if logger().HAL: logger().log( "[acpi] trying to extract ACPI table using get_ACPI_table..." ) t_data = self.cs.helper.get_ACPI_table(name) acpi_tables_data.append(t_data) acpi_tables = [] for data in acpi_tables_data: acpi_tables.append( (data[:ACPI_TABLE_HEADER_SIZE], data[ACPI_TABLE_HEADER_SIZE:])) return acpi_tables
def read_EFI_variables_from_file( self, filename ): rom = read_file( filename ) efi_var_store = self.find_EFI_variable_store( rom ) if efi_var_store: efi_vars = uefi_platform.EFI_VAR_DICT[ self._FWType ]['func_getefivariables'] return efi_vars return efi_var_store
def write_dma(self): if not os.path.exists(self.file_value): buffer_value = self.file_value.lower().strip('0x') try: buffer = bytearray.fromhex(buffer_value) except ValueError as e: self.logger.error("Incorrect <value> specified: '{}'".format( self.file_value)) self.logger.error(str(e)) return self.logger.log( "[CHIPSEC] Read 0x{:X} hex bytes from command-line: {}'". format(len(buffer), buffer_value)) else: buffer = read_file(self.file_value) self.logger.log( "[CHIPSEC] Read 0x{:X} bytes from file '{}'".format( len(buffer), self.file_value)) if len(buffer) < self.size: self.logger.error( "Number of bytes read (0x{:X}) is less than the specified <length> (0x{:X})" .format(len(buffer), self.size)) return self.logger.log( '[CHIPSEC] Writing buffer to memory: PA = 0x{:016X}, len = 0x{:X}..' .format(self.address, self.size)) self.cs.igd.gfx_aperture_dma_read_write(self.address, self.size, buffer)
def decode_uefi_region(_uefi, pth, fname, fwtype, filetype=[]): bios_pth = os.path.join(pth, fname + '.dir') if not os.path.exists(bios_pth): os.makedirs(bios_pth) fv_pth = os.path.join(bios_pth, 'FV') if not os.path.exists(fv_pth): os.makedirs(fv_pth) # Decoding UEFI Firmware Volumes if logger().HAL: logger().log("[spi_uefi] decoding UEFI firmware volumes...") parse_uefi_region_from_file(_uefi, fname, fwtype, fv_pth, filetype) # If a specific filetype is wanted, there is no need to check for EFI Variables if filetype: return # Decoding EFI Variables NVRAM if logger().HAL: logger().log("[spi_uefi] decoding UEFI NVRAM...") region_data = read_file(fname) if fwtype is None: fwtype = identify_EFI_NVRAM(region_data) if fwtype is None: return elif fwtype not in fw_types: if logger().HAL: logger().error("unrecognized NVRAM type {}".format(fwtype)) return nvram_fname = os.path.join(bios_pth, ('nvram_{}'.format(fwtype))) logger().set_log_file((nvram_fname + '.nvram.lst')) _uefi.parse_EFI_variables(nvram_fname, region_data, False, fwtype)
def run(self, module_argv): self.logger.start_test( "Check for black-listed EFI binaries in UEFI firmware") self.usage() image_file = DEF_FWIMAGE_FILE if len(module_argv) == 0: # Read firmware image directly from SPI flash memory self.spi = SPI(self.cs) (base, limit, freg) = self.spi.get_SPI_region(BIOS) image_size = limit + 1 - base self.logger.log( "[*] dumping FW image from ROM to {}: 0x{:08X} bytes at [0x{:08X}:0x{:08X}]" .format(image_file, base, limit, image_size)) self.logger.log( "[*] this may take a few minutes (instead, use 'chipsec_util spi dump')..." ) self.spi.read_spi_to_file(base, image_size, image_file) elif len(module_argv) > 0: # Use provided firmware image image_file = module_argv[0] self.logger.log( "[*] reading FW image from file: {}".format(image_file)) self.image = read_file(image_file) # Load JSON config with black-listed EFI modules if len(module_argv) > 1: self.cfg_name = module_argv[1] cfg_pth = os.path.join(get_main_dir(), "chipsec/modules/tools/uefi", self.cfg_name) with open(cfg_pth, 'r') as blacklist_json: self.efi_blacklist = json.load(blacklist_json) return self.check_blacklist()
def mem_write(self): if not os.path.exists(self.buffer_data): try: buffer = bytearray.fromhex(self.buffer_data) except ValueError: self.logger.error("Incorrect <value> specified: '{}'".format( self.buffer_data)) return self.logger.log( "[CHIPSEC] Read 0x{:X} hex bytes from command-line: '{}'". format(len(buffer), self.buffer_data)) else: buffer = read_file(self.buffer_data) self.logger.log( "[CHIPSEC] Read 0x{:X} bytes from file '{}'".format( len(buffer), self.buffer_data)) if len(buffer) < self.buffer_length: self.logger.error( "Number of bytes read (0x{:X}) is less than the specified <length> (0x{:X})" .format(len(buffer), self.buffer_length)) return self.logger.log( '[CHIPSEC] writing buffer to memory: PA = 0x{:016X}, len = 0x{:X}..' .format(self.phys_address, self.buffer_length)) self.cs.mem.write_physical_mem(self.phys_address, self.buffer_length, buffer)
def assemble(self): compression = {'none': 0, 'tiano': 1, 'lzma': 2} if get_guid_bin(self.guid) == '': print('*** Error *** Invalid GUID: {}'.format(self.guid)) return if not os.path.isfile(self.raw_file): print('*** Error *** File doesn\'t exist: {}'.format( self.raw_file)) return if self.comp not in compression: print('*** Error *** Unknown compression: {}'.format(self.comp)) return compression_type = compression[self.comp] if self.file_type == 'freeform': raw_image = read_file(self.raw_file) wrap_image = assemble_uefi_raw(raw_image) if compression_type > 0: comp_image = compress_image(self._uefi, wrap_image, compression_type) wrap_image = assemble_uefi_section(comp_image, len(wrap_image), compression_type) uefi_image = assemble_uefi_file(self.guid, wrap_image) write_file(self.efi_file, uefi_image) else: print('*** Error *** Unknow file type: {}'.format(self.file_type)) return self.logger.log( "[CHIPSEC] UEFI file was successfully assembled! Binary file size: {:d}, compressed UEFI file size: {:d}" .format(len(raw_image), len(uefi_image)))
def run(self, module_argv): self.logger.start_test( "Check for suspicious EFI binaries in UEFI firmware") self.usage() if len(module_argv) > 0: self.vt = VirusTotalPublicApi(module_argv[0]) if len(module_argv) > 1: self.vt_threshold = int(module_argv[1]) image_file = DEF_FWIMAGE_FILE if len(module_argv) > 2: # Use provided firmware image image_file = module_argv[2] self.logger.log( "[*] reading FW image from file: {}".format(image_file)) else: # Read firmware image directly from SPI flash memory self.spi = SPI(self.cs) (base, limit, freg) = self.spi.get_SPI_region(BIOS) image_size = limit + 1 - base self.logger.log( "[*] dumping FW image from ROM to {}: 0x{:08X} bytes at [0x{:08X}:0x{:08X}]" .format(image_file, base, limit, image_size)) self.logger.log( "[*] this may take a few minutes (instead, use 'chipsec_util spi dump')..." ) self.spi.read_spi_to_file(base, image_size, image_file) self.image = read_file(image_file) return self.check_reputation()
def run(self): if len(self.argv) < 3: print(UCodeCommand.__doc__) return ucode_op = self.argv[2] t = time.time() if ('load' == ucode_op): if (4 == len(self.argv)): ucode_filename = self.argv[3] self.logger.log( "[CHIPSEC] Loading Microcode update on all cores from '{}'" .format(ucode_filename)) self.cs.ucode.update_ucode_all_cpus(ucode_filename) elif (5 == len(self.argv)): ucode_filename = self.argv[3] cpu_thread_id = int(self.argv[4], 16) self.logger.log( "[CHIPSEC] Loading Microcode update on CPU{:d} from '{}'". format(cpu_thread_id, ucode_filename)) self.cs.ucode.update_ucode(cpu_thread_id, ucode_filename) else: print(UCodeCommand.__doc__) return elif ('decode' == ucode_op): if (4 == len(self.argv)): ucode_filename = self.argv[3] if (not ucode_filename.endswith('.pdb')): self.logger.log( "[CHIPSEC] Ucode update file is not PDB file: '{}'". format(ucode_filename)) return pdb_ucode_buffer = read_file(ucode_filename) self.logger.log( "[CHIPSEC] Decoding Microcode Update header of PDB file: '{}'" .format(ucode_filename)) dump_ucode_update_header(pdb_ucode_buffer) elif ('id' == ucode_op): if (3 == len(self.argv)): for tid in range(self.cs.msr.get_cpu_thread_count()): ucode_update_id = self.cs.ucode.ucode_update_id(tid) self.logger.log( "[CHIPSEC] CPU{:d}: Microcode update ID = 0x{:08X}". format(tid, ucode_update_id)) elif (4 == len(self.argv)): cpu_thread_id = int(self.argv[3], 16) ucode_update_id = self.cs.ucode.ucode_update_id(cpu_thread_id) self.logger.log( "[CHIPSEC] CPU{:d}: Microcode update ID = 0x{:08X}".format( cpu_thread_id, ucode_update_id)) else: self.logger.error( "unknown command-line option '{:32}'".format(ucode_op)) print(UCodeCommand.__doc__) return self.logger.log( "[CHIPSEC] (ucode) time elapsed {:.3f}".format(time.time() - t))
def replace(self): if get_guid_bin(self.guid) == '': print ('*** Error *** Invalid GUID: {}'.format(self.guid)) return if not os.path.isfile(self.rom_file): print ('*** Error *** File doesn\'t exist: {}'.format(self.rom_file)) return if not os.path.isfile(self.efi_file): print ('*** Error *** File doesn\'t exist: {}'.format(self.efi_file)) return rom_image = read_file(self.rom_file) efi_image = read_file(self.efi_file) new_image = modify_uefi_region(rom_image, CMD_UEFI_FILE_REPLACE, self.guid, efi_image) write_file(self.new_file, new_image)
def run(self, module_argv): self.logger.start_test( "simple list generation/checking for (U)EFI firmware") self.res = ModuleResult.SKIPPED op = module_argv[0] if len(module_argv) > 0 else 'generate' if op in ['generate', 'check']: if len(module_argv) <= 2: self.usage() return self.res elif len(module_argv) > 2: json_file = module_argv[1] image_file = module_argv[2] self.logger.log( "[*] reading firmware from '{}'...".format(image_file)) else: image_file = DEF_FWIMAGE_FILE json_file = DEF_EFILIST_FILE self.spi = SPI(self.cs) (base, limit, freg) = self.spi.get_SPI_region(BIOS) image_size = limit + 1 - base self.logger.log( "[*] dumping firmware image from ROM to '{}': 0x{:08X} bytes at [0x{:08X}:0x{:08X}]" .format(image_file, image_size, base, limit)) self.spi.read_spi_to_file(base, image_size, image_file) self.image_file = image_file self.image = read_file(image_file) json_pth = os.path.abspath(json_file) if op == 'generate': if os.path.exists(json_pth): self.logger.error( "JSON file '{}' already exists. Exiting...".format( json_file)) self.res = ModuleResult.ERROR else: self.res = self.generate_efilist(json_pth) elif op == 'check': if not os.path.exists(json_pth): self.logger.error( "JSON file '{}' doesn't exists. Exiting...".format( json_file)) self.res = ModuleResult.ERROR else: self.res = self.check_list(json_pth) elif op == 'help': self.usage() else: self.logger.error( "unrecognized command-line argument to the module") self.usage() return self.res
def parse_efivar_file( fname, var=None ): if not var: var = read_file( fname ) #path, var_name = os.path.split( fname ) #var_name, ext = os.path.splitext( var_name ) var_path = fname + '.dir' if not os.path.exists( var_path ): os.makedirs( var_path ) parse_db( var, var_path )
def parse_efivar_file(fname, var=None): if not var: var = read_file(fname) #path, var_name = os.path.split( fname ) #var_name, ext = os.path.splitext( var_name ) var_path = fname + '.dir' if not os.path.exists(var_path): os.makedirs(var_path) parse_db(var, var_path)
def compress_EFI_binary( self, uncompressed_name, compressed_name, compression_type ): if logger().HAL: logger().log( "[uefi] compressing EFI binary (type = 0x{:X})\n {} ->\n {}".format(compression_type,uncompressed_name,compressed_name) ) if compression_type in COMPRESSION_TYPES: if self.cs.helper.compress_file( uncompressed_name, compressed_name, compression_type ): return read_file(compressed_name) else: return None else: logger().error( 'Unknown EFI compression type 0x{:X}'.format(compression_type) ) return None
def set_EFI_variable_from_file(self, name, guid, filename, datasize=None, attrs=None): if filename is None: logger().error('File with EFI variable is not specified') return False var = read_file(filename) return self.set_EFI_variable(name, guid, var, datasize, attrs)
def ucode_decode(self): if (not self.ucode_filename.endswith('.pdb')): self.logger.log( "[CHIPSEC] Ucode update file is not PDB file: '{}'".format( self.ucode_filename)) return pdb_ucode_buffer = read_file(self.ucode_filename) self.logger.log( "[CHIPSEC] Decoding Microcode Update header of PDB file: '{}'". format(self.ucode_filename)) dump_ucode_update_header(pdb_ucode_buffer)
def read_ucode_file(ucode_filename): ucode_buf = read_file(ucode_filename) if (ucode_filename.endswith('.pdb')): if logger().HAL: logger().log( "[ucode] PDB file '{:256}' has ucode update header (size = 0x{:X})" .format(ucode_filename, UCODE_HEADER_SIZE)) dump_ucode_update_header(ucode_buf) return ucode_buf[UCODE_HEADER_SIZE:] else: return ucode_buf
def run(self): if len(self.argv) < 3: print SPIDescCommand.__doc__ return fd_file = self.argv[2] self.logger.log( "[CHIPSEC] Parsing SPI Flash Descriptor from file '%s'\n" % fd_file ) t = time.time() fd = read_file( fd_file ) if type(fd) == str: parse_spi_flash_descriptor( fd ) self.logger.log( "\n[CHIPSEC] (spidesc) time elapsed %.3f" % (time.time()-t) )
def run(self): t = time.time() self.logger.log( "[CHIPSEC] Parsing SPI Flash Descriptor from file '{}'\n".format( self.fd_file)) fd = read_file(self.fd_file) if fd: parse_spi_flash_descriptor(self.cs, fd) self.logger.log( "\n[CHIPSEC] (spidesc) time elapsed {:.3f}".format(time.time() - t))
def run(self): if len(self.argv) < 3: print SPIDescCommand.__doc__ return fd_file = self.argv[2] self.logger.log( "[CHIPSEC] Parsing SPI Flash Descriptor from file '%s'\n" % fd_file) t = time.time() fd = read_file(fd_file) if type(fd) == str: parse_spi_flash_descriptor(fd) self.logger.log("\n[CHIPSEC] (spidesc) time elapsed %.3f" % (time.time() - t))
def parse_efivar_file(fname, var=None, var_type=SECURE_BOOT_SIG_VAR): logger().log('Processing certs in file: {}'.format(fname)) if not var: var = read_file( fname ) var_path = fname + '.dir' if not os.path.exists( var_path ): os.makedirs( var_path ) if var_type == SECURE_BOOT_SIG_VAR: parse_sb_db(var, var_path) elif var_type == AUTH_SIG_VAR: parse_auth_var(var, var_path) elif var_type == ESAL_SIG_VAR: parse_esal_var(var, var_path) else: logger().warn('Unsupported variable type requested: {}'.format(var_type))
def nvram_auth(self): authvars = 1 rom = read_file( self.romfilename ) if self.fwtype is None: self.fwtype = identify_EFI_NVRAM( rom ) if self.fwtype is None: self.logger.error( "Could not automatically identify EFI NVRAM type" ) return elif self.fwtype not in fw_types: self.logger.error( "Unrecognized EFI NVRAM type '{}'".format(self.fwtype) ) return _orig_logname = self.logger.LOG_FILE_NAME self.logger.set_log_file( (self.romfilename + '.nv.lst') ) self._uefi.parse_EFI_variables( self.romfilename, rom, authvars, self.fwtype ) self.logger.set_log_file( _orig_logname )
def run(self): if len(self.argv) < 3: print(SPIDescCommand.__doc__) return fd_file = self.argv[2] self.logger.log( "[CHIPSEC] Parsing SPI Flash Descriptor from file '{}'\n".format( fd_file)) t = time.time() fd = read_file(fd_file) parse_spi_flash_descriptor(self.cs, fd) self.logger.log( "\n[CHIPSEC] (spidesc) time elapsed {:.3f}".format(time.time() - t))
def run(self, module_argv): self.logger.start_test( "Check for blocked EFI binaries in UEFI firmware") self.usage() image_file = DEF_FWIMAGE_FILE if len(module_argv) == 0: # Read firmware image directly from SPI flash memory self.spi = SPI(self.cs) (base, limit, freg) = self.spi.get_SPI_region(BIOS) image_size = limit + 1 - base self.logger.log( "[*] Dumping FW image from ROM to {}: 0x{:08X} bytes at [0x{:08X}:0x{:08X}]" .format(image_file, base, limit, image_size)) self.logger.log( "[*] This may take a few minutes (instead, use 'chipsec_util spi dump')..." ) self.spi.read_spi_to_file(base, image_size, image_file) elif len(module_argv) > 0: # Use provided firmware image image_file = module_argv[0] self.logger.log( "[*] Reading FW image from file: {}".format(image_file)) self.image = read_file(image_file) if not self.image: if len(module_argv) == 0: self.logger.log_important( 'Unable to read SPI and generate FW image. Access may be blocked.' ) self.logger.error('No FW image file to read. Exiting!') self.res = ModuleResult.ERROR return self.res # Load JSON config with blocked EFI modules if len(module_argv) > 1: self.cfg_name = module_argv[1] cfg_pth = os.path.join(get_main_dir(), "chipsec/modules/tools/uefi", self.cfg_name) with open(cfg_pth, 'r') as blockedlist_json: self.efi_blockedlist = json.load(blockedlist_json) self.res = self.check_blockedlist() return self.res
def run(self): if len(self.argv) < 3: print UCodeCommand.__doc__ return ucode_op = self.argv[2] t = time.time() if ( 'load' == ucode_op ): if (4 == len(self.argv)): ucode_filename = self.argv[3] self.logger.log( "[CHIPSEC] Loading Microcode update on all cores from '%s'" % ucode_filename ) self.cs.ucode.update_ucode_all_cpus( ucode_filename ) elif (5 == len(self.argv)): ucode_filename = self.argv[3] cpu_thread_id = int(self.argv[4],16) self.logger.log( "[CHIPSEC] Loading Microcode update on CPU%d from '%s'" % (cpu_thread_id, ucode_filename) ) self.cs.ucode.update_ucode( cpu_thread_id, ucode_filename ) else: print UCodeCommand.__doc__ return elif ( 'decode' == ucode_op ): if (4 == len(self.argv)): ucode_filename = self.argv[3] if (not ucode_filename.endswith('.pdb')): self.logger.log( "[CHIPSEC] Ucode update file is not PDB file: '%s'" % ucode_filename ) return pdb_ucode_buffer = read_file( ucode_filename ) self.logger.log( "[CHIPSEC] Decoding Microcode Update header of PDB file: '%s'" % ucode_filename ) dump_ucode_update_header( pdb_ucode_buffer ) elif ( 'id' == ucode_op ): if (3 == len(self.argv)): for tid in range(self.cs.msr.get_cpu_thread_count()): ucode_update_id = self.cs.ucode.ucode_update_id( tid ) self.logger.log( "[CHIPSEC] CPU%d: Microcode update ID = 0x%08X" % (tid, ucode_update_id) ) elif (4 == len(self.argv)): cpu_thread_id = int(self.argv[3],16) ucode_update_id = self.cs.ucode.ucode_update_id( cpu_thread_id ) self.logger.log( "[CHIPSEC] CPU%d: Microcode update ID = 0x%08X" % (cpu_thread_id, ucode_update_id) ) else: self.logger.error( "unknown command-line option '%.32s'" % ucode_op ) print UCodeCommand.__doc__ return self.logger.log( "[CHIPSEC] (ucode) time elapsed %.3f" % (time.time()-t) )
def DecompressSection(CompressedFileName, OutputFileName, CompressionType): from subprocess import call from chipsec.file import read_file decompressed = None edk2path = os.path.join('..', '..', 'tools', 'edk2', 'win') exe = None try: if (CompressionType == 1): exe = os.path.join(edk2path, 'TianoCompress.exe') elif (CompressionType == 2): exe = os.path.join(edk2path, 'LzmaCompress.exe') else: pass if exe: call('%s -d -o %s %s' % (exe, OutputFileName, CompressedFileName)) decompressed = read_file(OutputFileName) except: pass return decompressed
def DecompressSection(CompressedFileName, OutputFileName, CompressionType): from subprocess import call from chipsec.file import read_file decompressed = None edk2path = os.path.join('..','..','tools','edk2','win') exe = None try: if (CompressionType == 1): exe = os.path.join(edk2path,'TianoCompress.exe') elif (CompressionType == 2): exe = os.path.join(edk2path,'LzmaCompress.exe') else: pass if exe: call('%s -d -o %s %s' % (exe, OutputFileName, CompressedFileName)) decompressed = read_file( OutputFileName ) except: pass return decompressed
def write_spi_from_file(self, spi_fla, filename): buf = read_file(filename) return self.write_spi(spi_fla, struct.unpack('c' * len(buf), buf))
def run(self): if len(self.argv) < 3: print DecodeCommand.__doc__ return _uefi = uefi.UEFI( self.cs ) if self.argv[2] == "types": print "\n<fw_type> should be in [ %s ]\n" % ( " | ".join( ["%s" % t for t in uefi.uefi_platform.fw_types] ) ) return rom_file = self.argv[2] fwtype = self.argv[3] if len(self.argv) == 4 else None self.logger.log( "[CHIPSEC] Decoding SPI ROM image from a file '%s'" % rom_file ) t = time.time() f = read_file( rom_file ) (fd_off, fd) = spi_descriptor.get_spi_flash_descriptor( f ) if (-1 == fd_off) or (fd is None): self.logger.error( "Could not find SPI Flash descriptor in the binary '%s'" % rom_file ) return False self.logger.log( "[CHIPSEC] Found SPI Flash descriptor at offset 0x%x in the binary '%s'" % (fd_off, rom_file) ) rom = f[fd_off:] # Decoding Flash Descriptor #self.logger.LOG_COMPLETE_FILE_NAME = os.path.join( pth, 'flash_descriptor.log' ) #parse_spi_flash_descriptor( self.cs, fd ) # Decoding SPI Flash Regions # flregs[r] = (r,SPI_REGION_NAMES[r],flreg,base,limit,notused) flregs = spi_descriptor.get_spi_regions( fd ) if flregs is None: self.logger.error( "SPI Flash descriptor region is not valid" ) return False _orig_logname = self.logger.LOG_FILE_NAME pth = os.path.join( self.cs.helper.getcwd(), rom_file + ".dir" ) if not os.path.exists( pth ): os.makedirs( pth ) for r in flregs: idx = r[0] name = r[1] base = r[3] limit = r[4] notused = r[5] if not notused: region_data = rom[base:limit+1] fname = os.path.join( pth, '%d_%04X-%04X_%s.bin' % (idx, base, limit, name) ) write_file( fname, region_data ) if spi.FLASH_DESCRIPTOR == idx: # Decoding Flash Descriptor self.logger.set_log_file( os.path.join( pth, fname + '.log' ) ) spi_descriptor.parse_spi_flash_descriptor( self.cs, region_data ) elif spi.BIOS == idx: # Decoding EFI Firmware Volumes self.logger.set_log_file( os.path.join( pth, fname + '.log' ) ) spi_uefi.decode_uefi_region(_uefi, pth, fname, fwtype) self.logger.set_log_file( _orig_logname ) self.logger.log( "[CHIPSEC] (decode) time elapsed %.3f" % (time.time()-t) )