Example #1
0
    def _chipsec_cs(self,
                    arg,
                    helper_class=mock_helper.TestHelper,
                    platform=None,
                    pch=None):
        """Run the chipsec chipset commands

        Each test may setup a virtual helper to emulate the expected behaviour
        from the hardware. If no helper is provided, TestHelper will be used.
        It verifies that no error is being reported. self.log will be populated
        with the output.
        """
        _cs = chipset.cs()
        _cs.helper.helper = helper_class()
        _cs.init_xml_configuration()
        logger.logger().HAL = True
        logger.logger().VERBOSE = True
        logger.logger().set_log_file(self.log_file)
        try:
            _cs.init(platform, pch, True)
            ret = getattr(_cs, arg.split()[0])()
        finally:
            logger.logger().close()
        with open(self.log_file, 'rb') as log:
            self.log = log.read()
        return ret
Example #2
0
    def Run(self, args):
        self.logs = []
        self.chipsec_log = StringIO.StringIO()

        if args.logging:
            self.logs.append("Dumping %s" % args.table_signature)

            logger.logger().logfile = self.chipsec_log
            logger.logger().LOG_TO_FILE = True

        # 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)
            a = acpi.ACPI(c)

            acpi_tables_raw = a.get_ACPI_table(args.table_signature)
            acpi_tables = []

            for i, table_address in enumerate(
                    a.tableList[args.table_signature]):
                table_header, table_content = acpi_tables_raw[i]
                table_blob = table_header + table_content

                acpi_tables.append(
                    rdf_chipsec_types.ACPITableData(
                        table_address=table_address, table_blob=table_blob))
        except (chipset.UnknownChipsetError, OSError) as err:
            # Expected errors that might happen on the client
            # If the chipset is unknown or we encountered an error due to reading
            # an area we do not have access to using /dev/mem, simply return an
            # error message.
            if args.logging:
                self.LogError(err)
            self.SendReply(
                rdf_chipsec_types.DumpACPITableResponse(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.logging:
                self.LogError(err)
            raise

        if not acpi_tables:
            self.logs.append("No ACPI table with signature %s." %
                             args.table_signature)
        else:
            self.logs.append(
                "ACPI table with signature %s has been successfully dumped." %
                args.table_signature)

        if args.logging:
            self.logs.extend(self.chipsec_log.getvalue().splitlines())

        self.SendReply(
            rdf_chipsec_types.DumpACPITableResponse(acpi_tables=acpi_tables,
                                                    logs=self.logs))
Example #3
0
    def __init__(self, argv):
        self.VERBOSE               = False
        self.CHIPSEC_FOLDER        = os.path.abspath(chipsec.file.get_main_dir())
        self.CHIPSEC_LOADED_AS_EXE = chipsec.file.main_is_frozen()
        self.USER_MODULE_TAGS      = []
        self.ZIP_MODULES_RE        = None
        self.Import_Path           = "chipsec.modules."
        self.Modules_Path          = os.path.join(self.CHIPSEC_FOLDER,"chipsec","modules")
        self.IMPORT_PATHS          = []
        self.Loaded_Modules        = []
        self._list_tags            = False
        self.AVAILABLE_TAGS        = []
        self.MODPATH_RE            = re.compile("^\w+(\.\w+)*$")
        self.failfast              = False
        self.no_time               = False
        self._output               = 'chipsec.log'
        self._module               = None
        self._module_argv          = None
        self._platform             = None
        self._driver_exists        = False
        self._no_driver            = False
        self._unkownPlatform       = True
        self._list_tags            = False
        self._json_out             = None
        self.version               = defines.get_version()

        self.argv = argv
        self._cs = chipset.cs()
Example #4
0
    def __init__(self, argv):
        self.VERBOSE = False
        self.CHIPSEC_FOLDER = os.path.abspath(chipsec.file.get_main_dir())
        self.CHIPSEC_LOADED_AS_EXE = chipsec.file.main_is_frozen()
        self.USER_MODULE_TAGS = []
        self.ZIP_MODULES_RE = None
        self.Import_Path = "chipsec.modules."
        self.Modules_Path = os.path.join(self.CHIPSEC_FOLDER, "chipsec",
                                         "modules")
        self.IMPORT_PATHS = []
        self.Loaded_Modules = []
        self._list_tags = False
        self.AVAILABLE_TAGS = []
        self.MODPATH_RE = re.compile("^\w+(\.\w+)*$")
        self.failfast = False
        self.no_time = False
        self._output = 'chipsec.log'
        self._module = None
        self._module_argv = None
        self._platform = None
        self._pch = None
        self._driver_exists = False
        self._no_driver = False
        self._unkownPlatform = True
        self._list_tags = False
        self._json_out = None
        self.version = defines.get_version()

        self.argv = argv
        self._cs = chipset.cs()
Example #5
0
 def __init__(self, argv):
     self.VERBOSE = False
     self.CHIPSEC_FOLDER = os.path.abspath(chipsec.file.get_main_dir())
     self.CHIPSEC_LOADED_AS_EXE = chipsec.file.main_is_frozen()
     self.USER_MODULE_TAGS = []
     self.ZIP_MODULES_RE = None
     self.Import_Path = "chipsec.modules."
     self.Modules_Path = os.path.join(self.CHIPSEC_FOLDER, "chipsec",
                                      "modules")
     self.IMPORT_PATHS = []
     self.Loaded_Modules = []
     self._list_tags = False
     self.AVAILABLE_TAGS = []
     self.MODPATH_RE = re.compile("^\w+(\.\w+)*$")
     self.failfast = False
     self.no_time = False
     self._output = 'chipsec.log'
     self._module = None
     self._module_argv = None
     self._platform = None
     self._driver_exists = False
     self._no_driver = False
     self._unkownPlatform = True
     self._list_tags = False
     self.version = "    "
     self.VERSION_FILE = os.path.join(self.CHIPSEC_FOLDER, "chipsec",
                                      "VERSION")
     if os.path.exists(self.VERSION_FILE):
         with open(self.VERSION_FILE, "r") as verFile:
             self.version = verFile.read()
     self.argv = argv
     self.parse_args()
     from chipsec.chipset import cs
     self._cs = cs()
Example #6
0
 def __init__(self, argv):
     self.VERBOSE = False
     self.CHIPSEC_FOLDER = os.path.abspath(chipsec.file.get_main_dir())
     self.CHIPSEC_LOADED_AS_EXE = chipsec.file.main_is_frozen()
     self.USER_MODULE_TAGS = []
     self.ZIP_MODULES_RE = None
     self.Import_Path             = "chipsec.modules."
     self.Modules_Path            = os.path.join(self.CHIPSEC_FOLDER,"chipsec","modules")
     self.IMPORT_PATHS            = []
     self.Loaded_Modules  = []
     self._list_tags = False
     self.AVAILABLE_TAGS = []
     self.MODPATH_RE      = re.compile("^\w+(\.\w+)*$")
     self.failfast = False
     self.no_time = False
     self._output         = 'chipsec.log'
     self._module         = None
     self._module_argv    = None
     self._platform       = None
     self._start_svc      = True
     self._no_driver      = False
     self._unkownPlatform = True
     self._list_tags      = False
     self.version="    "
     self.VERSION_FILE = os.path.join( self.CHIPSEC_FOLDER , "VERSION" )
     if os.path.exists( self.VERSION_FILE ):
         with open(self.VERSION_FILE, "r") as verFile:
             self.version = verFile.read()
     self.argv = argv
     self.parse_args()
     from chipsec.chipset import cs
     self._cs = cs()
Example #7
0
  def Run(self, args):
    self.logs = []
    self.chipsec_log = StringIO.StringIO()

    if args.logging:
      self.logs.append("Dumping %s" % args.table_signature)

      logger.logger().logfile = self.chipsec_log
      logger.logger().LOG_TO_FILE = True

    # 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)
      a = acpi.ACPI(c)

      acpi_tables_raw = a.get_ACPI_table(args.table_signature)
      acpi_tables = []

      for i, table_address in enumerate(a.tableList[args.table_signature]):
        table_header, table_content = acpi_tables_raw[i]
        table_blob = table_header + table_content

        acpi_tables.append(
            chipsec_types.ACPITableData(
                table_address=table_address, table_blob=table_blob))
    except (chipset.UnknownChipsetError, OSError) as err:
      # Expected errors that might happen on the client
      # If the chipset is unknown or we encountered an error due to reading
      # an area we do not have access to using /dev/mem, simply return an
      # error message.
      if args.logging:
        self.LogError(err)
      self.SendReply(chipsec_types.DumpACPITableResponse(
          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.logging:
        self.LogError(err)
      raise

    if not acpi_tables:
      self.logs.append(
          "No ACPI table with signature %s." % args.table_signature)
    else:
      self.logs.append(
          "ACPI table with signature %s has been successfully dumped." %
          args.table_signature)

    if args.logging:
      self.logs.extend(self.chipsec_log.getvalue().splitlines())

    self.SendReply(
        chipsec_types.DumpACPITableResponse(
            acpi_tables=acpi_tables, logs=self.logs))
Example #8
0
 def __init__(self):
     self._cs = cs()
     self.VERBOSE = False
     self.CHIPSEC_LOADED_AS_EXE = chipsec.file.main_is_frozen()
     self.USER_MODULE_TAGS = []
     self.ZIP_MODULES_RE = None
     self.Import_Path = "chipsec.modules."
     self.Modules_Path = os.path.join(CHIPSEC_FOLDER, "chipsec", "modules")
     self.IMPORT_PATHS = []
     self.Loaded_Modules = []
     self._list_tags = False
     self.AVAILABLE_TAGS = []
     self.MODPATH_RE = re.compile("^\w+(\.\w+)*$")
     self.failfast = False
     self.no_time = False
Example #9
0
 def __init__(self):
     self._cs = cs()
     self.VERBOSE = False
     self.CHIPSEC_LOADED_AS_EXE = chipsec.file.main_is_frozen()
     self.USER_MODULE_TAGS = []
     self.ZIP_MODULES_RE = None
     self.Import_Path             = "chipsec.modules."
     self.Modules_Path            = os.path.join(CHIPSEC_FOLDER,"chipsec","modules")
     self.IMPORT_PATHS            = []
     self.Loaded_Modules  = []
     self._list_tags = False
     self.AVAILABLE_TAGS = []
     self.MODPATH_RE      = re.compile("^\w+(\.\w+)*$")
     self.failfast = False
     self.no_time = False
Example #10
0
    def _chipsec_util(self, arg, helper_class=mock_helper.TestHelper):
        """Run the chipsec_util command with the arguments.

        Each test may setup a virtual helper to emulate the expected behaviour
        from the hardware. If no helper is provided, TestHelper will be used.
        It verifies that no error is being reported. self.log will be populated
        with the output.
        """
        oshelper.Helper.registry = [(helper_class.__name__, helper_class)]
        chipsec_util._cs = chipset.cs()
        util = chipsec_util.ChipsecUtil()
        util.VERBOSE = True
        util.set_logfile(self.log_file)
        err_code = util.main(["chipsec_utils.py"] + arg.split())
        logger.logger().close()
        self.log = open(self.log_file).read()
        self.assertEqual(err_code, 0)
Example #11
0
    def _chipsec_util(self, arg, helper_class=mock_helper.TestHelper):
        """Run the chipsec_util command with the arguments.

        Each test may setup a virtual helper to emulate the expected behaviour
        from the hardware. If no helper is provided, TestHelper will be used.
        It verifies that no error is being reported. self.log will be populated
        with the output.
        """
        oshelper.Helper.registry = [(helper_class.__name__, helper_class)]
        chipsec_util._cs = chipset.cs()
        util = chipsec_util.ChipsecUtil()
        util.VERBOSE = True
        util.set_logfile(self.log_file)
        err_code = util.main(["chipsec_utils.py"] + arg.split())
        logger.logger().close()
        self.log = open(self.log_file).read()
        self.assertEqual(err_code, 0)
Example #12
0
    def _chipsec_util(self, arg, helper_class=mock_helper.TestHelper):
        """Run the chipsec_util command with the arguments.

        Each test may setup a virtual helper to emulate the expected behaviour
        from the hardware. If no helper is provided, TestHelper will be used.
        It verifies that no error is being reported. self.log will be populated
        with the output.
        """
        chipsec_util._cs = chipset.cs()
        chipsec_util._cs.helper.helper = helper_class()
        util = chipsec_util.ChipsecUtil(arg.split())
        util.VERBOSE = True
        logger.logger().HAL = True
        logger.logger().set_log_file(self.log_file)
        err_code = util.main()
        logger.logger().close()
        log = open(self.log_file, 'rb')
        self.log = log.read()
        log.close()
        self.assertEqual(err_code, 0)
Example #13
0
    def __init__(self, argv):
        self.global_usage = "CHIPSEC UTILITIES\n\n" + \
                   "All numeric values are in hex\n" + \
                   "<width> is in {1, byte, 2, word, 4, dword}\n\n"
        self.commands = {}
        # determine if CHIPSEC is loaded as chipsec_*.exe or in python
        self.CHIPSEC_LOADED_AS_EXE = True if (hasattr(sys, "frozen") or hasattr(sys, "importers")) else False

        self._platform       = None
        self._unkownPlatform = True
        self._no_driver      = False

        self.show_help = False
        self.help_cmd  = None

        # parse command-line arguments
        self._cmd_args       = None
        self.argv = argv
        self.parse_args()

        from chipsec.chipset import cs
        self._cs = cs()
Example #14
0
    def __init__(self, argv):
        self.global_usage = "CHIPSEC UTILITIES\n\n" + \
                   "All numeric values are in hex\n" + \
                   "<width> is in {1, byte, 2, word, 4, dword}\n\n"
        self.commands = {}
        # determine if CHIPSEC is loaded as chipsec_*.exe or in python
        self.CHIPSEC_LOADED_AS_EXE = True if (
            hasattr(sys, "frozen") or hasattr(sys, "importers")) else False

        self._platform = None
        self._unkownPlatform = True
        self._no_driver = False

        self.show_help = False
        self.help_cmd = None

        # parse command-line arguments
        self._cmd_args = None
        self.argv = argv
        self.parse_args()

        from chipsec.chipset import cs
        self._cs = cs()
Example #15
0
 def init_cs(self):
     self._cs = chipset.cs()
Example #16
0
__version__ = '1.2.5'

#import glob
import re
import os
import sys
import time
import importlib
import imp

from chipsec.logger     import *
from chipsec.file       import *
from chipsec.helper.oshelper   import helper

from chipsec.chipset import cs, UnknownChipsetError
_cs = cs()

#
# If you want to turn verbose logging change this line to True
#
logger().UTIL_TRACE = True
logger().VERBOSE    = False
logger().HAL        = False
logger().DEBUG      = False

# If you want to specify a different platform change this line to a string from chipset.py
# _Platform = 'SNB'
_Platform = None

class ExitCode:
    OK = 0
Example #17
0
    def parse_args(self):
        """Parse the arguments provided on the command line.

        Returns: a pair (continue, exit_code). If continue is False,
          the exit_code should be returned.
        """
        parser = argparse.ArgumentParser(
            usage='%(prog)s [options]',
            formatter_class=argparse.RawDescriptionHelpFormatter,
            epilog=ExitCode.help_epilog,
            add_help=False)
        options = parser.add_argument_group('Options')
        options.add_argument('-h',
                             '--help',
                             help="show this message and exit",
                             action='store_true')
        options.add_argument(
            '-m',
            '--module',
            dest='_module',
            help='specify module to run (example: -m common.bios_wp)')
        options.add_argument('-a',
                             '--module_args',
                             nargs='*',
                             dest="_module_argv",
                             help="additional module arguments")
        options.add_argument('-v',
                             '--verbose',
                             help='verbose mode',
                             action='store_true')
        options.add_argument('--hal', help='HAL mode', action='store_true')
        options.add_argument('-d',
                             '--debug',
                             help='debug mode',
                             action='store_true')
        options.add_argument('-l', '--log', help='output to log file')
        adv_options = parser.add_argument_group('Advanced Options')
        adv_options.add_argument('-p',
                                 '--platform',
                                 dest='_platform',
                                 help='explicitly specify platform code',
                                 choices=chipset.cs().chipset_codes,
                                 type=str.upper)
        adv_options.add_argument('--pch',
                                 dest='_pch',
                                 help='explicitly specify PCH code',
                                 choices=chipset.cs().pch_codes,
                                 type=str.upper)
        adv_options.add_argument(
            '-n',
            '--no_driver',
            dest='_no_driver',
            help=
            "chipsec won't need kernel mode functions so don't load chipsec driver",
            action='store_true')
        adv_options.add_argument(
            '-i',
            '--ignore_platform',
            dest='_unknownPlatform',
            help='run chipsec even if the platform is not recognized',
            action='store_false')
        adv_options.add_argument('-j',
                                 '--json',
                                 dest='_json_out',
                                 help='specify filename for JSON output')
        adv_options.add_argument(
            '-x',
            '--xml',
            dest='_xml_out',
            help='specify filename for xml output (JUnit style)')
        adv_options.add_argument('-k',
                                 '--markdown',
                                 dest='_markdown_out',
                                 help='specify filename for markdown output')
        adv_options.add_argument('-t',
                                 '--moduletype',
                                 dest='USER_MODULE_TAGS',
                                 help='run tests of a specific type (tag)',
                                 type=str.upper,
                                 default=[])
        adv_options.add_argument(
            '--list_tags',
            dest='_list_tags',
            help='list all the available options for -t,--moduletype',
            action='store_true')
        adv_options.add_argument(
            '-I',
            '--include',
            dest='IMPORT_PATHS',
            help='specify additional path to load modules from',
            default=[])
        adv_options.add_argument(
            '--failfast',
            help="fail on any exception and exit (don't mask exceptions)",
            action='store_true')
        adv_options.add_argument('--no_time',
                                 help="don't log timestamps",
                                 action='store_true')
        adv_options.add_argument(
            '--deltas',
            dest='_deltas_file',
            help='specifies a JSON log file to compute result deltas from')
        adv_options.add_argument(
            '--record',
            dest='_to_file',
            help='run chipsec and clone helper results into JSON file')
        adv_options.add_argument('--replay',
                                 dest='_from_file',
                                 help='replay a chipsec run with JSON file')
        adv_options.add_argument('--helper',
                                 dest='_driver_exists',
                                 help='specify OS Helper',
                                 choices=[i for i in oshelper.avail_helpers])

        parser.parse_args(self.argv, namespace=ChipsecMain)

        if self.help:
            parser.print_help()
        if self.verbose:
            logger().VERBOSE = True
        if self.hal:
            logger().HAL = True
        if self.debug:
            logger().DEBUG = True
        if self.log:
            logger().set_log_file(self.log)
        if self._module_argv and len(
                self._module_argv) == 1 and self._module_argv[0].count(','):
            logger().log(
                "[*] Use of the -a command no longer needs to have arguments concatenated with ','"
            )
            self._module_argv = self._module_argv[0].split(',')
        if self._unknownPlatform is False:
            logger().log(
                "[*] Ignoring unsupported platform warning and continue execution"
            )
        if self._from_file:
            self._driver_exists = "FileHelper"
Example #18
0
 def init_cs(self):
     self._cs = cs()
Example #19
0
    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_lib.CONFIG["Client.name"])

        logs = []

        if args.log_level:
            # Create a temporary file to store the log output as
            # Chipsec does not support in-memory logging.
            _, self.log_pathspec = tempfiles.CreateGRRTempFileVFS()
            logger().UTIL_TRACE = True
            if args.log_level == 2:
                logger().VERBOSE = True
            logger().set_log_file(self.log_pathspec.path)

        # Create a temporary file to store the flash image.
        dest_fd, dest_pathspec = tempfiles.CreateGRRTempFileVFS()

        # 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("".join(bios))

        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:
                logs = self.ReadAndDeleteChipsecLogs()
                logs.append("%r: %s" % (err, err))
                self.SendReply(chipsec_types.DumpFlashImageResponse(logs=logs))
                tempfiles.DeleteGRRTempFile(dest_pathspec.path)
            if isinstance(err, chipset.UnknownChipsetError):
                # If the chipset is unknown, simply returns an error message
                self.SendReply(
                    chipsec_types.DumpFlashImageResponse(logs=["%s" % err], ))
                return
            raise

        if args.log_level:
            logs = self.ReadAndDeleteChipsecLogs()

        if args.notify_syslog:
            syslog.info("%s: DumpFlashImage has completed successfully",
                        config_lib.CONFIG["Client.name"])

        self.SendReply(
            chipsec_types.DumpFlashImageResponse(path=dest_pathspec,
                                                 logs=logs))
Example #20
0
  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 = []
    # TODO(hanuszczak): This appears to be something that could be made into
    # `StringIO` instead of `BytesIO`.
    self.chipsec_log = io.BytesIO()

    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("".join(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))
Example #21
0
    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 = []
        # TODO(hanuszczak): This appears to be something that could be made into
        # `StringIO` instead of `BytesIO`.
        self.chipsec_log = io.BytesIO()

        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("".join(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))
Example #22
0
 def init_cs(self):
     self._cs = chipset.cs()
Example #23
0
  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_lib.CONFIG["Client.name"])

    logs = []

    if args.log_level:
      # Create a temporary file to store the log output as
      # Chipsec does not support in-memory logging.
      _, self.log_pathspec = tempfiles.CreateGRRTempFileVFS()
      logger().UTIL_TRACE = True
      if args.log_level == 2:
        logger().VERBOSE = True
      logger().set_log_file(self.log_pathspec.path)

    # Create a temporary file to store the flash image.
    dest_fd, dest_pathspec = tempfiles.CreateGRRTempFileVFS()

    # 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("".join(bios))

    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:
        logs = self.ReadAndDeleteChipsecLogs()
        logs.append("%r: %s" % (err, err))
        self.SendReply(chipsec_types.DumpFlashImageResponse(logs=logs))
        tempfiles.DeleteGRRTempFile(dest_pathspec.path)
      if isinstance(err, chipset.UnknownChipsetError):
        # If the chipset is unknown, simply returns an error message
        self.SendReply(chipsec_types.DumpFlashImageResponse(logs=["%s" % err],))
        return
      raise

    if args.log_level:
      logs = self.ReadAndDeleteChipsecLogs()

    if args.notify_syslog:
      syslog.info("%s: DumpFlashImage has completed successfully",
                  config_lib.CONFIG["Client.name"])

    self.SendReply(chipsec_types.DumpFlashImageResponse(path=dest_pathspec,
                                                        logs=logs))
Example #24
0
    def parse_args(self):
        parser = argparse.ArgumentParser(usage='%(prog)s [options] <command>',
                                         add_help=False)
        options = parser.add_argument_group('Options')
        options.add_argument('-h',
                             '--help',
                             dest='show_help',
                             help="show this message and exit",
                             action='store_true')
        options.add_argument('-v',
                             '--verbose',
                             help='verbose mode',
                             action='store_true')
        options.add_argument('--hal', help='HAL mode', action='store_true')
        options.add_argument('-d',
                             '--debug',
                             help='debug mode',
                             action='store_true')
        options.add_argument('-l', '--log', help='output to log file')
        options.add_argument('-p',
                             '--platform',
                             dest='_platform',
                             help='explicitly specify platform code',
                             choices=cs().chipset_codes,
                             type=str.upper)
        options.add_argument('--pch',
                             dest='_pch',
                             help='explicitly specify PCH code',
                             choices=cs().pch_codes,
                             type=str.upper)
        options.add_argument(
            '-n',
            '--no_driver',
            dest='_no_driver',
            help=
            "chipsec won't need kernel mode functions so don't load chipsec driver",
            action='store_true')
        options.add_argument(
            '-i',
            '--ignore_platform',
            dest='_unknownPlatform',
            help='run chipsec even if the platform is not recognized',
            action='store_false')
        options.add_argument('--helper',
                             dest='_driver_exists',
                             help='specify OS Helper',
                             choices=[i for i in oshelper.avail_helpers])
        options.add_argument('_cmd',
                             metavar='Command',
                             nargs='?',
                             choices=sorted(self.commands.keys()),
                             type=str.lower,
                             default="help",
                             help="Util command to run: {{{}}}".format(
                                 ','.join(sorted(self.commands.keys()))))
        options.add_argument('_cmd_args',
                             metavar='Command Args',
                             nargs=argparse.REMAINDER,
                             help=self.global_usage)

        parser.parse_args(self.argv, namespace=ChipsecUtil)
        if self.show_help or self._cmd == "help":
            parser.print_help()
        if self.verbose:
            logger().VERBOSE = True
        if self.hal:
            logger().HAL = True
        if self.debug:
            logger().DEBUG = True
        if self.log:
            logger().set_log_file(self.log)
        if not self._cmd_args:
            self._cmd_args = ["--help"]
Example #25
0
__version__ = '1.2.5'

#import glob
import re
import os
import sys
import time
import importlib
import imp

from chipsec.logger     import *
from chipsec.file       import *
from chipsec.helper.oshelper   import helper

from chipsec.chipset import cs, UnknownChipsetError
_cs = cs()

#
# If you want to turn verbose logging change this line to True
#
logger().UTIL_TRACE = True
logger().VERBOSE    = False
logger().HAL        = False
logger().DEBUG      = False

# If you want to specify a different platform change this line to a string from chipset.py
# _Platform = 'SNB'
_Platform = None

class ExitCode:
    OK = 0