Esempio n. 1
0
    def _ioctl(self, ioctl_code, in_buf, out_length):

        if not self.driver_loaded:
            _handle_error(
                "chipsec kernel driver is not loaded (in native API mode?)")

        out_buf = (c_char * out_length)()
        self.get_driver_handle()
        if logger().DEBUG: print_buffer(bytestostring(in_buf))
        try:
            out_buf = win32file.DeviceIoControl(self.driver_handle, ioctl_code,
                                                in_buf, out_length, None)
        except pywintypes.error as _err:
            err_status = _err.args[0] + 0x100000000
            if STATUS_PRIVILEGED_INSTRUCTION == err_status:
                err_msg = "HW Access Violation: DeviceIoControl returned STATUS_PRIVILEGED_INSTRUCTION (0x{:X})".format(
                    err_status)
                if logger().DEBUG: logger().error(err_msg)
                raise HWAccessViolationError(err_msg, err_status)
            else:
                _handle_error(
                    "HW Access Error: DeviceIoControl returned status 0x{:X} ({})"
                    .format(err_status, _err.args[2]), err_status)

        return out_buf
Esempio n. 2
0
    def get_ACPI_table_list(self):
        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 enumerate ACPI tables from physical memory..."
                )
            # find RSDT/XSDT table
            (is_xsdt, sdt_pa, sdt, sdt_header) = self.get_SDT()

            # cache RSDT/XSDT in the list of ACPI tables
            if sdt_pa is not None:
                self.tableList[bytestostring(
                    sdt_header.Signature)].append(sdt_pa)

            self.get_table_list_from_SDT(sdt, is_xsdt)
            self.get_DSDT_from_FADT()
        except oshelper.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 self.cs.use_native_api():
                if logger().HAL:
                    logger().log(
                        "[acpi] trying to enumerate ACPI tables using get_ACPI_table..."
                    )
                for t in ACPI_TABLES.keys():
                    table = self.cs.helper.get_ACPI_table(t)
                    if table: self.tableList[t].append(0)

        return self.tableList
Esempio n. 3
0
 def _find_RSDP_in_EFI(self):
     rsdp_pa = None
     rsdp = None
     if logger().HAL:
         logger().log(
             "[acpi] searching all EFI memory for RSDP (this may take a minute).."
         )
     CHUNK_SZ = 1024 * 1024  # 1MB
     (smram_base, smram_limit, smram_size) = self.cs.cpu.get_SMRAM()
     pa = smram_base - CHUNK_SZ
     while pa > CHUNK_SZ:
         membuf = self.cs.mem.read_physical_mem(pa, CHUNK_SZ)
         pos = bytestostring(membuf).find(ACPI_RSDP_SIG)
         if -1 != pos:
             rsdp_pa = pa + pos
             if logger().HAL:
                 logger().log(
                     "[acpi] found '{}' signature at 0x{:16X}. Checking if valid RSDP.."
                     .format(ACPI_RSDP_SIG, rsdp_pa))
             rsdp = self.read_RSDP(rsdp_pa)
             if rsdp.is_RSDP_valid():
                 if logger().HAL:
                     logger().log(
                         "[acpi] found RSDP in EFI memory: 0x{:016X}".
                         format(rsdp_pa))
                 break
         pa -= CHUNK_SZ
     return rsdp, rsdp_pa
Esempio n. 4
0
def parse_script(script, log_script=False):
    off = 0
    entry_type = 0
    s3_boot_script_entries = []
    len_s = len(script)

    if log_script: logger().log('[uefi] +++ S3 Resume Boot-Script +++\n')
    script_type, script_header_length = uefi_platform.id_s3bootscript_type(
        script, log_script)
    off += script_header_length

    while (off < len_s) and (
            entry_type != S3BootScriptOpcode.EFI_BOOT_SCRIPT_TERMINATE_OPCODE):
        entry_type, s3script_entry = uefi_platform.parse_s3bootscript_entry(
            script_type, script, off, log_script)
        # couldn't parse the next entry - return what has been parsed so far
        if s3script_entry is None: return s3_boot_script_entries
        s3_boot_script_entries.append(s3script_entry)
        off += s3script_entry.length

    if log_script: logger().log('[uefi] +++ End of S3 Resume Boot-Script +++')

    if logger().HAL:
        logger().log('[uefi] S3 Resume Boot-Script size: 0x{:X}'.format(off))
    if logger().HAL:
        logger().log(
            '\n[uefi] [++++++++++ S3 Resume Boot-Script Buffer ++++++++++]')
        print_buffer(bytestostring(script[:off]))

    return s3_boot_script_entries
Esempio n. 5
0
 def _find_RSDP_in_legacy_BIOS_segments(self):
     rsdp_pa = None
     rsdp = None
     membuf = self.cs.mem.read_physical_mem(0xE0000, 0x20000)
     membuf = bytestostring(membuf)
     pos = bytestostring(membuf).find(ACPI_RSDP_SIG)
     if -1 != pos:
         rsdp_pa = 0xE0000 + pos
         rsdp = self.read_RSDP(rsdp_pa)
         if rsdp.is_RSDP_valid():
             if logger().HAL:
                 logger().log(
                     "[acpi] found RSDP in BIOS E/F segments: 0x{:016X}".
                     format(rsdp_pa))
         else:
             rsdp_pa = None
     return rsdp, rsdp_pa
Esempio n. 6
0
 def __str__(self):
     _s = "{}+{:08X}h {}: Type {:02X}h".format(self.indent,self.Offset,self.name(),self.Type)
     if self.Guid: _s += " GUID {{{}}}".format(self.Guid)
     if self.Attributes: _s += " Attr {:04X}h".format(self.Attributes)
     if self.DataOffset: _s += " DataOffset {:04X}h".format(self.DataOffset)
     if self.Comments: _s += "Comments {}".format(self.Comments)
     _s += super(EFI_SECTION, self).__str__()
     return bytestostring(_s)
Esempio n. 7
0
 def get_table_list_from_SDT(self, sdt, is_xsdt):
     if logger().HAL: logger().log( '[acpi] Getting table list from entries in {}'.format('XSDT' if is_xsdt else 'RSDT') )
     for a in sdt.Entries:
         _sig = self.cs.mem.read_physical_mem( a, ACPI_TABLE_SIG_SIZE )
         _sig = bytestostring(_sig)
         if _sig not in ACPI_TABLES.keys():
             if logger().HAL: logger().warn( 'Unknown ACPI table signature: {}'.format(_sig) )
         self.tableList[ _sig ].append(a)
Esempio n. 8
0
 def get_EFI_variable(self, name, guid, filename=None):
     var = self.helper.get_EFI_variable(name, guid)
     if var:
         if filename: write_file(filename, var)
         if logger().UTIL_TRACE or logger().HAL:
             logger().log('[uefi] EFI variable {}:{} :'.format(guid, name))
             print_buffer(bytestostring(var))
     return var
Esempio n. 9
0
 def write_mmio_reg(self, phys_address, size, value):
     phys_address_lo = phys_address & 0xFFFFFFFF
     phys_address_hi = (phys_address >> 32) & 0xFFFFFFFF
     if size == 4:
         return edk2.writemem_dword(phys_address_lo, phys_address_hi, value)
     else:
         buf = bytestostring(struct.pack(size * "B", value))
         edk2.writemem(phys_address_lo, phys_address_hi, buf, size)
Esempio n. 10
0
 def find_EFI_Table( self, table_sig ):
     (smram_base,smram_limit,smram_size) = self.cs.cpu.get_SMRAM()
     CHUNK_SZ = 1024*1024 # 1MB
     if logger().HAL: logger().log( "[uefi] searching memory for EFI table with signature '{}' ..".format(table_sig) )
     table_pa,table_header,table,table_buf = None,None,None,None
     pa = smram_base - CHUNK_SZ
     isFound = False
     while pa > CHUNK_SZ:
         if logger().HAL: logger().log( '[uefi] reading 0x{:016X}..'.format(pa) )
         membuf = self.cs.mem.read_physical_mem( pa, CHUNK_SZ )
         pos = bytestostring(membuf).find( table_sig )
         if -1 != pos:
             table_pa = pa + pos
             if logger().HAL: logger().log( "[uefi] found signature '{}' at 0x{:016X}..".format(table_sig,table_pa) )
             if pos < (CHUNK_SZ - EFI_TABLE_HEADER_SIZE):
                 hdr = membuf[ pos : pos + EFI_TABLE_HEADER_SIZE ]
             else:
                 hdr = self.cs.mem.read_physical_mem( table_pa, EFI_TABLE_HEADER_SIZE )
             table_header = EFI_TABLE_HEADER( *struct.unpack_from( EFI_TABLE_HEADER_FMT, hdr ) )
             # do some sanity checks on the header
             if 0 != table_header.Reserved or                 \
                0 == table_header.CRC32    or                 \
                table_header.Revision not in EFI_REVISIONS or \
                table_header.HeaderSize > MAX_EFI_TABLE_SIZE:
                 if logger().HAL:
                     logger().log( "[uefi] found '{}' at 0x{:016X} but doesn't look like an actual table. keep searching..".format(table_sig,table_pa) )
                     logger().log( table_header )
             else:
                 isFound = True
                 if logger().HAL: logger().log( "[uefi] found EFI table at 0x{:016X} with signature '{}'..".format(table_pa,table_sig) )
                 table_size = struct.calcsize( EFI_TABLES[table_sig]['fmt'] )
                 if pos < (CHUNK_SZ - EFI_TABLE_HEADER_SIZE - table_size):
                     table_buf = membuf[ pos : pos + EFI_TABLE_HEADER_SIZE + table_size ]
                 else:
                     table_buf = self.cs.mem.read_physical_mem( table_pa, EFI_TABLE_HEADER_SIZE + table_size )
                 table = EFI_TABLES[table_sig]['struct']( *struct.unpack_from( EFI_TABLES[table_sig]['fmt'], table_buf[EFI_TABLE_HEADER_SIZE:] ) )
                 if logger().HAL:
                     print_buffer( bytestostring(table_buf) )
                     logger().log( '[uefi] {}:'.format(EFI_TABLES[table_sig]['name']) )
                     logger().log( table_header )
                     logger().log( table )
                 break
         pa -= CHUNK_SZ
     if (not isFound) and logger().HAL: logger().log( "[uefi] could not find EFI table with signature '{}'".format(table_sig) )
     return (isFound,table_pa,table_header,table,table_buf)
Esempio n. 11
0
def print_efi_variable( offset, efi_var_buf, EFI_var_header, efi_var_name, efi_var_data, efi_var_guid, efi_var_attributes ):
    logger().log( '\n--------------------------------' )
    logger().log( 'EFI Variable (offset = 0x{:X}):'.format(offset) )
    logger().log( '--------------------------------' )

    # Print Variable Name
    logger().log( u'Name      : {}'.format(efi_var_name) )
    # Print Variable GUID
    logger().log( 'Guid      : {}'.format(efi_var_guid) )

    # Print Variable State
    if EFI_var_header:
        if 'State' in EFI_var_header._fields:
            state = getattr(EFI_var_header, 'State')
            state_str = 'State     :'
            if uefi_platform.IS_VARIABLE_STATE( state, uefi_platform.VAR_IN_DELETED_TRANSITION ):
                state_str = state_str + ' IN_DELETED_TRANSITION +'
            if uefi_platform.IS_VARIABLE_STATE( state, uefi_platform.VAR_DELETED ):
                state_str = state_str + ' DELETED +'
            if uefi_platform.IS_VARIABLE_STATE( state, uefi_platform.VAR_ADDED ):
                state_str = state_str + ' ADDED +'
            logger().log( state_str )

        # Print Variable Complete Header
        if logger().VERBOSE:
            if EFI_var_header.__str__:
                logger().log( EFI_var_header )
            else:
                logger().log( 'Decoded Header ({}):'.format(uefi_platform.EFI_VAR_DICT[ uefi_platform.FWType.EFI_FW_TYPE_UEFI ]['name']) )
                for attr in EFI_var_header._fields:
                    logger().log( '{} = {:X}'.format('{0:<16}'.format(attr), getattr(EFI_var_header, attr)) )

    attr_str = ('Attributes: 0x{:X} ( {} )'.format(efi_var_attributes, get_attr_string( efi_var_attributes )))
    logger().log( attr_str )

    # Print Variable Data
    logger().log( 'Data:' )
    print_buffer( bytestostring(efi_var_data) )

    # Print Variable Full Contents
    if logger().VERBOSE:
        logger().log( 'Full Contents:' )
        if not efi_var_buf is None:
            print_buffer( bytestostring(efi_var_buf) )
Esempio n. 12
0
    def find_s3_bootscript( self ):
        found                = False
        BootScript_addresses = []

        efivars = self.list_EFI_variables()
        if efivars is None:
            logger().error( 'Could not enumerate UEFI variables at runtime' )
            return (found,BootScript_addresses)
        if logger().HAL: logger().log( "[uefi] searching for EFI variable(s): " + str(S3_BOOTSCRIPT_VARIABLES) )

        for efivar_name in efivars:
            (off, buf, hdr, data, guid, attrs) = efivars[efivar_name][0]
            if efivar_name in S3_BOOTSCRIPT_VARIABLES:
                if logger().HAL: logger().log( "[uefi] found: {} {{{}}} {} variable".format(efivar_name,guid,get_attr_string(attrs)) )
                if logger().HAL:
                    logger().log('[uefi] {} variable data:'.format(efivar_name))
                    print_buffer( bytestostring(data) )

                varsz = len(data)
                if   4 == varsz: AcpiGlobalAddr_fmt = '<L'
                elif 8 == varsz: AcpiGlobalAddr_fmt = '<Q'
                else:
                    logger().error( "Unrecognized format of '{}' UEFI variable (data size = 0x{:X})".format(efivar_name,varsz) )
                    break
                AcpiGlobalAddr = struct.unpack_from( AcpiGlobalAddr_fmt, data )[0]
                if 0 == AcpiGlobalAddr:
                    logger().error( "Pointer to ACPI Global Data structure in {} variable is 0".format(efivar_name) )
                    break
                if logger().HAL: logger().log( "[uefi] Pointer to ACPI Global Data structure: 0x{:016X}".format( AcpiGlobalAddr ) )
                if logger().HAL: logger().log( "[uefi] Decoding ACPI Global Data structure.." )
                AcpiVariableSet = self.helper.read_physical_mem( AcpiGlobalAddr, ACPI_VARIABLE_SET_STRUCT_SIZE )
                if logger().HAL:
                    logger().log('[uefi] AcpiVariableSet structure:')
                    print_buffer( bytestostring(AcpiVariableSet) )
                AcpiVariableSet_fmt = '<6Q'
                #if len(AcpiVariableSet) < struct.calcsize(AcpiVariableSet_fmt):
                #    logger().error( 'Unrecognized format of AcpiVariableSet structure' )
                #    return (False,0)
                AcpiReservedMemoryBase, AcpiReservedMemorySize, S3ReservedLowMemoryBase, AcpiBootScriptTable, RuntimeScriptTableBase, AcpiFacsTable = struct.unpack_from( AcpiVariableSet_fmt, AcpiVariableSet )
                if logger().HAL: logger().log( '[uefi] ACPI Boot-Script table base = 0x{:016X}'.format(AcpiBootScriptTable) )
                found   = True
                BootScript_addresses.append( AcpiBootScriptTable )
                #break
        return (found,BootScript_addresses)
Esempio n. 13
0
   def __str__(self):
       return """Header:
 Signature     : {}
 Revision      : {}
 HeaderSize    : 0x{:08X}
 CRC32         : 0x{:08X}
 Reserved      : 0x{:08X}""".format(bytestostring(self.Signature),
                                    EFI_SYSTEM_TABLE_REVISION(self.Revision),
                                    self.HeaderSize, self.CRC32,
                                    self.Reserved)
Esempio n. 14
0
 def __str__(self):
     schecksum = ('{:04X}h ({:04X}h) *** checksum mismatch ***'.format(
         self.Checksum,
         self.CalcSum)) if self.CalcSum != self.Checksum else (
             '{:04X}h'.format(self.Checksum))
     _s = "\n{}+{:08X}h {}\n{}Type {:02X}h, Attr {:08X}h, State {:02X}h, Size {:06X}h, Checksum {}".format(
         self.indent, self.Offset, self.name(), self.indent, self.Type,
         self.Attributes, self.State, self.Size, schecksum)
     _s += (super(EFI_FILE, self).__str__() + '\n')
     return bytestostring(_s)
Esempio n. 15
0
def get_json_results(json_file):
    file_data = chipsec.file.read_file(json_file)
    if file_data == 0:
        return None
    try:
        json_data = json.loads(bytestostring(file_data))
    except:
        logger().error("Unable to load JSON file: {}".format(json_file))
        return None
    return json_data
Esempio n. 16
0
 def dump_ACPI_table(self, name, isfile=False):
     acpi_tables = self.get_parse_ACPI_table(name, isfile)
     for acpi_table in acpi_tables:
         (table_header, table, table_header_blob, table_blob) = acpi_table
         logger().log(
             "=================================================================="
         )
         logger().log("ACPI Table: {}".format(name))
         logger().log(
             "=================================================================="
         )
         # print table header
         logger().log(table_header)
         print_buffer(bytestostring(table_header_blob))
         # print table contents
         logger().log('')
         logger().log(table)
         print_buffer(bytestostring(table_blob))
         logger().log('')
Esempio n. 17
0
    def __str__(self):
        return """
Header (Windows)
----------------
VendorGuid= {{{:08X}-{:04X}-{:04X}-{:4}-{:6}}}
Size      = 0x{:08X}
DataOffset= 0x{:08X}
DataSize  = 0x{:08X}
Attributes= 0x{:08X}
""".format( self.guid0, self.guid1, self.guid2, bytestostring(codecs.encode(self.guid3[:2],'hex')).upper(), bytestostring(codecs.encode(self.guid3[-6::],'hex')).upper(), self.Size, self.DataOffset, self.DataSize, self.Attributes )
Esempio n. 18
0
def FvSum16(buffer):
    sum16 = 0
    buffer = bytestostring(buffer)
    blen = len(buffer) // 2
    i = 0
    while i < blen:
        el16 = ord(buffer[2 * i]) | (ord(buffer[2 * i + 1]) << 8)
        sum16 = (sum16 + el16) & 0xffff
        i = i + 1
    return sum16
Esempio n. 19
0
 def mem_read(self):
     self.logger.log(
         '[CHIPSEC] Reading buffer from memory: PA = 0x{:016X}, len = 0x{:X}..'
         .format(self.phys_address, self.buffer_length))
     buffer = self.cs.mem.read_physical_mem(self.phys_address,
                                            self.buffer_length)
     if self.file_name:
         write_file(self.file_name, buffer)
         self.logger.log("[CHIPSEC] Written 0x{:X} bytes to '{}'".format(
             len(buffer), self.file_name))
     else:
         print_buffer(bytestostring(buffer))
Esempio n. 20
0
    def kern_get_EFI_variable_full(self, name, guid):
        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" }
        off = 0
        data = ""
        attr = 0
        buf = list()
        hdr = 0
        base = 12
        namelen = len(name)
        header_size = 52
        data_size = header_size + namelen
        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('13I'+str(namelen)+'s', data_size, guid0, guid1, guid2, guid3, guid4, guid5, guid6, guid7, guid8, guid9, guid10, namelen, name.encode())
        buffer = array.array("B", in_buf)
        stat = self.ioctl(IOCTL_GET_EFIVAR, buffer)
        new_size, status = struct.unpack( "2I", buffer[:8])

        if (status == 0x5):
            data_size = new_size + header_size + namelen # size sent by driver + size of header (size + guid) + size of name
            in_buf = struct.pack('13I'+str(namelen+new_size)+'s', data_size, guid0, guid1, guid2, guid3, guid4, guid5, guid6, guid7, guid8, guid9, guid10, namelen, name.encode())
            buffer = array.array("B", in_buf)
            try:
                stat = self.ioctl(IOCTL_GET_EFIVAR, buffer)
            except IOError:
                if logger().DEBUG: logger().error("IOError IOCTL GetUEFIvar\n")
                return (off, buf, hdr, None, guid, attr)
            new_size, status = struct.unpack( "2I", buffer[:8])

        if (new_size > data_size):
            if logger().DEBUG: logger().error( "Incorrect size returned from driver" )
            return (off, buf, hdr, None, guid, attr)

        if (status > 0):
            if logger().DEBUG: logger().error( "Reading variable (GET_EFIVAR) did not succeed: {}".format(status_dict[status]))
            data = ""
            guid = 0
            attr = 0
        else:
            data = buffer[base:base+new_size].tostring()
            attr = struct.unpack( "I", buffer[8:12])[0]
        return (off, buf, hdr, bytestostring(data), guid, attr)
Esempio n. 21
0
 def find_smmc(self, start, end):
     chunk_sz = 1024 * 8  #8KB chunks
     phys_address = start
     found_at = 0
     while phys_address <= end:
         buffer = self.cs.mem.read_physical_mem(phys_address, chunk_sz)
         buffer = bytestostring(buffer)
         offset = buffer.find('smmc')
         if offset != -1:
             found_at = phys_address + offset
             break
         phys_address += chunk_sz
     return found_at
Esempio n. 22
0
 def __str__(self):
     schecksum = ('{:04X}h ({:04X}h) *** checksum mismatch ***'.format(
         self.Checksum,
         self.CalcSum)) if self.CalcSum != self.Checksum else (
             '{:04X}h'.format(self.Checksum))
     _s = "\n{}{} +{:08X}h {{{}}}: ".format(self.indent,
                                            type(self).__name__,
                                            self.Offset, self.Guid)
     _s += "Size {:08X}h, Attr {:08X}h, HdrSize {:04X}h, ExtHdrOffset {:08X}h, Checksum {}".format(
         self.Size, self.Attributes, self.HeaderSize, self.ExtHeaderOffset,
         schecksum)
     _s += super(EFI_FV, self).__str__()
     return bytestostring(_s)
Esempio n. 23
0
    def run(self, module_argv):
        # Log the start of the test
        self.logger.start_test('Current Processor Information:')
        self.res = ModuleResult.INFORMATION

        # Determine number of threads to check
        thread_count = 1
        if not self.cs.helper.is_efi():
            thread_count = self.cs.msr.get_cpu_thread_count()

        for thread in range(thread_count):
            # Handle processor binding so we are allways checking processor 0
            # for this example.  No need to do this in UEFI Shell.
            if not self.cs.helper.is_efi():
                self.cs.helper.set_affinity(thread)

            # Display thread
            self.logger.log('[*] Thread {:04d}'.format(thread))

            # Get processor brand string
            brand = ''
            for eax_val in [0x80000002, 0x80000003, 0x80000004]:
                regs = self.cs.cpu.cpuid(eax_val, 0)
                for i in range(4):
                    brand += bytestostring(struct.pack('<I', regs[i]))
            brand = brand.rstrip('\x00')
            self.logger.log('[*] Processor: {}'.format(brand))

            # Get processor version information
            (eax, ebx, ecx, edx) = self.cs.cpu.cpuid(0x01, 0x00)
            stepping = eax & 0xF
            model = (eax >> 4) & 0xF
            family = (eax >> 8) & 0xF
            if family == 0x0F or family == 0x06:
                model = ((eax >> 12) & 0xF0) | model
            if family == 0x0F:
                family = ((eax >> 20) & 0xFF) | family
            self.logger.log(
                '[*]            Family: {:02X} Model: {:02X} Stepping: {:01X}'.
                format(family, model, stepping))

            # Get microcode revision
            microcode_rev = self.cs.read_register_field('IA32_BIOS_SIGN_ID',
                                                        'Microcode',
                                                        cpu_thread=thread)
            self.logger.log(
                '[*]            Microcode: {:08X}'.format(microcode_rev))
            self.logger.log('[*]')

        self.logger.log_information_check('Processor information displayed')
        return self.res
Esempio n. 24
0
    def mem_search(self):
        buffer = self.cs.mem.read_physical_mem(self.phys_address, self.length)
        buffer = bytestostring(buffer)
        offset = buffer.find(self.value)

        if (offset != -1):
            self.logger.log(
                '[CHIPSEC] Search buffer from memory: PA = 0x{:016X}, len = 0x{:X}, target address= 0x{:X}..'
                .format(self.phys_address, self.length,
                        self.phys_address + offset))
        else:
            self.logger.log(
                '[CHIPSEC] Search buffer from memory: PA = 0x{:016X}, len = 0x{:X}, can not find the target in the searched range..'
                .format(self.phys_address, self.length))
Esempio n. 25
0
 def AddElement(self, cmd, args, ret):
     try:
         margs = '({})'.format(','.join(str(i) for i in args))
     except:
         margs = str(args)
     if isinstance(ret, bytes):
         ret = bytestostring(ret)
     if str(cmd) in self.data:
         if margs in self.data[str(cmd)]:
             #using insert opposed to append so that it creates last in first out when using pop command within getElement
             self.data[str(cmd)][margs].insert(0, str(ret))
         else:
             self.data[str(cmd)][margs] = [str(ret)]
     else:
         self.data[str(cmd)] = {margs: [str(ret)]}
Esempio n. 26
0
    def vmem_read(self):
        self.logger.log(
            '[CHIPSEC] Reading buffer from memory: VA = 0x{:016X}, len = 0x{:X}.'
            .format(self.virt_address, self.size))
        try:
            buffer = self._vmem.read_virtual_mem(self.virt_address, self.size)
        except (TypeError, OSError):
            self.logger.error('Error mapping VA to PA.')
            return

        if self.buf_file:
            write_file(self.buf_file, buffer)
            self.logger.log("[CHIPSEC] Written 0x{:X} bytes to '{}'".format(
                len(buffer), self.buf_file))
        else:
            print_buffer(bytestostring(buffer))
Esempio n. 27
0
 def _find_RSDP_in_EBDA(self):
     rsdp_pa = None
     rsdp    = None
     if logger().HAL: logger().log( "[acpi] searching RSDP in EBDA.." )
     ebda_ptr_addr = 0x40E
     ebda_addr = struct.unpack('<H', self.cs.mem.read_physical_mem( ebda_ptr_addr, 2 ))[0] << 4
     if ebda_addr > 0x400 and ebda_addr < 0xA0000:
         membuf = self.cs.mem.read_physical_mem(ebda_addr, 0xA0000 - ebda_addr)
         pos = bytestostring(membuf).find( ACPI_RSDP_SIG )
         if -1 != pos:
             rsdp_pa = ebda_addr + pos
             rsdp = self.read_RSDP(rsdp_pa)
             if rsdp.is_RSDP_valid():
                 if logger().HAL: logger().log( "[acpi] found RSDP in EBDA at: 0x{:016X}".format(rsdp_pa) )
             else:
                 rsdp_pa = None
     return rsdp, rsdp_pa
Esempio n. 28
0
    def vmem_search(self):
        try:
            buffer = self._vmem.read_virtual_mem(self.virt_address, self.size)
        except (TypeError, OSError):
            self.logger.error('Error mapping VA to PA.')
            return

        buffer = bytestostring(buffer)
        offset = buffer.find(self.value)

        self.logger.log("[CHIPSEC] Search buffer for '{}':".format(self.value))
        self.logger.log('          VA = 0x{:016X}, len = 0x{:X}'.format(
            self.virt_address, self.size))
        if offset != -1:
            self.logger.log(
                '[CHIPSEC] Target address = 0x{:X}.'.format(self.virt_address +
                                                            offset))
        else:
            self.logger.log(
                '[CHIPSEC] Could not find the target in the searched range.')
Esempio n. 29
0
    def set_EFI_variable( self, name, guid, data, datasize, attrs ):
        var     = bytes(0) if data     is None else data
        var_len = len(var) if datasize is None else datasize
        if isinstance(attrs, (str, bytes)):
            attrs_data = "{message:\x00<{fill}}".format(message=bytestostring(attrs), fill=8)[:8]
            attrs = struct.unpack("Q", stringtobytes(attrs_data))[0]

        if attrs is None:
            if self.SetFirmwareEnvironmentVariable is not None:
                if logger().DEBUG: logger().log( "[helper] -> SetFirmwareEnvironmentVariable( name='{}', GUID='{}', length=0x{:X} )..".format(name, "{{{}}}".format(guid), var_len) )
                ntsts = self.SetFirmwareEnvironmentVariable( name, "{{{}}}".format(guid), var, var_len )
        else:
            if self.SetFirmwareEnvironmentVariableEx is not None:
                if logger().DEBUG: logger().log( "[helper] -> SetFirmwareEnvironmentVariableEx( name='{}', GUID='{}', length=0x{:X}, attrs=0x{:X} )..".format(name, "{{{}}}".format(guid), var_len, attrs) )
                ntsts = self.SetFirmwareEnvironmentVariableEx( name, "{{{}}}".format(guid), var, var_len, attrs )
        if 0 != ntsts:
            status = 0 # EFI_SUCCESS
        else:
            status = kernel32.GetLastError()
            if logger().DEBUG: logger().error( 'SetFirmwareEnvironmentVariable[Ex] returned error: {}'.format(WinError()) )
            #raise WinError(errno.EIO, "Unable to set EFI variable")
        return status
Esempio n. 30
0
    def get_string_list(self, raw_data):
        ret_val = []

        if logger().HAL: logger().log('Getting strings from structure')
        raw_data_size = len(raw_data)
        header = self.get_header(raw_data)
        if header is None:
            return None
        if header.Length + SMBIOS_STRUCT_TERM_SIZE > raw_data_size:
            if logger().HAL:
                logger().log('- Data buffer too small for structure')
            return None
        if header.Length + SMBIOS_STRUCT_TERM_SIZE == raw_data_size:
            if logger().HAL: logger().log('+ No strings in this structure')
            return ret_val

        index = 0
        tmp_offset = header.Length
        while tmp_offset + index + 1 < raw_data_size:
            (value, ) = struct.unpack_from('=B', raw_data[tmp_offset + index:])
            if value == 0:
                if logger().HAL:
                    logger().log(
                        '+ Unpacking string of size {:d}'.format(index))
                (string, ) = struct.unpack_from('={:d}s'.format(index),
                                                raw_data[tmp_offset:])
                string = bytestostring(string)
                if logger().HAL: logger().log('+ Found: {:s}'.format(string))
                ret_val.append(string)
                tmp_offset += index + 1
                index = 0
                continue
            index += 1

        if logger().HAL:
            logger().log('+ Found {:d} strings'.format(len(ret_val)))
        return ret_val