def local_config():
    """Configuration for all the test cases in this module."""
    return Config.load("""
    id: cbc_binary_toolkit
    version: 0.0.1
    engine:
        name: "default"
    """)
示例#2
0
def local_config():
    """Configuration for most of the test cases in this module."""
    return Config.load("""
    id: cbc_binary_toolkit
    version: 0.0.1
    database:
      _provider: cbc_binary_toolkit.state.builtin.Persistor
      location: ":memory:"
    """)
示例#3
0
def local_persistent_config():
    """Configuration for the persistence test cases in this module."""
    return Config.load(f"""
    id: cbc_binary_toolkit
    version: 0.0.1
    database:
      _provider: cbc_binary_toolkit.state.builtin.Persistor
      location: {PERSISTENCE_FILE}
    """)
def local_config():
    """Configuration for all the test cases in this module."""
    return Config.load("""
    id: cbc_binary_toolkit
    version: 0.0.1
    database:
      _provider: test_persistence_manager.TestPersistorFactory
      is_test: "True"
    """)
def test_config_without_provider_set():
    """Test the configuration without having a provider class set."""
    cfg = Config.load("""
    id: cbc_binary_toolkit
    version: 0.0.1
    database:
      is_test: "True"
    """)
    with pytest.raises(KeyError):
        StateManager(cfg)
def config():
    """Configuration for all the test cases in this module."""
    return Config.load(f"""
    id: cbc_binary_toolkit
    version: 0.0.1
    engine:
      name: {ENGINE_NAME}
      type: local
      _provider: tests.component.engine_fixtures.mock_engine.MockLocalEngineFactory
      Test: TestPassed
    """)
def test_config_with_bogus_class():
    """Test the configuration while trying to load a bogus class."""
    cfg = Config.load("""
    id: cbc_binary_toolkit
    version: 0.0.1
    database:
      _provider: not_exist_package.NotExist
      is_test: "True"
    """)
    with pytest.raises(ImportError):
        StateManager(cfg)
示例#8
0
def config():
    """Configure for all the test cases in this module."""
    return Config.load(f"""
    id: cbc_binary_toolkit
    version: 0.0.1
    database:
      _provider: cbc_binary_toolkit.state.builtin.Persistor
      location: ":memory:"
    engine:
      name: {ENGINE_NAME}
      feed_id: {FEED_ID}
    """)
def config():
    """Configuration for all the test cases in this module."""
    return Config.load(f"""
    id: cbc_binary_toolkit
    version: 0.0.1
    carbonblackcloud:
      expiration_seconds: 3600
    database:
      _provider: persistor_fixtures.mock_persistor.MockPersistorFactory
    engine:
      name: {ENGINE_NAME}
    """)
示例#10
0
def config():
    """Configuration for all the test cases in this module."""
    return Config.load(f"""
    id: cbc_binary_toolkit
    version: 0.0.1
    engine:
      name: Yara
      feed_id: example-feed-id
      type: local
      _provider: cbc_binary_toolkit_examples.engine.yara_local.yara_engine.YaraFactory
      rules_file: {attach_path("yara_local_fixtures/test_rule.yara")}
    """)
def config3():
    """Configure for one of the restart tests."""
    return Config.load(f"""
    id: cbc_binary_toolkit
    version: 0.0.1
    database:
      _provider: tests.component.persistor_fixtures.mock_persistor.MockPersistorFactory
    engine:
      _provider: tests.component.engine_fixtures.mock_engine.MockLocalEngineFactory
      name: {ENGINE_NAME}
      type: local
      Test: TestPassed
    """)
示例#12
0
def test_section():
    """Test the section() API."""
    cfg = Config.load("""
    id: cbc_binary_toolkit
    version: 0.0.1
    pets:
      dog: QBit
      cat: Penny
      tortoise: Homer
    """)
    sect = cfg.section('pets')
    assert sect.string('dog') == cfg.string('pets.dog')
    assert sect.string('cat') == cfg.string('pets.cat')
    assert sect.string('tortoise') == cfg.string('pets.tortoise')
def config():
    """Configure for most of the test cases in this module."""
    return Config.load(f"""
    id: cbc_binary_toolkit
    version: 0.0.1
    database:
      _provider: cbc_binary_toolkit.state.builtin.Persistor
      location: ":memory:"
    engine:
      _provider: tests.component.engine_fixtures.mock_engine.MockLocalEngineFactory
      name: {ENGINE_NAME}
      feed_id: {FEED_ID}
      type: local
      Test: TestPassed
    """)
示例#14
0
def config():
    """Configuration for all the test cases in this module."""
    return Config.load(f"""
    id: cbc_binary_toolkit
    version: 0.0.1
    carbonblackcloud:
      expiration_seconds: 3600
    database:
      _provider: tests.component.persistor_fixtures.mock_persistor.MockPersistorFactory
    engine:
      name: {ENGINE_NAME}
      feed_id: {FEED_ID}
      type: local
      _provider: tests.component.engine_fixtures.mock_engine.MockLocalEngineFactory
      Test: TestPassed
    """)
示例#15
0
def test_get():
    """Test the get() API."""
    cfg = Config.load("""
    id: cbc_binary_toolkit
    version: 0.0.1
    pets:
      dog: QBit
      cat: True
      tortoises: 2
    """)
    assert isinstance(cfg.get('pets.dog'), str)
    assert cfg.get('pets.dog') == "QBit"
    assert isinstance(cfg.get('pets.cat'), bool)
    assert cfg.get('pets.cat') is True
    assert isinstance(cfg.get('pets.tortoises'), int)
    assert cfg.get('pets.tortoises') == 2
    assert isinstance(cfg.get('pets.missing', True), bool)
    assert cfg.get('pets.missing', True) is True
    assert cfg.get('pets.missing') is None
示例#16
0
def test_load_valid_config():
    """Test the load of a valid configuration."""
    cfg = Config.load("""
    id: cbc_binary_toolkit
    version: 0.0.1
    orville:
      captain: Ed Mercer
      doctor: Claire Finn
    enterprise:
      captain: Jim Kirk
      doctor: Leonard McCoy
    voyager:
      captain: Kathryn Janeway
      doctor: EMH
    """)
    assert cfg.string('orville.captain') == "Ed Mercer"
    assert cfg.string('orville.doctor') == "Claire Finn"
    assert cfg.string('enterprise.captain') == "Jim Kirk"
    assert cfg.string('enterprise.doctor') == "Leonard McCoy"
    assert cfg.string('voyager.captain') == "Kathryn Janeway"
    assert cfg.string('voyager.doctor') == "EMH"
示例#17
0
def test_load_errors():
    """Test various load errors in the configuration."""
    with pytest.raises(ConfigError,
                       match=r"^Invalid configuration data format"):
        Config.load("""
        - alpha
        - bravo
        - charlie
        """)
    with pytest.raises(ConfigError, match=r"^Invalid configuration ID"):
        Config.load("""
        values:
          this: A
          that: B
        """)
    with pytest.raises(ConfigError, match=r"^Invalid configuration ID"):
        Config.load("""
        id: something-weird
        version: 0
        values:
          this: A
          that: B
        """)
    def main(self, cmdline_args):
        """
        Entry point for the analysis utility.

        Args:
            cmdline_args (list): Command-line argument strings to be parsed.

        Returns:
            int: Return code from the utility (0=success, nonzero=failure).

        """
        args = self._parser.parse_args(cmdline_args)
        logging.basicConfig(level=LOG_LEVELS[args.log_level])

        if args.log_level != "DEBUG":
            sys.tracebacklimit = 0

        log.debug("Started: {}".format(datetime.now()))

        if args.command_name is None:
            print(
                "usage: cbc-binary-analysis [-h] [-c CONFIG]\n"
                "                           [-ll {DEBUG,INFO,WARNING,ERROR,CRITICAL}]\n"
                "                           {analyze,restart,clear} ...\n"
                "cbc-binary-analysis: error: the following arguments are required: command_name"
            )
            return

        try:
            if self.config is None:
                if args.config != self.default_install:
                    self.config = Config.load_file(args.config)
                elif self.default_install == "ERROR":
                    # Exit if default_install was not found
                    log.error(
                        "Exiting as default example config file could not be "
                        "found and no alternative was specified")
                    return 1
                else:
                    log.info(
                        f"Attempting to load config from {self.default_install}"
                    )
                    self.config = Config.load_file(self.default_install)

            if args.command_name == "analyze":
                components = self._init_components()
                if components["success"]:
                    log.info("Analyzing hashes")
                    self._analyze_command(args, components)

            elif args.command_name == "clear":
                timestamp = args.timestamp
                if timestamp is None:
                    timestamp = str(datetime.now())
                if not (args.force or self._yes_or_no(
                        f"Confirm you want to clear runs prior to {timestamp}")
                        ):
                    log.info("Clear canceled")
                    return

                # Clear previous states
                try:
                    state_manager = StateManager(self.config)
                except:
                    log.error(
                        "Failed to create State Manager. Check your configuration"
                    )
                    log.debug(traceback.format_exc())
                else:
                    log.info("Clearing cache")
                    state_manager.prune(timestamp)
                    if args.reports and self._any_reports_present(
                            state_manager):
                        if args.force or self._yes_or_no(
                                "Confirm you want to clear unsent report items"
                        ):
                            log.info("Clearing report items")
                            for i in range(1, 11):
                                state_manager.clear_report_items(
                                    i, self.config.get("engine.name"))

            elif args.command_name == "restart":
                components = self._init_components()
                if components["success"]:
                    log.info("Restarting")
                    self._restart_command(components)

            log.debug("Finished: {}".format(datetime.now()))
            return 0
        except Exception:
            log.error(traceback.format_exc())
            return 1
示例#19
0
def test_invalid_config(config_text, exception):
    """Test invalid initialization"""
    with pytest.raises(exception):
        LocalEngineManager(Config.load(config_text))
def test_failed_init(engine_config, exception):
    """Test raised exceptions on init of LocalEngineManager"""
    config = Config.load(engine_config)
    with pytest.raises(exception):
        LocalEngineManager(config)