示例#1
0
文件: main.py 项目: njgibbon/checkov
def run(banner=checkov_banner, argv=sys.argv[1:]):
    default_config_paths = get_default_config_paths(sys.argv[1:])
    parser = ExtArgumentParser(
        description='Infrastructure as code static analysis',
        default_config_files=default_config_paths,
        config_file_parser_class=configargparse.YAMLConfigFileParser,
        add_env_var_help=True)
    add_parser_args(parser)
    config = parser.parse_args(argv)
    # bridgecrew uses both the urllib3 and requests libraries, while checkov uses the requests library.
    # Allow the user to specify a CA bundle to be used by both libraries.
    bc_integration.setup_http_manager(config.ca_certificate)

    # if a repo is passed in it'll save it.  Otherwise a default will be created based on the file or dir
    config.repo_id = bc_integration.persist_repo_id(config)
    # if a bc_api_key is passed it'll save it.  Otherwise it will check ~/.bridgecrew/credentials
    config.bc_api_key = bc_integration.persist_bc_api_key(config)

    # Disable runners with missing system dependencies
    config.skip_framework = runnerDependencyHandler.disable_incompatible_runners(
        config.skip_framework)

    runner_filter = RunnerFilter(
        framework=config.framework,
        skip_framework=config.skip_framework,
        checks=config.check,
        skip_checks=config.skip_check,
        download_external_modules=convert_str_to_bool(
            config.download_external_modules),
        external_modules_download_path=config.external_modules_download_path,
        evaluate_variables=convert_str_to_bool(config.evaluate_variables),
        runners=checkov_runners)
    if outer_registry:
        runner_registry = outer_registry
        runner_registry.runner_filter = runner_filter
    else:
        if USE_SECRETS_RUNNER.upper() == "FALSE":
            runner_registry = RunnerRegistry(banner, runner_filter,
                                             *DEFAULT_RUNNERS)
        else:
            runner_registry = RunnerRegistry(banner,
                                             runner_filter, *DEFAULT_RUNNERS,
                                             secrets_runner())

    if config.show_config:
        print(parser.format_values())
        return

    if config.bc_api_key == '':
        parser.error(
            'The --bc-api-key flag was specified but the value was blank. If this value was passed as a secret, '
            'you may need to double check the mapping.')
    elif config.bc_api_key:
        logger.debug(f'Using API key ending with {config.bc_api_key[-8:]}')

        if config.repo_id is None:
            parser.error(
                "--repo-id argument is required when using --bc-api-key")
        if len(config.repo_id.split('/')) != 2:
            parser.error(
                "--repo-id argument format should be 'organization/repository_name' E.g "
                "bridgecrewio/checkov")

        source = os.getenv('BC_SOURCE', 'cli')
        source_version = os.getenv('BC_SOURCE_VERSION', version)
        logger.debug(f'BC_SOURCE = {source}, version = {source_version}')
        try:
            bc_integration.setup_bridgecrew_credentials(
                bc_api_key=config.bc_api_key,
                repo_id=config.repo_id,
                skip_fixes=config.skip_fixes,
                skip_suppressions=config.skip_suppressions,
                source=source,
                source_version=source_version,
                repo_branch=config.branch)
            excluded_paths = bc_integration.get_excluded_paths()
            runner_filter.excluded_paths = excluded_paths
        except Exception as e:
            logger.error(
                'An error occurred setting up the Bridgecrew platform integration. Please check your API token'
                ' and try again.',
                exc_info=True)
            return
    else:
        logger.debug('No API key found. Scanning locally only.')

    guidelines = {}
    if not config.no_guide:
        guidelines = bc_integration.get_guidelines()

    if config.check and config.skip_check:
        if any(item in runner_filter.checks
               for item in runner_filter.skip_checks):
            parser.error(
                "The check ids specified for '--check' and '--skip-check' must be mutually exclusive."
            )
            return

    if config.list:
        print_checks(framework=config.framework)
        return

    external_checks_dir = get_external_checks_dir(config)
    url = None

    if config.directory:
        exit_codes = []
        for root_folder in config.directory:
            file = config.file
            scan_reports = runner_registry.run(
                root_folder=root_folder,
                external_checks_dir=external_checks_dir,
                files=file,
                guidelines=guidelines)
            if bc_integration.is_integration_configured():
                bc_integration.persist_repository(root_folder)
                bc_integration.persist_scan_results(scan_reports)
                url = bc_integration.commit_repository(config.branch)

            exit_codes.append(
                runner_registry.print_reports(scan_reports, config, url))

        exit_code = 1 if 1 in exit_codes else 0
        return exit_code
    elif config.file:
        scan_reports = runner_registry.run(
            external_checks_dir=external_checks_dir,
            files=config.file,
            guidelines=guidelines,
            repo_root_for_plan_enrichment=config.repo_root_for_plan_enrichment)
        if bc_integration.is_integration_configured():
            files = [os.path.abspath(file) for file in config.file]
            root_folder = os.path.split(os.path.commonprefix(files))[0]
            bc_integration.persist_repository(root_folder, files)
            bc_integration.persist_scan_results(scan_reports)
            url = bc_integration.commit_repository(config.branch)
        return runner_registry.print_reports(scan_reports, config, url)
    elif config.docker_image:
        if config.bc_api_key is None:
            parser.error(
                "--bc-api-key argument is required when using --docker-image")
            return
        if config.dockerfile_path is None:
            parser.error(
                "--dockerfile-path argument is required when using --docker-image"
            )
            return
        if config.branch is None:
            parser.error(
                "--branch argument is required when using --docker-image")
            return
        image_scanner.scan(config.docker_image, config.dockerfile_path)
    else:
        print(f"{banner}")

        bc_integration.onboarding()
示例#2
0
from checkov.terraform.plan_runner import Runner as tf_plan_runner
from checkov.terraform.runner import Runner as tf_graph_runner
from checkov.version import version

outer_registry = None

logging_init()
logger = logging.getLogger(__name__)
checkov_runners = [
    'cloudformation', 'terraform', 'kubernetes', 'serverless', 'arm',
    'terraform_plan', 'helm', 'dockerfile', 'secrets'
]

DEFAULT_RUNNERS = (tf_graph_runner(), cfn_runner(), k8_runner(), sls_runner(),
                   arm_runner(), tf_plan_runner(), helm_runner(),
                   dockerfile_runner(), secrets_runner())


def run(banner=checkov_banner, argv=sys.argv[1:]):
    default_config_paths = get_default_config_paths(sys.argv[1:])
    parser = ExtArgumentParser(
        description='Infrastructure as code static analysis',
        default_config_files=default_config_paths,
        config_file_parser_class=configargparse.YAMLConfigFileParser,
        add_env_var_help=True)
    add_parser_args(parser)
    config = parser.parse_args(argv)
    # bridgecrew uses both the urllib3 and requests libraries, while checkov uses the requests library.
    # Allow the user to specify a CA bundle to be used by both libraries.
    bc_integration.setup_http_manager(config.ca_certificate)
示例#3
0
from checkov.version import version

signal.signal(signal.SIGINT, lambda x, y: sys.exit(''))

outer_registry = None

logging_init()
logger = logging.getLogger(__name__)
checkov_runners = [
    value for attr, value in CheckType.__dict__.items()
    if not attr.startswith("__")
]

DEFAULT_RUNNERS = (tf_graph_runner(), cfn_runner(), k8_runner(), sls_runner(),
                   arm_runner(), tf_plan_runner(), helm_runner(),
                   dockerfile_runner(), secrets_runner(), json_runner(),
                   github_configuration_runner(),
                   gitlab_configuration_runner(), kustomize_runner(),
                   sca_package_runner())


def run(banner: str = checkov_banner,
        argv: List[str] = sys.argv[1:]) -> Optional[int]:
    default_config_paths = get_default_config_paths(sys.argv[1:])
    parser = ExtArgumentParser(
        description='Infrastructure as code static analysis',
        default_config_files=default_config_paths,
        config_file_parser_class=configargparse.YAMLConfigFileParser,
        add_env_var_help=True)
    add_parser_args(parser)
    argcomplete.autocomplete(parser)