def start(self, start_driver, driver_exists=False): if start_driver: self.load_driver() self.init(start_driver) if logger().VERBOSE: logger().log("[helper] OSX Helper started/loaded") return True
def write_mmcfg_reg( cs, bus, dev, fun, off, size, value ): pciexbar = get_PCIEXBAR_base_address( cs ) pciexbar_off = (bus * 32 * 8 + dev * 8 + fun) * 0x1000 + off write_MMIO_reg( cs, pciexbar, pciexbar_off, (value&0xFFFFFFFF) ) if logger().VERBOSE: logger().log( "[mmcfg] writing B/D/F %d/%d/%d + %02X (PCIEXBAR + %08X): 0x%08X" % (bus, dev, fun, off, pciexbar_off, value) ) return True
def read_MMIOBAR_reg(cs, bar_id, offset ): bar_base = MMIO_BAR_base[ bar_id ](cs) reg_addr = bar_base + offset reg_value = cs.mem.read_physical_mem_dword( reg_addr ) if logger().VERBOSE: logger().log( '[mmio] %s + 0x%08X (0x%08X) = 0x%08X' % (MMIO_BAR_name[bar_id], offset, reg_addr, reg_value) ) return reg_value
def init( self, platform_code, start_driver, driver_exists=False ): _unknown_platform = False self.helper.start(start_driver, driver_exists) logger().log( '[CHIPSEC] API mode: %s' % ('using OS native API (not using CHIPSEC kernel module)' if self.use_native_api() else 'using CHIPSEC kernel module API') ) if platform_code is None: self.vid, self.did = self.detect_platform() if VID_INTEL != self.vid: _unknown_platform = True else: self.vid = VID_INTEL self.code = platform_code.lower() if Chipset_Code.has_key( platform_code ): self.did = Chipset_Code[ platform_code ] else: _unknown_platform = True self.did = 0xFFFF if Chipset_Dictionary.has_key( self.did ): data_dict = Chipset_Dictionary[ self.did ] self.code = data_dict['code'].lower() self.longname = data_dict['longname'] self.id = data_dict['id'] else: _unknown_platform = True self.longname = 'UnknownPlatform' self.init_cfg() if _unknown_platform and start_driver: msg = 'Unsupported Platform: VID = 0x%04X, DID = 0x%04X' % (self.vid,self.did) logger().error( msg ) raise UnknownChipsetError, msg
def write_MMIOBAR_reg(cs, bar_id, offset, dword_value ): bar_base = MMIO_BAR_base[ bar_id ]() reg_addr = bar_base + offset if logger().VERBOSE: logger().log( '[mmio] write %s + 0x%08X (0x%08X) = 0x%08X' % (MMIO_BAR_name[bar_id], offset, reg_addr, dword_value) ) cs.mem.write_physical_mem_dword( reg_addr, dword_value ) return 1
def read_IO_BAR_reg( self, bar_name, offset, size ): if logger().VERBOSE: logger().log('[iobar] read %s + 0x%X (%u)' % (bar_name, offset, size)) (bar_base,bar_size) = self.get_IO_BAR_base_address( bar_name ) io_port = bar_base + offset if offset > bar_size: logger().warn( 'offset 0x%X is ouside %s size (0x%X)' % (offset,bar_name,size) ) value = self.cs.io._read_port( io_port, size ) return value
def is_IO_BAR_defined( self, bar_name ): try: return (self.cs.Cfg.IO_BARS[ bar_name ] is not None) except KeyError: logger().error( "'%s' I/O BAR definition not found in XML config" % bar_name) #raise IOBARNotFoundError, ('IOBARNotFound: %s' % bar_name) return False
def get_MMIO_BAR_base_address( cs, bar_name ): bar = cs.Cfg.MMIO_BARS[ bar_name ] if bar is None or bar == {}: return -1,-1 b = int(bar['bus'],16) d = int(bar['dev'],16) f = int(bar['fun'],16) r = int(bar['reg'],16) width = int(bar['width'],16) if 8 == width: base_lo = cs.pci.read_dword( b, d, f, r ) base_hi = cs.pci.read_dword( b, d, f, r + 4 ) base = (base_hi << 32) | base_lo else: base = cs.pci.read_dword( b, d, f, r ) if 'enable_bit' in bar: en_mask = 1 << int(bar['enable_bit']) if ( 0 == base & en_mask ): logger().warn('%s is disabled' % bar_name) if 'mask' in bar: base &= int(bar['mask'],16) if 'offset' in bar: base = base + int(bar['offset'],16) size = int(bar['size'],16) if ('size' in bar) else 0x1000 if logger().VERBOSE: logger().log( '[mmio] %s: 0x%016X (size = 0x%X)' % (bar_name,base,size) ) return base, size
def va2pa( self, va ): (pa, error_code) = self.helper.va2pa( va ) if logger().HAL: logger().log( '[mem] VA (0x%016X) -> PA (0x%016X)' % (va, pa) ) if error_code: logger().log( '[mem] Looks like VA (0x%016X) not mapped' % (va) ) return return pa
def __init__(self, helper=None): if logger().VERBOSE: logger().log("[Chipset] __init__") if helper is None: self.helper = OsHelper() else: self.helper = helper self.vid = 0 self.did = 0 self.code = CHIPSET_CODE_UNKNOWN self.longname = "Unrecognized Platform" self.id = CHIPSET_ID_UNKNOWN self.Cfg = Cfg() # # Initializing 'basic primitive' HAL components # (HAL components directly using native OS helper functionality) # self.pci = Pci ( self ) self.mem = Memory ( self ) self.msr = Msr ( self ) self.ucode = Ucode ( self ) self.io = PortIO ( self ) self.cr = CrRegs ( self ) self.cpuid = CpuID ( self )
def print_register( _cs, reg_name, reg_val ): reg = _cs.Cfg.REGISTERS[ reg_name ] rtype = reg['type'] reg_str = '' reg_val_str = ("0x%0" + ("%dX" % (int(reg['size'],16)*2))) % reg_val if RegisterType.PCICFG == rtype or RegisterType.MMCFG == rtype: b = int(reg['bus'],16) d = int(reg['dev'],16) f = int(reg['fun'],16) o = int(reg['offset'],16) mmcfg_off_str = '' if RegisterType.MMCFG == rtype: mmcfg_off_str += ", MMCFG + 0x%X" % ((b*32*8 + d*8 + f) * 0x1000 + o) reg_str = "[*] %s = %s << %s (b:d.f %02d:%02d.%d + 0x%X%s)" % (reg_name, reg_val_str, reg['desc'], b, d, f, o, mmcfg_off_str) elif RegisterType.MMIO == rtype: reg_str = "[*] %s = %s << %s (%s + 0x%X)" % (reg_name, reg_val_str, reg['desc'], reg['bar'], int(reg['offset'],16)) elif RegisterType.MSR == rtype: reg_str = "[*] %s = %s << %s (MSR 0x%X)" % (reg_name, reg_val_str, reg['desc'], int(reg['msr'],16)) elif RegisterType.PORTIO == rtype: reg_str = "[*] %s = %s << %s (I/O port 0x%X)" % (reg_name, reg_val_str, reg['desc'], int(reg['port'],16)) elif RegisterType.IOBAR == rtype: reg_str = "[*] %s = %s << %s (I/O %s + 0x%X)" % (reg_name, reg_val_str, reg['desc'], reg['bar'], int(reg['offset'],16)) reg_str += _register_fields_str( reg, reg_val ) logger().log( reg_str ) return reg_str
def init(self): global _DEV_FH _DEV_FH = None # already initialized? if _DEV_FH != None: return logger().log("\n****** Chipsec Linux Kernel module is licensed under GPL 2.0\n") try: _DEV_FH = open("/dev/chipsec", "r+") except IOError as e: raise OsHelperError("Unable to open chipsec device. %s" % str(e), e.errno) except BaseException as be: raise OsHelperError("Unable to open chipsec device. %s" % str(be), errno.ENXIO) # decode the arg size global _PACK _PACK = "I" global _IOCTL_BASE _IOCTL_BASE = fcntl.ioctl(_DEV_FH, IOCTL_BASE()) << 4 global CPU_MASK_LEN CPU_MASK_LEN = 8 if sys.maxsize > 2 ** 32 else 4
def write_pci_reg( self, bus, device, function, offset, value, size = 4 ): data = struct.pack(_pci_msg_t_fmt, bus, device, function, offset, size, value) try: ret = self.ioctl(IOCTL_WRPCI, data) except IOError: logger().error("IOError")
def get_MMIO_BAR_base_address(self, bar_name): bar = self.cs.Cfg.MMIO_BARS[ bar_name ] if bar is None or bar == {}: return -1,-1 if 'register' in bar: bar_reg = bar['register'] if 'base_field' in bar: base_field = bar['base_field'] base = self.cs.read_register_field(bar_reg, base_field, preserve_field_position=True) else: base = self.cs.read_register(bar_reg) else: # this method is not preferred (less flexible) b = int(bar['bus'],16) d = int(bar['dev'],16) f = int(bar['fun'],16) r = int(bar['reg'],16) width = int(bar['width'],16) if 8 == width: base_lo = self.cs.pci.read_dword( b, d, f, r ) base_hi = self.cs.pci.read_dword( b, d, f, r + 4 ) base = (base_hi << 32) | base_lo else: base = self.cs.pci.read_dword( b, d, f, r ) if 'mask' in bar: base &= int(bar['mask'],16) if 'offset' in bar: base = base + int(bar['offset'],16) size = int(bar['size'],16) if ('size' in bar) else DEFAULT_MMIO_BAR_SIZE if logger().VERBOSE: logger().log( '[mmio] %s: 0x%016X (size = 0x%X)' % (bar_name,base,size) ) return base, size
def dump_IO( self, range_base, range_size, size=1 ): n = range_size/size fmt = '%0' + ( '%dX' % (size*2) ) logger().log("[io] I/O register range [0x%04X:0x%04X+%04X]:" % (range_base,range_base,range_size)) for i in xrange(n): reg = self._read_port( range_base + i*size, size ) logger().log( ('+%04X: ' + fmt) % (i*size,reg) )
def init( self, platform_code, start_driver ): _unknown_platform = False self.helper.start(start_driver) if platform_code is None: vid_did = self.pci.read_dword( 0, 0, 0, 0 ) self.vid = vid_did & 0xFFFF self.did = (vid_did >> 16) & 0xFFFF if VID_INTEL != self.vid: _unknown_platform = True else: self.vid = VID_INTEL self.code = platform_code.lower() if Chipset_Code.has_key( platform_code ): self.did = Chipset_Code[ platform_code ] else: _unknown_platform = True self.did = 0xFFFF if Chipset_Dictionary.has_key( self.did ): data_dict = Chipset_Dictionary[ self.did ] self.code = data_dict['code'].lower() self.longname = data_dict['longname'] self.id = data_dict['id'] else: _unknown_platform = True self.longname = 'UnknownPlatform' self.init_cfg() if _unknown_platform and start_driver: msg = 'Unsupported Platform: VID = 0x%04X, DID = 0x%04X' % (self.vid,self.did) logger().error( msg ) raise UnknownChipsetError, msg
def read_MMIOBAR_reg(self, bar_id, offset ): bar_base = self.MMIO_BAR_base[ bar_id ] reg_addr = bar_base + offset reg_value = self.cs.helper.read_mmio_reg( reg_addr, 4 ) if logger().VERBOSE: logger().log( '[mmio] %s + 0x%08X (0x%08X) = 0x%08X' % (MMIO_BAR_name[bar_id], offset, reg_addr, reg_value) ) return reg_value
def list_IO_BARs(self): logger().log("") logger().log("--------------------------------------------------------------------------------") logger().log(" I/O Range | BAR Register | Base | Size | En? | Description") logger().log("--------------------------------------------------------------------------------") for _bar_name in self.cs.Cfg.IO_BARS: if not self.is_IO_BAR_defined(_bar_name): continue _bar = self.cs.Cfg.IO_BARS[_bar_name] (_base, _size) = self.get_IO_BAR_base_address(_bar_name) _en = self.is_IO_BAR_enabled(_bar_name) if "register" in _bar: _s = _bar["register"] if "offset" in _bar: _s += " + 0x%X" % int(_bar["offset"], 16) else: _s = "%02X:%02X.%01X + %s" % ( int(_bar["bus"], 16), int(_bar["dev"], 16), int(_bar["fun"], 16), _bar["reg"], ) logger().log(" %-12s | %-14s | %016X | %08X | %d | %s" % (_bar_name, _s, _base, _size, _en, _bar["desc"]))
def get_IO_BAR_base_address(self, bar_name): bar = self.cs.Cfg.IO_BARS[bar_name] if bar is None or bar == {}: raise IOBARNotFoundError, ("IOBARNotFound: %s" % bar_name) if "register" in bar: bar_reg = bar["register"] if "base_field" in bar: base_field = bar["base_field"] base = chipsec.chipset.read_register_field(self.cs, bar_reg, base_field, preserve_field_position=True) else: base = chipsec.chipset.read_register(self.cs, bar_reg) else: # this method is not preferred base = self.cs.pci.read_word( int(bar["bus"], 16), int(bar["dev"], 16), int(bar["fun"], 16), int(bar["reg"], 16) ) if "mask" in bar: base = base & int(bar["mask"], 16) if "offset" in bar: base = base + int(bar["offset"], 16) size = int(bar["size"], 16) if ("size" in bar) else DEFAULT_IO_BAR_SIZE if logger().VERBOSE: logger().log("[iobar] %s: 0x%04X (size = 0x%X)" % (bar_name, base, size)) return base, size
def kern_set_EFI_variable(self, name, guid, value, attr=0x7): status_dict = { 0:"EFI_SUCCESS", 1:"EFI_LOAD_ERROR", 2:"EFI_INVALID_PARAMETER", 3:"EFI_UNSUPPORTED", 4:"EFI_BAD_BUFFER_SIZE", 5:"EFI_BUFFER_TOO_SMALL", 6:"EFI_NOT_READY", 7:"EFI_DEVICE_ERROR", 8:"EFI_WRITE_PROTECTED", 9:"EFI_OUT_OF_RESOURCES", 14:"EFI_NOT_FOUND", 26:"EFI_SECURITY_VIOLATION" } header_size = 60 # 4*15 namelen = len(name) if value: datalen = len(value) else: datalen = 0 value = '\0' data_size = header_size + namelen + datalen guid0 = int(guid[:8] , 16) guid1 = int(guid[9:13], 16) guid2 = int(guid[14:18], 16) guid3 = int(guid[19:21], 16) guid4 = int(guid[21:23], 16) guid5 = int(guid[24:26], 16) guid6 = int(guid[26:28], 16) guid7 = int(guid[28:30], 16) guid8 = int(guid[30:32], 16) guid9 = int(guid[32:34], 16) guid10 = int(guid[34:], 16) in_buf = struct.pack('15I'+str(namelen)+'s'+str(datalen)+'s', data_size, guid0, guid1, guid2, guid3, guid4, guid5, guid6, guid7, guid8, guid9, guid10, attr, namelen, datalen, name, value) buffer = array.array("c", in_buf) stat = fcntl.ioctl(_DEV_FH, IOCTL_SET_EFIVAR(), buffer, True) size, status = struct.unpack( "2I", buffer[:8]) if (status != 0): logger().error( "Setting EFI (SET_EFIVAR) variable did not succeed: %s" % status_dict[status] ) else: os.system('umount /sys/firmware/efi/efivars; mount -t efivarfs efivarfs /sys/firmware/efi/efivars') return status
def get_affinity(self): CORES = ctypes.cdll.LoadLibrary( os.path.join(chipsec.file.get_main_dir( ), 'chipsec/helper/linux/cores.so' ) ) CORES.getaffinity.argtypes = [ ctypes.c_int, POINTER( ( ctypes.c_long * 128 ) ),POINTER( ctypes.c_int ) ] CORES.getaffinity.restype = ctypes.c_int mask = ( ctypes.c_long * 128 )( ) try: numCpus = 0 f = open('/proc/cpuinfo', 'r') for line in f: if "processor" in line: numCpus += 1 f.close() except: numCpus = 1; pass errno = ctypes.c_int( 0 ) if 0 == CORES.getaffinity( numCpus,byref( mask ),byref( errno ) ): AffinityString = " GetAffinity: " for i in range( 0, numCpus ): if mask[i] == 1: AffinityString += "%s " % i logger().log( AffinityString ) return 1 else: AffinityString = " Get_affinity errno::%s"%( errno.value ) logger().log( AffinityString ) return None
def decompress_file( self, CompressedFileName, OutputFileName, CompressionType ): if not CompressionType in [i for i in chipsec.defines.COMPRESSION_TYPES]: return False if CompressionType == chipsec.defines.COMPRESSION_TYPE_UNKNOWN: data = self.unknown_decompress(CompressedFileName,OutputFileName) return data elif CompressionType == chipsec.defines.COMPRESSION_TYPE_EFI_STANDARD: data = self.unknown_efi_decompress(CompressedFileName,OutputFileName) return data decode_str = " -d -o {} ".format(OutputFileName) if CompressionType == chipsec.defines.COMPRESSION_TYPE_NONE: shutil.copyfile(CompressedFileName,OutputFileName) return True elif CompressionType == chipsec.defines.COMPRESSION_TYPE_TIANO: decode_str = TIANO + decode_str elif CompressionType == chipsec.defines.COMPRESSION_TYPE_UEFI: decode_str = EFI + decode_str + "--uefi " elif CompressionType == chipsec.defines.COMPRESSION_TYPE_LZMA: decode_str = LZMA + decode_str elif CompressionType == chipsec.defines.COMPRESSION_TYPE_BROTLI: decode_str = BROTLI + decode_str decode_str += CompressedFileName data = subprocess.call(decode_str,shell=True) if not data == 0 and logger().VERBOSE: logger().error("Cannot decompress file({})".format(CompressedFileName)) return False return True
def native_write_mmio_reg(self, phys_address, size, value): if self.devmem_available(): reg = struct.pack(('=%c' % chipsec.defines.SIZE2FORMAT[size]), value) os.lseek(self.dev_mem, phys_address, os.SEEK_SET) written = os.write(self.dev_mem, reg) if written != size: logger().error("Unable to write all data to MMIO (wrote %d of %d)" % (written, size))
def read_MMIOBAR_reg(cs, bar_id, offset): bar_base = MMIO_BAR_base[bar_id](cs) reg_addr = bar_base + offset reg_value = cs.helper.read_mmio_reg(reg_addr, 4) if logger().VERBOSE: logger().log("[mmio] %s + 0x%08X (0x%08X) = 0x%08X" % (MMIO_BAR_name[bar_id], offset, reg_addr, reg_value)) return reg_value
def get_MMIO_BAR_base_address(cs, bar_name): bar = cs.Cfg.MMIO_BARS[bar_name] if bar is None or bar == {}: return -1, -1 if "register" in bar: bar_reg = bar["register"] if "base_field" in bar: base_field = bar["base_field"] base = chipsec.chipset.read_register_field(cs, bar_reg, base_field, True) else: base = chipsec.chipset.read_register(cs, bar_reg) else: # this method is not preferred (less flexible) b = int(bar["bus"], 16) d = int(bar["dev"], 16) f = int(bar["fun"], 16) r = int(bar["reg"], 16) width = int(bar["width"], 16) if 8 == width: base_lo = cs.pci.read_dword(b, d, f, r) base_hi = cs.pci.read_dword(b, d, f, r + 4) base = (base_hi << 32) | base_lo else: base = cs.pci.read_dword(b, d, f, r) if "mask" in bar: base &= int(bar["mask"], 16) if "offset" in bar: base = base + int(bar["offset"], 16) size = int(bar["size"], 16) if ("size" in bar) else DEFAULT_MMIO_BAR_SIZE if logger().VERBOSE: logger().log("[mmio] %s: 0x%016X (size = 0x%X)" % (bar_name, base, size)) return base, size
def write_mmio_reg(self, phys_address, size, value): if logger().VERBOSE: logger().log( '[efi] helper does not support 64b PA' ) if size == 4: return edk2.writemem_dword( phys_address, value ) else: logger().error( '[efi] unsupported size %d by write_mmio_reg' % size )
def stop(self, start_driver): self.close() if self.driver_loaded: subprocess.call(["rmmod", self.MODULE_NAME]) if logger().VERBOSE: logger().log("[helper] Linux Helper stopped/unloaded") return True
def start(self, start_driver, driver_exists=False): # The driver is part of the modified version of edk2. # It is always considered as loaded. self.driver_loaded = True if logger().DEBUG: logger().log("[helper] UEFI Helper started/loaded") return True
def native_write_msr(self, thread_id, msr_addr, eax, edx): if self.devport_available(): os.lseek(self.dev_msr[thread_id], msr_addr, os.SEEK_SET) buf = struct.pack( "2I", eax, edx) written = os.write(self.dev_msr[thread_id], buf) if written != 8: logger().error("Cannot write %8X to MSR %x" % (buf, msr_addr))
def kern_list_EFI_variables(self, infcls): varlist = [] off = 0 buf = list() hdr = 0 attr = 0 try: if os.path.isdir('/sys/firmware/efi/efivars'): varlist = os.listdir('/sys/firmware/efi/efivars') elif os.path.isdir('/sys/firmware/efi/vars'): varlist = os.listdir('/sys/firmware/efi/vars') else: return None except Exception: logger().error('Failed to read /sys/firmware/efi/[vars|efivars]. Folder does not exist') return None variables = dict() for v in varlist: name = v[:-37] guid = v[len(name)+1:] if name and name is not None: variables[name] = [] var = self.kern_get_EFI_variable_full(name, guid) (off, buf, hdr, data, guid, attr) = var variables[name].append(var) return variables
def find_thread(self): for en_thread in range(len(self.base.threads)): if self.base.threads[en_thread].isenabled: return en_thread logger().log('[WARNING] No enabled threads found.') return 0
def get_EFI_variable(self, name, guid, attrs=None): logger().error('[DAL] API get_EFI_variable() is not supported') return None
def native_list_EFI_variables(self): logger().error( '[DAL] API native_list_EFI_variables() is not supported') return None
def native_delete_EFI_variable(self, name, guid): logger().error( '[DAL] API native_delete_EFI_variable() is not supported') return None
def get_descriptor_table(self, cpu_thread_id, desc_table_code): logger().error('[DAL] API get_descriptor_table() is not supported') return None
def get_threads_count(self): no_threads = len(self.base.threads) if logger().DEBUG: logger().log('[helper] Threads discovered : 0x%X (%d)' % (no_threads, no_threads)) return no_threads
def load_ucode_update(self, core_id, ucode_update_buf): logger().error("[DAL] API load_ucode_update() is not supported yet") return False
def print_chipset(self): logger().log( "[*] Platform: %s\n VID: %04X\n DID: %04X" % (self.longname, self.vid, self.did))
def list_EFI_variables(self, infcls=2): if logger().DEBUG: logger().log( '[helper] -> NtEnumerateSystemEnvironmentValuesEx( infcls={:d} )..' .format(infcls)) efi_vars = create_string_buffer(EFI_VAR_MAX_BUFFER_SIZE) length = packl_ctypes(EFI_VAR_MAX_BUFFER_SIZE, 32) status = self.NtEnumerateSystemEnvironmentValuesEx( infcls, efi_vars, length) status = (((1 << 32) - 1) & status) if (0xC0000023 == status): retlength, = struct.unpack("<I", length) efi_vars = create_string_buffer(retlength) status = self.NtEnumerateSystemEnvironmentValuesEx( infcls, efi_vars, length) elif (0xC0000002 == status): if logger().DEBUG: logger().warn( 'NtEnumerateSystemEnvironmentValuesEx was not found (NTSTATUS = 0xC0000002)' ) if logger().DEBUG: logger().log( '[*] Your Windows does not expose UEFI Runtime Variable API. It was likely installed as legacy boot.\nTo use UEFI variable functions, chipsec needs to run in OS installed with UEFI boot (enable UEFI Boot in BIOS before installing OS)' ) return None if 0 != status: if logger().DEBUG: logger().error( 'NtEnumerateSystemEnvironmentValuesEx failed (GetLastError = 0x{:X})' .format(kernel32.GetLastError())) logger().error('*** NTSTATUS: {:08X}'.format(((1 << 32) - 1) & status)) raise WinError() if logger().DEBUG: logger().log( '[helper] len(efi_vars) = 0x{:X} (should be 0x20000)'.format( len(efi_vars))) return getEFIvariables_NtEnumerateSystemEnvironmentValuesEx2(efi_vars)
def init_cfg_xml(self, fxml, code): import xml.etree.ElementTree as ET if not os.path.exists(fxml): return if logger().VERBOSE: logger().log("[*] looking for platform config in '%s'.." % fxml) tree = ET.parse(fxml) root = tree.getroot() for _cfg in root.iter('configuration'): if 'platform' not in _cfg.attrib: if logger().HAL: logger().log( "[*] loading common platform config from '%s'.." % fxml) elif code == _cfg.attrib['platform'].lower(): if logger().HAL: logger().log( "[*] loading '%s' platform config from '%s'.." % (code, fxml)) else: continue if logger().VERBOSE: logger().log("[*] loading integrated devices/controllers..") for _pci in _cfg.iter('pci'): for _device in _pci.iter('device'): _name = _device.attrib['name'] del _device.attrib['name'] self.Cfg.CONFIG_PCI[_name] = _device.attrib if logger().VERBOSE: logger().log(" + %-16s: %s" % (_name, _device.attrib)) if logger().VERBOSE: logger().log("[*] loading MMIO BARs..") for _mmio in _cfg.iter('mmio'): for _bar in _mmio.iter('bar'): _name = _bar.attrib['name'] del _bar.attrib['name'] self.Cfg.MMIO_BARS[_name] = _bar.attrib if logger().VERBOSE: logger().log(" + %-16s: %s" % (_name, _bar.attrib)) if logger().VERBOSE: logger().log("[*] loading I/O BARs..") for _io in _cfg.iter('io'): for _bar in _io.iter('bar'): _name = _bar.attrib['name'] del _bar.attrib['name'] self.Cfg.IO_BARS[_name] = _bar.attrib if logger().VERBOSE: logger().log(" + %-16s: %s" % (_name, _bar.attrib)) if logger().VERBOSE: logger().log("[*] loading memory ranges..") for _memory in _cfg.iter('memory'): for _range in _memory.iter('range'): _name = _range.attrib['name'] del _range.attrib['name'] self.Cfg.MEMORY_RANGES[_name] = _range.attrib if logger().VERBOSE: logger().log(" + %-16s: %s" % (_name, _range.attrib)) if logger().VERBOSE: logger().log("[*] loading configuration registers..") for _registers in _cfg.iter('registers'): for _register in _registers.iter('register'): _name = _register.attrib['name'] del _register.attrib['name'] if 'size' not in _register.attrib: _register.attrib['size'] = "0x4" if 'desc' not in _register.attrib: _register.attrib['desc'] = '' reg_fields = {} if _register.find('field') is not None: for _field in _register.iter('field'): _field_name = _field.attrib['name'] del _field.attrib['name'] if 'desc' not in _field.attrib: _field.attrib['desc'] = '' reg_fields[_field_name] = _field.attrib _register.attrib['FIELDS'] = reg_fields self.Cfg.REGISTERS[_name] = _register.attrib if logger().VERBOSE: logger().log(" + %-16s: %s" % (_name, _register.attrib)) if logger().VERBOSE: logger().log("[*] loading controls..") for _controls in _cfg.iter('controls'): for _control in _controls.iter('control'): _name = _control.attrib['name'] del _control.attrib['name'] self.Cfg.CONTROLS[_name] = _control.attrib if logger().VERBOSE: logger().log(" + %-16s: %s" % (_name, _control.attrib))
def delete(self, start_driver): if not start_driver: return True if self.use_existing_service: return True if win32serviceutil.QueryServiceStatus( SERVICE_NAME)[1] != win32service.SERVICE_STOPPED: logger().warn("cannot delete service '{}' (not stopped)".format( SERVICE_NAME)) return False if logger().DEBUG: logger().log( "[helper] deleting service '{}'...".format(SERVICE_NAME)) try: win32serviceutil.RemoveService(SERVICE_NAME) if logger().DEBUG: logger().log( "[helper] service '{}' deleted".format(SERVICE_NAME)) except win32service.error as err: if logger().DEBUG: logger().warn("RemoveService failed: {} ({:d})".format( err.args[2], err.args[0])) return False return True
class Chipset: def __init__(self, helper=None): if helper is None: self.helper = OsHelper() else: self.helper = helper self.vid = 0 self.did = 0 self.code = CHIPSET_CODE_UNKNOWN self.longname = "Unrecognized Platform" self.id = CHIPSET_ID_UNKNOWN self.Cfg = Cfg() # # Initializing 'basic primitive' HAL components # (HAL components directly using native OS helper functionality) # self.pci = Pci(self) self.mem = Memory(self) self.msr = Msr(self) self.ucode = Ucode(self) self.io = PortIO(self) self.cpu = chipsec.hal.cpu.CPU(self) #self.cr = CrRegs ( self ) #self.cpuid = CpuID ( self ) self.msgbus = MsgBus(self) # # All HAL components which use above 'basic primitive' HAL components # should be instantiated in modules/utilcmd with an instance of chipset # Examples: # - initializing SPI HAL component in a module: # self.spi = SPI( self.cs ) # - initializing second order UEFI HAL component in utilcmd extension: # spi = SPI( chipsec_util._cs ) # def init(self, platform_code, start_driver): _unknown_platform = False self.helper.start(start_driver) if platform_code is None: vid_did = self.pci.read_dword(0, 0, 0, 0) self.vid = vid_did & 0xFFFF self.did = (vid_did >> 16) & 0xFFFF if VID_INTEL != self.vid: _unknown_platform = True else: self.vid = VID_INTEL self.code = platform_code.lower() if Chipset_Code.has_key(platform_code): self.did = Chipset_Code[platform_code] else: _unknown_platform = True self.did = 0xFFFF if Chipset_Dictionary.has_key(self.did): data_dict = Chipset_Dictionary[self.did] self.code = data_dict['code'].lower() self.longname = data_dict['longname'] self.id = data_dict['id'] else: _unknown_platform = True self.longname = 'UnknownPlatform' self.init_cfg() if _unknown_platform and start_driver: msg = 'Unsupported Platform: VID = 0x%04X, DID = 0x%04X' % ( self.vid, self.did) logger().error(msg) raise UnknownChipsetError, msg def destroy(self, start_svc): self.stop(start_svc) #self.helper.destroy() def stop(self, start_svc): if start_svc: self.helper.stop() def get_chipset_id(self): return self.id def get_chipset_code(self): return self.code def get_chipset_name(self, id): return self.longname def print_chipset(self): logger().log( "[*] Platform: %s\n VID: %04X\n DID: %04X" % (self.longname, self.vid, self.did)) def is_core(self): return self.get_chipset_id() in CHIPSET_FAMILY_CORE def is_server(self): return self.get_chipset_id() in CHIPSET_FAMILY_XEON def is_atom(self): return self.get_chipset_id() in CHIPSET_FAMILY_ATOM ################################################################################## # # Loading platform configuration from XML files in chipsec/cfg/ # ################################################################################## def init_xml_configuration(self): _cfg_path = os.path.join(chipsec.file.get_main_dir(), 'chipsec/cfg') # Load chipsec/cfg/common.xml configuration XML file common for all platforms if it exists self.init_cfg_xml(os.path.join(_cfg_path, 'common.xml'), self.code) # Load chipsec/cfg/<code>.xml configuration XML file if it exists for platform <code> if self.code and '' != self.code: self.init_cfg_xml(os.path.join(_cfg_path, ('%s.xml' % self.code)), self.code) # Load configuration from all other XML files recursively (if any) for dirname, subdirs, xml_fnames in os.walk(_cfg_path): for _xml in xml_fnames: if fnmatch.fnmatch(_xml, '*.xml') and not fnmatch.fnmatch( _xml, 'common.xml') and not (_xml in [ '%s.xml' % c.lower() for c in Chipset_Code ]): self.init_cfg_xml(os.path.join(dirname, _xml), self.code) self.Cfg.XML_CONFIG_LOADED = True def init_cfg_xml(self, fxml, code): import xml.etree.ElementTree as ET if not os.path.exists(fxml): return if logger().VERBOSE: logger().log("[*] looking for platform config in '%s'.." % fxml) tree = ET.parse(fxml) root = tree.getroot() for _cfg in root.iter('configuration'): if 'platform' not in _cfg.attrib: if logger().HAL: logger().log( "[*] loading common platform config from '%s'.." % fxml) elif code == _cfg.attrib['platform'].lower(): if logger().HAL: logger().log( "[*] loading '%s' platform config from '%s'.." % (code, fxml)) else: continue if logger().VERBOSE: logger().log("[*] loading integrated devices/controllers..") for _pci in _cfg.iter('pci'): for _device in _pci.iter('device'): _name = _device.attrib['name'] del _device.attrib['name'] self.Cfg.CONFIG_PCI[_name] = _device.attrib if logger().VERBOSE: logger().log(" + %-16s: %s" % (_name, _device.attrib)) if logger().VERBOSE: logger().log("[*] loading MMIO BARs..") for _mmio in _cfg.iter('mmio'): for _bar in _mmio.iter('bar'): _name = _bar.attrib['name'] del _bar.attrib['name'] self.Cfg.MMIO_BARS[_name] = _bar.attrib if logger().VERBOSE: logger().log(" + %-16s: %s" % (_name, _bar.attrib)) if logger().VERBOSE: logger().log("[*] loading I/O BARs..") for _io in _cfg.iter('io'): for _bar in _io.iter('bar'): _name = _bar.attrib['name'] del _bar.attrib['name'] self.Cfg.IO_BARS[_name] = _bar.attrib if logger().VERBOSE: logger().log(" + %-16s: %s" % (_name, _bar.attrib)) if logger().VERBOSE: logger().log("[*] loading memory ranges..") for _memory in _cfg.iter('memory'): for _range in _memory.iter('range'): _name = _range.attrib['name'] del _range.attrib['name'] self.Cfg.MEMORY_RANGES[_name] = _range.attrib if logger().VERBOSE: logger().log(" + %-16s: %s" % (_name, _range.attrib)) if logger().VERBOSE: logger().log("[*] loading configuration registers..") for _registers in _cfg.iter('registers'): for _register in _registers.iter('register'): _name = _register.attrib['name'] del _register.attrib['name'] if 'size' not in _register.attrib: _register.attrib['size'] = "0x4" if 'desc' not in _register.attrib: _register.attrib['desc'] = '' reg_fields = {} if _register.find('field') is not None: for _field in _register.iter('field'): _field_name = _field.attrib['name'] del _field.attrib['name'] if 'desc' not in _field.attrib: _field.attrib['desc'] = '' reg_fields[_field_name] = _field.attrib _register.attrib['FIELDS'] = reg_fields self.Cfg.REGISTERS[_name] = _register.attrib if logger().VERBOSE: logger().log(" + %-16s: %s" % (_name, _register.attrib)) if logger().VERBOSE: logger().log("[*] loading controls..") for _controls in _cfg.iter('controls'): for _control in _controls.iter('control'): _name = _control.attrib['name'] del _control.attrib['name'] self.Cfg.CONTROLS[_name] = _control.attrib if logger().VERBOSE: logger().log(" + %-16s: %s" % (_name, _control.attrib)) # # Load chipsec/cfg/<code>.py configuration file for platform <code> # def init_cfg(self): if self.code and '' != self.code: try: module_path = 'chipsec.cfg.' + self.code module = importlib.import_module(module_path) logger().log_good( "imported platform specific configuration: chipsec.cfg.%s" % self.code) self.Cfg = getattr(module, self.code)() except ImportError, msg: if logger().VERBOSE: logger().log("[*] Couldn't import chipsec.cfg.%s\n%s" % (self.code, str(msg))) # # Initialize platform configuration from XML files # try: self.init_xml_configuration() except: if logger().VERBOSE: logger().log_bad(traceback.format_exc()) pass
def show_warning(self): logger().log("") logger().warn( "*******************************************************************" ) logger().warn("Chipsec should only be used on test systems!") logger().warn( "It should not be installed/deployed on production end-user systems." ) logger().warn("See WARNING.txt") logger().warn( "*******************************************************************" ) logger().log("")
def stop(self, start_driver): if not start_driver: return True if self.use_existing_service: return True if logger().DEBUG: logger().log( "[helper] stopping service '{}'..".format(SERVICE_NAME)) try: win32api.CloseHandle(self.driver_handle) self.driver_handle = None win32serviceutil.StopService(SERVICE_NAME) except pywintypes.error as err: if logger().DEBUG: logger().error("StopService failed: {} ({:d})".format( err.args[2], err.args[0])) return False finally: self.driver_loaded = False try: win32serviceutil.WaitForServiceStatus(SERVICE_NAME, win32service.SERVICE_STOPPED, 1) if logger().DEBUG: logger().log( "[helper] service '{}' stopped".format(SERVICE_NAME)) except pywintypes.error as err: if logger().DEBUG: logger().warn("service '{}' didn't stop: {} ({:d})".format( SERVICE_NAME, err.args[2], err.args[0])) return False return True
def _handle_error(err, hr=0): logger().error(err) raise OsHelperError(err, hr)
def create(self, start_driver): if not start_driver: return True # check DRIVER_FILE_PATHS for the DRIVER_FILE_NAME self.driver_path = None for path in DRIVER_FILE_PATHS: driver_path = os.path.join(path, DRIVER_FILE_NAME) if os.path.isfile(driver_path): self.driver_path = driver_path if logger().DEBUG: logger().log( "[helper] found driver in {}".format(driver_path)) if self.driver_path is None: if logger().DEBUG: logger().log("[helper] CHIPSEC Windows Driver Not Found") raise Exception("CHIPSEC Windows Driver Not Found") self.show_warning() try: hscm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_ALL_ACCESS ) # SC_MANAGER_CREATE_SERVICE except win32service.error as err: _handle_winerror(err.args[1], err.args[2], err.args[0]) if logger().DEBUG: logger().log( "[helper] service control manager opened (handle = {})".format( hscm)) logger().log("[helper] driver path: '{}'".format( os.path.abspath(self.driver_path))) try: hs = win32service.CreateService( hscm, SERVICE_NAME, DISPLAY_NAME, (win32service.SERVICE_QUERY_STATUS | win32service.SERVICE_START | win32service.SERVICE_STOP), win32service.SERVICE_KERNEL_DRIVER, win32service.SERVICE_DEMAND_START, win32service.SERVICE_ERROR_NORMAL, os.path.abspath(self.driver_path), None, 0, u"", None, None) if hs: if logger().DEBUG: logger().log( "[helper] service '{}' created (handle = 0x{:08X})". format(SERVICE_NAME, int(hs))) except win32service.error as err: if (winerror.ERROR_SERVICE_EXISTS == err.args[0]): if logger().DEBUG: logger().log( "[helper] service '{}' already exists: {} ({:d})". format(SERVICE_NAME, err.args[2], err.args[0])) try: hs = win32service.OpenService( hscm, SERVICE_NAME, (win32service.SERVICE_QUERY_STATUS | win32service.SERVICE_START | win32service.SERVICE_STOP)) # SERVICE_ALL_ACCESS except win32service.error as _err: _handle_winerror(_err.args[1], _err.args[2], _err.args[0]) else: _handle_winerror(err.args[1], err.args[2], err.args[0]) finally: win32service.CloseServiceHandle(hs) win32service.CloseServiceHandle(hscm) return True
def main(self): from chipsec.chipset import UnknownChipsetError self.print_banner() for import_path in self.IMPORT_PATHS: sys.path.append(os.path.abspath(import_path)) if self._no_driver and self._driver_exists: logger().error("incompatible options: --no_driver and --exists") return ExitCode.EXCEPTION try: self._cs.init(self._platform, (not self._no_driver), self._driver_exists) except UnknownChipsetError, msg: logger().error("Platform is not supported (%s)." % str(msg)) if self._unkownPlatform: logger().error( 'To run anyways please use -i command-line option\n\n') if logger().DEBUG: logger().log_bad(traceback.format_exc()) if self.failfast: raise msg return ExitCode.EXCEPTION logger().warn( "Platform dependent functionality is likely to be incorrect")
def __init__(self): super(Win32Helper, self).__init__() self.os_system = platform.system() self.os_release = platform.release() self.os_version = platform.version() self.os_machine = platform.machine() self.os_uname = platform.uname() self.name = "Win32Helper" if "windows" == self.os_system.lower(): win_ver = "win7_" + self.os_machine.lower() if ("5" == self.os_release): win_ver = "winxp" if logger().DEBUG: logger().log("[helper] OS: {} {} {}".format( self.os_system, self.os_release, self.os_version)) self.use_existing_service = False self.win_ver = win_ver self.driver_handle = None self.device_file = str(DEVICE_FILE) c_int_p = POINTER(c_int) # enable required SeSystemEnvironmentPrivilege privilege privilege = win32security.LookupPrivilegeValue( None, 'SeSystemEnvironmentPrivilege') token = win32security.OpenProcessToken( win32process.GetCurrentProcess(), win32security.TOKEN_READ | win32security.TOKEN_ADJUST_PRIVILEGES) win32security.AdjustTokenPrivileges( token, False, [(privilege, win32security.SE_PRIVILEGE_ENABLED)]) win32api.CloseHandle(token) # import firmware variable API try: self.GetFirmwareEnvironmentVariable = kernel32.GetFirmwareEnvironmentVariableW self.GetFirmwareEnvironmentVariable.restype = c_int self.GetFirmwareEnvironmentVariable.argtypes = [ c_wchar_p, c_wchar_p, c_void_p, c_int ] self.SetFirmwareEnvironmentVariable = kernel32.SetFirmwareEnvironmentVariableW self.SetFirmwareEnvironmentVariable.restype = c_int self.SetFirmwareEnvironmentVariable.argtypes = [ c_wchar_p, c_wchar_p, c_void_p, c_int ] except AttributeError as msg: logger().warn( "G[S]etFirmwareEnvironmentVariableW function doesn't seem to exist" ) pass try: self.NtEnumerateSystemEnvironmentValuesEx = windll.ntdll.NtEnumerateSystemEnvironmentValuesEx self.NtEnumerateSystemEnvironmentValuesEx.restype = c_int self.NtEnumerateSystemEnvironmentValuesEx.argtypes = [ c_int, c_void_p, c_void_p ] except AttributeError as msg: logger().warn( "NtEnumerateSystemEnvironmentValuesEx function doesn't seem to exist" ) pass try: self.GetFirmwareEnvironmentVariableEx = kernel32.GetFirmwareEnvironmentVariableExW self.GetFirmwareEnvironmentVariableEx.restype = c_int self.GetFirmwareEnvironmentVariableEx.argtypes = [ c_wchar_p, c_wchar_p, c_void_p, c_int, c_int_p ] self.SetFirmwareEnvironmentVariableEx = kernel32.SetFirmwareEnvironmentVariableExW self.SetFirmwareEnvironmentVariableEx.restype = c_int self.SetFirmwareEnvironmentVariableEx.argtypes = [ c_wchar_p, c_wchar_p, c_void_p, c_int, c_int ] except AttributeError as msg: if logger().DEBUG: logger().warn( "G[S]etFirmwareEnvironmentVariableExW function doesn't seem to exist" ) pass try: self.GetSystemFirmwareTbl = kernel32.GetSystemFirmwareTable self.GetSystemFirmwareTbl.restype = c_int self.GetSystemFirmwareTbl.argtypes = [ c_int, c_int, c_void_p, c_int ] except AttributeError as msg: logger().warn( "GetSystemFirmwareTable function doesn't seem to exist") pass try: self.EnumSystemFirmwareTbls = kernel32.EnumSystemFirmwareTables self.EnumSystemFirmwareTbls.restype = c_int self.EnumSystemFirmwareTbls.argtypes = [c_int, c_void_p, c_int] except AttributeError as msg: logger().warn( "GetSystemFirmwareTable function doesn't seem to exist")
def print_loaded_modules(self): if self.Loaded_Modules == []: logger().log("No modules have been loaded") for (modx, modx_argv) in self.Loaded_Modules: logger().log(modx)
def msgbus_send_message(self, mcr, mcrx, mdr=None): if logger().DEBUG: logger().error("[helper] Message Bus is not supported yet") return None
import getopt try: opts, args = getopt.getopt(self.argv, "ip:m:ho:vda:nl:t:j:x:I:", [ "ignore_platform", "platform=", "module=", "help", "output=", "verbose", "debug", "module_args=", "no_driver", "log=", "moduletype=", "json=", "xml=", "list_tags", "include", "failfast", "no_time" ]) except getopt.GetoptError, err: print str(err) self.usage() return ExitCode.EXCEPTION for o, a in opts: if o in ("-v", "--verbose"): logger().VERBOSE = True logger().HAL = True logger().DEBUG = True elif o in ("-d", "--debug"): logger().DEBUG = True elif o in ("-h", "--help"): self.usage() sys.exit(0) return 0 elif o in ("-o", "--output"): self._output = a elif o in ("-p", "--platform"): self._platform = a.upper() elif o in ("-m", "--module"): #_module = a.lower() self._module = a
def run_loaded_modules(self): from chipsec.module_common import ModuleResult failed = [] errors = [] warnings = [] passed = [] skipped = [] exceptions = [] executed = 0 exit_code = ExitCode() results = {} if not self._list_tags: logger().log("[*] running loaded modules ..") t = time.time() for (modx, modx_argv) in self.Loaded_Modules: executed += 1 if not self._list_tags: logger().start_module(modx.get_name()) # Run the module try: result = self.run_module(modx, modx_argv) except BaseException: exceptions.append(modx) exit_code.exception() result = ModuleResult.ERROR if logger().DEBUG: logger().log_bad(traceback.format_exc()) if self.failfast: raise # Module uses the old API display warning and try to run anyways if result == ModuleResult.DEPRECATED: exit_code.deprecated() logger().error('Module %s does not inherit BaseModule class' % str(modx)) # Populate results dictionary to export to JSON r = {} r['result'] = module_common.getModuleResultName(result) if modx_argv: r['arg'] = modx_argv results[modx.get_name()] = r if not self._list_tags: logger().end_module(modx.get_name()) if result is None or ModuleResult.ERROR == result: errors.append(modx) exit_code.error() elif False == result or ModuleResult.FAILED == result: failed.append(modx) exit_code.fail() elif True == result or ModuleResult.PASSED == result: passed.append(modx) elif ModuleResult.WARNING == result: exit_code.warning() warnings.append(modx) elif ModuleResult.SKIPPED == result: exit_code.skipped() skipped.append(modx) if self._json_out: results_json = json.dumps(results, sort_keys=True, indent=2, separators=(',', ': ')) chipsec.file.write_file(self._json_out, results_json) if not self._list_tags: logger().log("") logger().log( "[CHIPSEC] *************************** SUMMARY ***************************" ) if not self.no_time: logger().log("[CHIPSEC] Time elapsed %.3f" % (time.time() - t)) logger().log("[CHIPSEC] Modules total %d" % executed) logger().log("[CHIPSEC] Modules failed to run %d:" % len(errors)) for mod in errors: logger().error(str(mod)) logger().log("[CHIPSEC] Modules passed %d:" % len(passed)) for fmod in passed: logger().log_passed(str(fmod)) logger().log("[CHIPSEC] Modules failed %d:" % len(failed)) for fmod in failed: logger().log_failed(str(fmod)) logger().log("[CHIPSEC] Modules with warnings %d:" % len(warnings)) for fmod in warnings: logger().log_warning(str(fmod)) logger().log("[CHIPSEC] Modules skipped %d:" % len(skipped)) for fmod in skipped: logger().log_skipped(str(fmod)) if len(exceptions) > 0: logger().log("[CHIPSEC] Modules with Exceptions %d:" % len(exceptions)) for fmod in exceptions: logger().error(str(fmod)) logger().log( "[CHIPSEC] *****************************************************************" ) #logger().log( "[CHIPSEC] Version: %s"% self.get_chipsec_version() ) else: logger().log("[*] Available tags are:") for at in self.AVAILABLE_TAGS: logger().log(" %s" % at) return exit_code.get_code()
def create(self, start_driver): #self.init(start_driver) if logger().DEBUG: logger().log("[helper] OSX Helper created") return True
def load_user_modules(self): for import_path in self.IMPORT_PATHS: logger().log("[*] loading modules from \"%s\" .." % import_path) self.load_modules_from_path(import_path)
def read_virtual_mem(self, virt_address, length): if logger().HAL: logger().log("[mem] 0x{:016X}".format(virt_address)) phys_address = self.va2pa(virt_address) return self.helper.read_physical_mem(phys_address, length)
def delete(self, start_driver): if logger().DEBUG: logger().log("[helper] OSX Helper deleted") return True
def stop(self, start_driver): if logger().VERBOSE: logger().log("[helper] Helper stopped/unloaded") raise NotImplementedError()
def Run(self, args): # Due to talking raw to hardware, this action has some inevitable risk of # crashing the machine, so we need to flush the transaction log to ensure # we know when this happens. self.SyncTransactionLog() # Temporary extra logging for Ubuntu # TODO(user): Add generic hunt flag to notify syslog before running each # client action. if args.notify_syslog: syslog = logging.getLogger("chipsec_grr") syslog.setLevel(logging.INFO) syslog.addHandler(handlers.SysLogHandler(address="/dev/log")) syslog.info("%s: Runnning DumpFlashImage", config.CONFIG["Client.name"]) self.logs = [] self.chipsec_log = io.StringIO() if args.log_level: logger.logger().UTIL_TRACE = True if args.log_level == 2: logger.logger().VERBOSE = True logger.logger().logfile = self.chipsec_log logger.logger().LOG_TO_FILE = True # Create a temporary file to store the flash image. dest_fd, dest_pathspec = tempfiles.CreateGRRTempFileVFS( suffix=".flash") # Wrap most of Chipsec code to gather its logs in case of failure. try: # Initialise Chipsec (die early if unknown chipset) c = chipset.cs() # Platform = None, Start Driver = False c.init(None, False) s = spi.SPI(c) # Use hal.spi from chipsec to write BIOS to that file. with dest_fd: # Based on Chipsec code, rely on the address of BIOS(=1) region to # determine the size of the flash. _, limit, _ = s.get_SPI_region(1) spi_size = limit + 1 # Read args.chunk_size bytes at a time and heartbeat. bios = [] for i in range(0, spi_size, args.chunk_size): bios.extend(s.read_spi(i, args.chunk_size)) self.Progress() dest_fd.write(bytes(bios)) except (chipset.UnknownChipsetError, oshelper.OsHelperError) as err: # If the chipset is not recognised or if the helper threw an error, # report gracefully the error to the flow. if args.log_level: self.LogError(err) tempfiles.DeleteGRRTempFile(dest_pathspec.path) self.SendReply( rdf_chipsec_types.DumpFlashImageResponse(logs=["%s" % err], )) return except Exception as err: # pylint: disable=broad-except # In case an exception is raised, if the verbose mode # is enabled, return the raw logs from Chipsec. if args.log_level: self.LogError(err) tempfiles.DeleteGRRTempFile(dest_pathspec.path) raise if args.log_level: self.logs.extend(self.chipsec_log.getvalue().splitlines()) if args.notify_syslog: syslog.info("%s: DumpFlashImage has completed successfully", config.CONFIG["Client.name"]) self.SendReply( rdf_chipsec_types.DumpFlashImageResponse(path=dest_pathspec, logs=self.logs))
def start(self, start_driver, from_file=None): if logger().VERBOSE: logger().log("[helper] Helper started/loaded") raise NotImplementedError()
def delete(self, start_driver): if logger().VERBOSE: logger().log("[helper] Helper deleted") raise NotImplementedError()