id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
2,259
from __future__ import annotations from typing import TYPE_CHECKING, Any from checkov.bicep.image_referencer.base_provider import BaseBicepProvider from checkov.common.util.data_structures_utils import find_in_dict from checkov.common.util.type_forcers import force_list def find_in_dict(input_dict: dict[str, Any], key_path: str) -> Any: """Tries to retrieve the value under the given 'key_path', otherwise returns None.""" value: Any = input_dict key_list = key_path.split("/") try: for key in key_list: if key.startswith("[") and key.endswith("]"): if isinstance(value, list): idx = int(key[1:-1]) value = value[idx] continue else: return None value = value.get(key) if value is None: return None except (AttributeError, IndexError, KeyError, TypeError, ValueError): logging.debug(f"Could not find {key_path} in dict") return None return value def force_list(var: list[T]) -> list[T]: ... def force_list(var: T) -> list[T]: ... def force_list(var: T | list[T]) -> list[T]: if not isinstance(var, list): return [var] return var def extract_images_from_azurerm_web_app(resource: dict[str, Any]) -> list[str]: image_names: list[str] = [] containers = find_in_dict(input_dict=resource, key_path="properties/template/containers") if containers: for container in force_list(containers): name = container.get("image") if name and isinstance(name, str): image_names.append(name) return image_names
null
2,260
from __future__ import annotations import io import itertools import logging import os import subprocess import tempfile import threading from typing import Any, Type, TYPE_CHECKING import yaml from checkov.common.bridgecrew.check_type import CheckType from checkov.common.graph.checks_infra.registry import BaseRegistry from checkov.common.typing import LibraryGraphConnector from checkov.common.graph.graph_builder.consts import GraphSource from checkov.common.images.image_referencer import fix_related_resource_ids, Image from checkov.common.output.report import Report from checkov.common.parallelizer.parallel_runner import parallel_runner from checkov.common.runners.base_runner import BaseRunner, filter_ignored_paths from checkov.helm.image_referencer.manager import HelmImageReferencerManager from checkov.helm.registry import registry from checkov.kubernetes.graph_builder.local_graph import KubernetesLocalGraph from checkov.kubernetes.runner import Runner as k8_runner, handle_timeout, _KubernetesContext, _KubernetesDefinitions from checkov.runner_filter import RunnerFilter import signal class Report: def __init__(self, check_type: str): self.check_type = check_type self.passed_checks: list[Record] = [] self.failed_checks: list[Record] = [] self.skipped_checks: list[Record] = [] self.parsing_errors: list[str] = [] self.resources: set[str] = set() self.extra_resources: set[ExtraResource] = set() self.image_cached_results: List[dict[str, Any]] = [] self.error_status: ErrorStatus = ErrorStatus.SUCCESS def errors(self) -> Dict[str, List[str]]: return dict() def set_error_status(self, error_status: ErrorStatus) -> None: self.error_status = error_status def add_parsing_errors(self, errors: "Iterable[str]") -> None: for file in errors: self.add_parsing_error(file) def add_parsing_error(self, file: str) -> None: if file: self.parsing_errors.append(file) def add_resource(self, resource: str) -> None: self.resources.add(resource) def add_record(self, record: Record) -> None: if record.check_result["result"] == CheckResult.PASSED: self.passed_checks.append(record) if record.check_result["result"] == CheckResult.FAILED: self.failed_checks.append(record) if record.check_result["result"] == CheckResult.SKIPPED: self.skipped_checks.append(record) def get_summary(self) -> Dict[str, Union[int, str]]: return { "passed": len(self.passed_checks), "failed": len(self.failed_checks), "skipped": len(self.skipped_checks), "parsing_errors": len(self.parsing_errors), "resource_count": len(self.resources), "checkov_version": version, } def get_json(self) -> str: return json.dumps(self.get_dict(), indent=4, cls=CustomJSONEncoder) def get_all_records(self) -> List[Record]: return self.failed_checks + self.passed_checks + self.skipped_checks def get_dict(self, is_quiet: bool = False, url: str | None = None, full_report: bool = False, s3_setup_failed: bool = False, support_path: str | None = None) -> dict[str, Any]: if not url and not s3_setup_failed: url = "Add an api key '--bc-api-key <api-key>' to see more detailed insights via https://bridgecrew.cloud" elif s3_setup_failed: url = S3_UPLOAD_DETAILS_MESSAGE if is_quiet: return { "check_type": self.check_type, "results": { "failed_checks": [check.__dict__ for check in self.failed_checks] }, "summary": self.get_summary(), } if full_report: return { "check_type": self.check_type, "checks": { "passed_checks": [check.__dict__ for check in self.passed_checks], "failed_checks": [check.__dict__ for check in self.failed_checks], "skipped_checks": [check.__dict__ for check in self.skipped_checks] }, "image_cached_results": [res.__dict__ for res in self.image_cached_results] } else: result = { "check_type": self.check_type, "results": { "passed_checks": [check.__dict__ for check in self.passed_checks], "failed_checks": [check.__dict__ for check in self.failed_checks], "skipped_checks": [check.__dict__ for check in self.skipped_checks], "parsing_errors": list(self.parsing_errors), }, "summary": self.get_summary(), "url": url, } if support_path: result["support_path"] = support_path return result def get_exit_code(self, exit_code_thresholds: Union[_ExitCodeThresholds, _ScaExitCodeThresholds]) -> int: """ Returns the appropriate exit code depending on the flags that are passed in. :return: Exit code 0 or 1. """ hard_fail_on_parsing_errors = os.getenv(PARSE_ERROR_FAIL_FLAG, "false").lower() == 'true' logging.debug(f'In get_exit_code; exit code thresholds: {exit_code_thresholds}, hard_fail_on_parsing_errors: {hard_fail_on_parsing_errors}') if self.parsing_errors and hard_fail_on_parsing_errors: logging.debug('hard_fail_on_parsing_errors is True and there were parsing errors - returning 1') return 1 if not self.failed_checks: logging.debug('No failed checks in this report - returning 0') return 0 # we will have two different sets of logic in this method, determined by this variable. # if we are using enforcement rules, then there are two different sets of thresholds that apply for licenses and vulnerabilities # and we have to handle that throughout while processing the report # if we are not using enforcement rules, then we can combine licenses and vulnerabilities like normal and same as all other report types # this determination is made in runner_registry.get_fail_thresholds has_split_enforcement = CodeCategoryType.LICENSES in exit_code_thresholds hard_fail_threshold: Optional[Severity | Dict[str, Severity]] soft_fail: Optional[bool | Dict[str, bool]] if has_split_enforcement: sca_thresholds = cast(_ScaExitCodeThresholds, exit_code_thresholds) # these three are the same even in split enforcement rules generic_thresholds = cast(_ExitCodeThresholds, next(iter(sca_thresholds.values()))) soft_fail_on_checks = generic_thresholds['soft_fail_checks'] soft_fail_threshold = generic_thresholds['soft_fail_threshold'] hard_fail_on_checks = generic_thresholds['hard_fail_checks'] # these two can be different for licenses / vulnerabilities hard_fail_threshold = {category: thresholds['hard_fail_threshold'] for category, thresholds in sca_thresholds.items()} # type:ignore[index] # thinks it's an object, can't possibly be more clear soft_fail = {category: thresholds['soft_fail'] for category, thresholds in sca_thresholds.items()} # type:ignore[index] # thinks it's an object failed_checks_by_category = { CodeCategoryType.LICENSES: [fc for fc in self.failed_checks if '_LIC_' in fc.check_id], CodeCategoryType.VULNERABILITIES: [fc for fc in self.failed_checks if '_VUL_' in fc.check_id] } has_soft_fail_values = soft_fail_on_checks or soft_fail_threshold if all( not failed_checks_by_category[cast(CodeCategoryType, c)] or ( not has_soft_fail_values and not (hard_fail_threshold[c] or hard_fail_on_checks) and soft_fail[c] ) for c in sca_thresholds.keys() ): logging.debug( 'No failed checks, or soft_fail is True and soft_fail_on and hard_fail_on are empty for all SCA types - returning 0') return 0 if any( not has_soft_fail_values and not (hard_fail_threshold[c] or hard_fail_on_checks) and failed_checks_by_category[cast(CodeCategoryType, c)] for c in sca_thresholds.keys() ): logging.debug('There are failed checks and all soft/hard fail args are empty for one or more SCA reports - returning 1') return 1 else: non_sca_thresholds = cast(_ExitCodeThresholds, exit_code_thresholds) soft_fail_on_checks = non_sca_thresholds['soft_fail_checks'] soft_fail_threshold = non_sca_thresholds['soft_fail_threshold'] hard_fail_on_checks = non_sca_thresholds['hard_fail_checks'] hard_fail_threshold = non_sca_thresholds['hard_fail_threshold'] soft_fail = non_sca_thresholds['soft_fail'] has_soft_fail_values = soft_fail_on_checks or soft_fail_threshold has_hard_fail_values = hard_fail_threshold or hard_fail_on_checks if not has_soft_fail_values and not has_hard_fail_values and soft_fail: logging.debug('Soft_fail is True and soft_fail_on and hard_fail_on are empty - returning 0') return 0 elif not has_soft_fail_values and not has_hard_fail_values: logging.debug('There are failed checks and all soft/hard fail args are empty - returning 1') return 1 for failed_check in self.failed_checks: check_id = failed_check.check_id bc_check_id = failed_check.bc_check_id severity = failed_check.severity secret_validation_status = failed_check.validation_status if hasattr(failed_check, 'validation_status') else '' hf_threshold: Severity sf: bool if has_split_enforcement: category = CodeCategoryType.LICENSES if '_LIC_' in check_id else CodeCategoryType.VULNERABILITIES hard_fail_threshold = cast(Dict[str, Severity], hard_fail_threshold) hf_threshold = hard_fail_threshold[category] soft_fail = cast(Dict[str, bool], soft_fail) sf = soft_fail[category] else: hard_fail_threshold = cast(Severity, hard_fail_threshold) hf_threshold = hard_fail_threshold soft_fail = cast(bool, soft_fail) sf = soft_fail soft_fail_severity = severity and soft_fail_threshold and severity.level <= soft_fail_threshold.level hard_fail_severity = severity and hf_threshold and severity.level >= hf_threshold.level explicit_soft_fail = RunnerFilter.check_matches(check_id, bc_check_id, soft_fail_on_checks) explicit_hard_fail = RunnerFilter.check_matches(check_id, bc_check_id, hard_fail_on_checks) explicit_secrets_soft_fail = RunnerFilter.secret_validation_status_matches(secret_validation_status, soft_fail_on_checks) explicit_secrets_hard_fail = RunnerFilter.secret_validation_status_matches(secret_validation_status, hard_fail_on_checks) implicit_soft_fail = not explicit_hard_fail and not explicit_secrets_hard_fail and not soft_fail_on_checks and not soft_fail_threshold implicit_hard_fail = not explicit_soft_fail and not soft_fail_severity and not explicit_secrets_soft_fail if explicit_hard_fail or \ (hard_fail_severity and not explicit_soft_fail) or \ (implicit_hard_fail and not implicit_soft_fail and not sf): logging.debug(f'Check {check_id} (BC ID: {bc_check_id}, severity: {severity.level if severity else None} triggered hard fail - returning 1') return 1 logging.debug('No failed check triggered hard fail - returning 0') return 0 def is_empty(self, full: bool = False) -> bool: checks_count = ( len(self.passed_checks) + len(self.failed_checks) + len(self.skipped_checks) + len(self.parsing_errors) ) if full: checks_count += len(self.resources) + len(self.extra_resources) + len(self.image_cached_results) return checks_count == 0 def add_errors_to_output(self) -> str: ret_value = '' for error_title, errors_messages in self.errors.items(): ret_value += colored(f"Encountered {error_title} error - {len(errors_messages)} times\n\n", "red") return ret_value def print_console( self, is_quiet: bool = False, is_compact: bool = False, created_baseline_path: str | None = None, baseline: Baseline | None = None, use_bc_ids: bool = False, summary_position: str = 'top', openai_api_key: str | None = None, ) -> str: summary = self.get_summary() output_data = colored(f"{self.check_type} scan results:\n", "blue") if self.parsing_errors: message = "\nPassed checks: {}, Failed checks: {}, Skipped checks: {}, Parsing errors: {}\n\n".format( summary["passed"], summary["failed"], summary["skipped"], summary["parsing_errors"], ) else: if self.check_type == CheckType.SCA_PACKAGE or self.check_type.lower().startswith(CheckType.SAST): message = f"\nFailed checks: {summary['failed']}, Skipped checks: {summary['skipped']}\n\n" else: message = f"\nPassed checks: {summary['passed']}, Failed checks: {summary['failed']}, Skipped checks: {summary['skipped']}\n\n" if summary_position == 'top': output_data += colored(message, "cyan") # output for vulnerabilities is different if self.check_type in (CheckType.SCA_PACKAGE, CheckType.SCA_IMAGE): if self.failed_checks or self.skipped_checks: create_cli_output = create_sca_package_cli_output_v2 output_data += create_cli_output(self.check_type == CheckType.SCA_PACKAGE, self.failed_checks, self.skipped_checks) elif self.check_type == CheckType.POLICY_3D: if self.failed_checks or self.skipped_checks: output_data += create_3d_policy_cli_output(self.failed_checks, self.skipped_checks) # type:ignore[arg-type] else: if self.check_type.lower().startswith(CheckType.SAST): output_data += colored(f"Source code files scanned: {summary.get(SOURCE_FILES_COUNT, -1)}, " f"Policies found: {summary.get(POLICY_COUNT, -1)}\n\n", "cyan") policies_errors: str = str(summary.get(POLICIES_ERRORS, "")) if policies_errors: output_data += colored(f"Policy parsing failures ({summary.get(POLICIES_ERRORS_COUNT)}):\n{policies_errors}\n\n", "red") if not is_quiet: for record in self.passed_checks: output_data += record.to_string(compact=is_compact, use_bc_ids=use_bc_ids) if self.failed_checks: OpenAi(api_key=openai_api_key).enhance_records(runner_type=self.check_type, records=self.failed_checks) for record in self.failed_checks: output_data += record.to_string(compact=is_compact, use_bc_ids=use_bc_ids) if not is_quiet: for record in self.skipped_checks: output_data += record.to_string(compact=is_compact, use_bc_ids=use_bc_ids) if not is_quiet: for file in self.parsing_errors: output_data += colored(f"Error parsing file {file}ֿ\n", "red") if created_baseline_path: output_data += colored( f"Created a checkov baseline file at {created_baseline_path}", "blue", ) if baseline: output_data += colored( f"Baseline analysis report using {baseline.path} - only new failed checks with respect to the baseline are reported", "blue", ) if summary_position == 'bottom': output_data += colored(message, "cyan") return output_data def _print_parsing_error_console(file: str) -> None: print(colored(f"Error parsing file {file}", "red")) def get_junit_xml_string(ts: list[TestSuite]) -> str: return to_xml_report_string(ts) def print_failed_github_md(self, use_bc_ids: bool = False) -> str: result = [] for record in self.failed_checks: result.append( [ record.get_output_id(use_bc_ids), record.file_path, record.resource, record.check_name, record.guideline, ] ) if result: table = tabulate( result, headers=["check_id", "file", "resource", "check_name", "guideline"], tablefmt="github", showindex=True, ) output_data = f"### {self.check_type} scan results:\n\n{table}\n\n---\n" return output_data else: return "\n\n---\n\n" def get_test_suite(self, properties: Optional[Dict[str, Any]] = None, use_bc_ids: bool = False) -> TestSuite: """Creates a test suite for the JUnit XML report""" test_cases = [] records = self.passed_checks + self.failed_checks + self.skipped_checks for record in records: severity = BcSeverities.NONE if record.severity: severity = record.severity.name if self.check_type == CheckType.SCA_PACKAGE: if record.check_name != SCA_PACKAGE_SCAN_CHECK_NAME: continue if not record.vulnerability_details: # this shouldn't normally happen logging.warning(f"Vulnerability check without details {record.file_path}") continue check_id = record.vulnerability_details["id"] test_name_detail = f"{record.vulnerability_details['package_name']}: {record.vulnerability_details['package_version']}" class_name = f"{record.file_path}.{record.vulnerability_details['package_name']}" else: check_id = record.bc_check_id if use_bc_ids else record.check_id test_name_detail = record.check_name class_name = f"{record.file_path}.{record.resource}" test_name = f"[{severity}][{check_id}] {test_name_detail}" test_case = TestCase(name=test_name, file=record.file_path, classname=class_name) if record.check_result["result"] == CheckResult.FAILED: test_case.add_failure_info( message=record.check_name, output=self._create_test_case_failure_output(record) ) if record.check_result["result"] == CheckResult.SKIPPED: if self.check_type == CheckType.SCA_PACKAGE: test_case.add_skipped_info(f"{check_id} skipped for {test_name_detail}") else: test_case.add_skipped_info(record.check_result.get("suppress_comment", "")) test_cases.append(test_case) test_suite = TestSuite(name=f"{self.check_type} scan", test_cases=test_cases, properties=properties) return test_suite def create_test_suite_properties_block(config: argparse.Namespace) -> Dict[str, Any]: """Creates a dictionary without 'None' values for the JUnit XML properties block""" properties = {k: v for k, v in config.__dict__.items() if v is not None} return properties def _create_test_case_failure_output(self, record: Record) -> str: """Creates the failure output for a JUnit XML test case IaC example: Resource: azurerm_network_security_rule.fail_rdp File: /main.tf: 71-83 Guideline: https://docs.bridgecrew.io/docs/bc_azr_networking_2 71 | resource "azurerm_network_security_rule" "fail_rdp" { 72 | resource_group_name = azurerm_resource_group.example.name 73 | network_security_group_name=azurerm_network_security_group.example_rdp.name 74 | name = "fail_security_rule" 75 | direction = "Inbound" 76 | access = "Allow" 77 | protocol = "TCP" 78 | source_port_range = "*" 79 | destination_port_range = "3389" 80 | source_address_prefix = "*" 81 | destination_address_prefix = "*" 82 | priority = 120 83 | } SCA example: Description: Django before 1.11.27, 2.x before 2.2.9, and 3.x before 3.0.1 allows account takeover. Link: https://nvd.nist.gov/vuln/detail/CVE-2019-19844 Published Date: 2019-12-18T20:15:00+01:00 Base Score: 9.8 Vector: CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H Risk Factors: ['Attack complexity: low', 'Attack vector: network', 'Critical severity', 'Has fix'] Resource: requirements.txt.django File: /requirements.txt: 0-0 0 | django: 1.2 """ failure_output = [] if self.check_type == CheckType.SCA_PACKAGE: if record.vulnerability_details: lowest_fixed_version = record.vulnerability_details.get('lowest_fixed_version') if lowest_fixed_version is not None: fix = lowest_fixed_version else: fixlist = record.vulnerability_details.get('fixed_versions') if fixlist is not None: fix = fixlist failure_output.extend( [ "", f"Description: {record.description}", f"Link: {record.vulnerability_details.get('link')}", f"Published Date: {record.vulnerability_details.get('published_date')}", f"Base Score: {record.vulnerability_details.get('cvss')}", f"Vector: {record.vulnerability_details.get('vector')}", f"Risk Factors: {record.vulnerability_details.get('risk_factors')}", "Fix Details:", f" Status: {record.vulnerability_details.get('status')}", f" Fixed Version: {fix}", ] ) else: # this shouldn't normally happen logging.warning(f"Vulnerability check without details {record.file_path}") failure_output.extend( [ "", f"Resource: {record.resource}", ] ) if record.file_path: file_line = f"File: {record.file_path}" if record.file_line_range: file_line += f": {record.file_line_range[0]}-{record.file_line_range[1]}" failure_output.append(file_line) if self.check_type != CheckType.SCA_PACKAGE: failure_output.append(f"Guideline: {record.guideline}") if record.code_block: failure_output.append("") failure_output.append(record._code_line_string(code_block=record.code_block, colorized=False)) return "\n".join(failure_output) def print_json(self) -> None: print(self.get_json()) def enrich_plan_report( report: "Report", enriched_resources: Dict[str, Dict[str, Any]] ) -> "Report": # This enriches reports with the appropriate filepath, line numbers, and codeblock for record in report.failed_checks: resource_raw_id = Report.get_plan_resource_raw_id(record.resource) enriched_resource = enriched_resources.get(resource_raw_id) if enriched_resource: record.file_path = enriched_resource["scanned_file"] record.file_line_range = enriched_resource["entity_lines_range"] record.code_block = enriched_resource["entity_code_lines"] return report def handle_skipped_checks( report: "Report", enriched_resources: Dict[str, Dict[str, Any]] ) -> "Report": module_address_len = len("module.") skip_records = [] for record in report.failed_checks: resource_raw_id = Report.get_plan_resource_raw_id(record.resource) resource_skips = enriched_resources.get(resource_raw_id, {}).get( "skipped_checks", [] ) for skip in resource_skips: if record.check_id in skip["id"]: # Mark for removal and add it as a skipped record. It is not safe to remove # the record from failed_checks immediately because we're iterating over it skip_records.append(record) record.check_result["result"] = CheckResult.SKIPPED record.check_result["suppress_comment"] = skip["suppress_comment"] report.add_record(record) if record.resource_address and record.resource_address.startswith("module."): module_path = record.resource_address[module_address_len:record.resource_address.index('.', module_address_len + 1)] module_enrichments = enriched_resources.get(module_path, {}) for module_skip in module_enrichments.get("skipped_checks", []): if record.check_id in module_skip["id"]: skip_records.append(record) record.check_result["result"] = CheckResult.SKIPPED record.check_result["suppress_comment"] = module_skip["suppress_comment"] report.add_record(record) for record in skip_records: if record in report.failed_checks: report.failed_checks.remove(record) return report def get_plan_resource_raw_id(resource_id: str) -> str: """ return the resource raw id without the modules and the indexes example: from resource_id='module.module_name.type.name[1]' return 'type.name' """ resource_raw_id = ".".join(resource_id.split(".")[-2:]) if '[' in resource_raw_id: resource_raw_id = resource_raw_id[:resource_raw_id.index('[')] return resource_raw_id def from_reduced_json(cls, json_report: dict[str, Any], check_type: str) -> Report: report = Report(check_type) report.image_cached_results = json_report['image_cached_results'] all_json_records = json_report["checks"]["passed_checks"] + \ json_report["checks"]["failed_checks"] + \ json_report["checks"]["skipped_checks"] for json_record in all_json_records: report.add_record( Record.from_reduced_json(json_record) ) return report def fix_report_paths(report: Report, tmp_dir: str) -> None: for check in itertools.chain(report.failed_checks, report.passed_checks): check.repo_file_path = check.repo_file_path.replace(tmp_dir, '', 1) report.resources = {r.replace(tmp_dir, '', 1) for r in report.resources}
null
2,261
from __future__ import annotations import io import itertools import logging import os import subprocess import tempfile import threading from typing import Any, Type, TYPE_CHECKING import yaml from checkov.common.bridgecrew.check_type import CheckType from checkov.common.graph.checks_infra.registry import BaseRegistry from checkov.common.typing import LibraryGraphConnector from checkov.common.graph.graph_builder.consts import GraphSource from checkov.common.images.image_referencer import fix_related_resource_ids, Image from checkov.common.output.report import Report from checkov.common.parallelizer.parallel_runner import parallel_runner from checkov.common.runners.base_runner import BaseRunner, filter_ignored_paths from checkov.helm.image_referencer.manager import HelmImageReferencerManager from checkov.helm.registry import registry from checkov.kubernetes.graph_builder.local_graph import KubernetesLocalGraph from checkov.kubernetes.runner import Runner as k8_runner, handle_timeout, _KubernetesContext, _KubernetesDefinitions from checkov.runner_filter import RunnerFilter import signal def get_skipped_checks(entity_conf: dict[str, Any]) -> list[dict[str, str]]: skipped = [] metadata = {} if not isinstance(entity_conf, dict): return skipped if entity_conf["kind"] == "containers" or entity_conf["kind"] == "initContainers": metadata = entity_conf["parent_metadata"] else: if "metadata" in entity_conf.keys(): metadata = entity_conf["metadata"] if "annotations" in metadata.keys() and metadata["annotations"] is not None: for key in metadata["annotations"].keys(): skipped_item = {} if "checkov.io/skip" in key or "bridgecrew.io/skip" in key: if "CKV_K8S" in metadata["annotations"][key]: if "=" in metadata["annotations"][key]: (skipped_item["id"], skipped_item["suppress_comment"]) = metadata["annotations"][key].split("=") else: skipped_item["id"] = metadata["annotations"][key] skipped_item["suppress_comment"] = "No comment provided" skipped.append(skipped_item) else: logging.info(f"Parse of Annotation Failed for {metadata['annotations'][key]}: {entity_conf}") continue return skipped
null
2,262
from __future__ import annotations import io import itertools import logging import os import subprocess import tempfile import threading from typing import Any, Type, TYPE_CHECKING import yaml from checkov.common.bridgecrew.check_type import CheckType from checkov.common.graph.checks_infra.registry import BaseRegistry from checkov.common.typing import LibraryGraphConnector from checkov.common.graph.graph_builder.consts import GraphSource from checkov.common.images.image_referencer import fix_related_resource_ids, Image from checkov.common.output.report import Report from checkov.common.parallelizer.parallel_runner import parallel_runner from checkov.common.runners.base_runner import BaseRunner, filter_ignored_paths from checkov.helm.image_referencer.manager import HelmImageReferencerManager from checkov.helm.registry import registry from checkov.kubernetes.graph_builder.local_graph import KubernetesLocalGraph from checkov.kubernetes.runner import Runner as k8_runner, handle_timeout, _KubernetesContext, _KubernetesDefinitions from checkov.runner_filter import RunnerFilter import signal def filter_ignored_paths( root_dir: str, names: list[str] | list[os.DirEntry[str]], excluded_paths: list[str] | None, included_paths: Iterable[str] | None = None ) -> None: # we need to handle legacy logic, where directories to skip could be specified using the env var (default value above) # or a directory starting with '.'; these look only at directory basenames, not relative paths. # # But then any other excluded paths (specified via --skip-path or via the platform repo settings) should look at # the path name relative to the root folder. These can be files or directories. # Example: take the following dir tree: # . # ./dir1 # ./dir1/dir33 # ./dir1/.terraform # ./dir2 # ./dir2/dir33 # /.dir2/hello.yaml # # if excluded_paths = ['dir1/dir33', 'dir2/hello.yaml'], then we would scan dir1, but we would skip its subdirectories. We would scan # dir2 and its subdirectory, but we'd skip hello.yaml. # first handle the legacy logic - this will also remove files starting with '.' but that's probably fine # mostly this will just remove those problematic directories hardcoded above. included_paths = included_paths or [] for entry in list(names): path = entry.name if isinstance(entry, os.DirEntry) else entry if path in ignored_directories: safe_remove(names, entry) if path.startswith(".") and IGNORE_HIDDEN_DIRECTORY_ENV and path not in included_paths: safe_remove(names, entry) # now apply the new logic # TODO this is not going to work well on Windows, because paths specified in the platform will use /, and # paths specified via the CLI argument will presumably use \\ if excluded_paths: compiled = [] for p in excluded_paths: try: compiled.append(re.compile(p.replace(".terraform", r"\.terraform"))) except re.error: # do not add compiled paths that aren't regexes continue for entry in list(names): path = entry.name if isinstance(entry, os.DirEntry) else entry full_path = os.path.join(root_dir, path) if any(pattern.search(full_path) for pattern in compiled) or any(p in full_path for p in excluded_paths): safe_remove(names, entry) def find_chart_directories(root_folder: str | None, files: list[str] | None, excluded_paths: list[str]) -> list[str]: chart_directories = [] if not excluded_paths: excluded_paths = [] if files: logging.info('Running with --file argument; checking for Helm Chart.yaml files') for file in files: if os.path.basename(file) == 'Chart.yaml': chart_directories.append(os.path.dirname(file)) if root_folder: for root, d_names, f_names in os.walk(root_folder): filter_ignored_paths(root, d_names, excluded_paths) filter_ignored_paths(root, f_names, excluded_paths) if 'Chart.yaml' in f_names: chart_directories.append(root) return chart_directories
null
2,263
from __future__ import annotations import json import os from collections.abc import Iterable from pathlib import Path from typing import Tuple, Optional, List, Any, Pattern, Callable import jmespath import logging import re import yaml from yaml import YAMLError from checkov.cloudformation.parser import cfn_yaml from checkov.cloudformation.context_parser import ContextParser from checkov.cloudformation.parser.cfn_yaml import CfnParseError from checkov.common.models.consts import SLS_DEFAULT_VAR_PATTERN from checkov.common.parsers.node import DictNode, StrNode from checkov.common.resource_code_logger_filter import add_resource_code_filter_to_logger CFN_RESOURCES_TOKEN = 'resources' class DictNode(dict): # type:ignore[type-arg] # either typing works or runtime, but not both """Node class created based on the input class""" def __init__(self, x: dict[str, Any], start_mark: Mark | Any, end_mark: Mark | Any): try: super().__init__(x) except TypeError: super().__init__() self.start_mark = start_mark self.end_mark = end_mark self.condition_functions = ['Fn::If'] def __deepcopy__(self, memo: dict[int, Any]) -> DictNode: result = DictNode(self, self.start_mark, self.end_mark) memo[id(self)] = result for k, v in self.items(): result[deepcopy(k)] = deepcopy(v, memo) return result def __copy__(self) -> DictNode: return self def is_function_returning_object(self, _mappings: Any = None) -> bool: """ Check if an object is using a function that could return an object Return True when Fn::Select: - 0 # or any number - !FindInMap [mapname, key, value] # or any mapname, key, value Otherwise False """ if len(self) == 1: for k, v in self.items(): if k in ['Fn::Select']: if isinstance(v, list): if len(v) == 2: p_v = v[1] if isinstance(p_v, dict): if len(p_v) == 1: for l_k in p_v.keys(): if l_k == 'Fn::FindInMap': return True return False def get(self, key: str, default: Any = None) -> Any: """ Override the default get """ if isinstance(default, dict): default = DictNode(default, self.start_mark, self.end_mark) return super().get(key, default) def get_safe( self, key: str, default: Any = None, path: list[str] | None = None, type_t: Type[tuple[Any, ...]] = tuple ) -> list[tuple[tuple[Any, ...], list[str]]]: """Get values in format""" path = path or [] value = self.get(key, default) if not isinstance(value, dict): if isinstance(value, type_t) or not type_t: return [(value, (path[:] + [key]))] results = [] for sub_v, sub_path in value.items_safe(path + [key]): if isinstance(sub_v, type_t) or not type_t: results.append((sub_v, sub_path)) return results def items_safe( self, path: list[int | str] | None = None, type_t: Type[tuple[Any, ...]] = tuple ) -> Generator[tuple[Any, ...], Any, None]: """Get items while handling IFs""" path = path or [] if len(self) == 1: for k, v in self.items(): if k == 'Fn::If': if isinstance(v, list): if len(v) == 3: for i, if_v in enumerate(v[1:]): if isinstance(if_v, DictNode): # yield from if_v.items_safe(path[:] + [k, i - 1]) # Python 2.7 support for items, p in if_v.items_safe(path[:] + [k, i + 1]): if isinstance(items, type_t) or not type_t: yield items, p elif isinstance(if_v, list): if isinstance(if_v, type_t) or not type_t: yield if_v, path[:] + [k, i + 1] else: if isinstance(if_v, type_t) or not type_t: yield if_v, path[:] + [k, i + 1] elif not (k == 'Ref' and v == 'AWS::NoValue'): if isinstance(self, type_t) or not type_t: yield self, path[:] else: if isinstance(self, type_t) or not type_t: yield self, path[:] def __getattr__(self, name: str) -> Any: raise TemplateAttributeError(f'{name} is invalid') def template_contains_cfn_resources(template: dict[str, Any]) -> bool: if template.__contains__(CFN_RESOURCES_TOKEN) and isinstance(template[CFN_RESOURCES_TOKEN], DictNode): if template[CFN_RESOURCES_TOKEN].get('Resources'): return True return False
null
2,264
from __future__ import annotations import json import os from collections.abc import Iterable from pathlib import Path from typing import Tuple, Optional, List, Any, Pattern, Callable import jmespath import logging import re import yaml from yaml import YAMLError from checkov.cloudformation.parser import cfn_yaml from checkov.cloudformation.context_parser import ContextParser from checkov.cloudformation.parser.cfn_yaml import CfnParseError from checkov.common.models.consts import SLS_DEFAULT_VAR_PATTERN from checkov.common.parsers.node import DictNode, StrNode from checkov.common.resource_code_logger_filter import add_resource_code_filter_to_logger class ContextParser: """ CloudFormation template context parser """ def __init__(self, cf_file: str, cf_template: dict[str, Any], cf_template_lines: List[Tuple[int, str]]) -> None: self.cf_file = cf_file self.cf_template = cf_template self.cf_template_lines = cf_template_lines def evaluate_default_refs(self) -> None: # Get Parameter Defaults - Locate Refs in Template refs = self.search_deep_keys("Ref", self.cf_template, []) for ref in refs: refname = ref.pop() ref.pop() # Get rid of the 'Ref' dict key # TODO refactor into evaluations if not isinstance(refname, str): continue default_value = self.cf_template.get("Parameters", {}).get(refname, {}).get("Properties", {}).get("Default") if default_value is not None: logging.debug( "Replacing Ref {} in file {} with default parameter value: {}".format( refname, self.cf_file, default_value ) ) self._set_in_dict(self.cf_template, ref, default_value) # TODO - Add Variable Eval Message for Output # Output in Checkov looks like this: # Variable versioning (of /.) evaluated to value "True" in expression: enabled = ${var.versioning} def extract_cf_resource_id(cf_resource: dict[str, Any], cf_resource_name: str) -> Optional[str]: if cf_resource_name == STARTLINE or cf_resource_name == ENDLINE: return None if "Type" not in cf_resource: # This is not a CloudFormation resource, skip return None return f"{cf_resource['Type']}.{cf_resource_name}" def extract_cf_resource_code_lines( self, cf_resource: dict[str, Any] ) -> Tuple[Optional[List[int]], Optional[List[Tuple[int, str]]]]: find_lines_result_set = set(self.find_lines(cf_resource, STARTLINE)) if len(find_lines_result_set) >= 1: start_line = min(find_lines_result_set) end_line = max(self.find_lines(cf_resource, ENDLINE)) # start_line - 2: -1 to switch to 0-based indexing, and -1 to capture the resource name entity_code_lines = self.cf_template_lines[start_line - 2 : end_line - 1] # if the file did not end in a new line, and this was the last resource in the file, then we # trimmed off the last line if (end_line - 1) < len(self.cf_template_lines) and not self.cf_template_lines[end_line - 1][1].endswith( "\n" ): entity_code_lines.append(self.cf_template_lines[end_line - 1]) entity_code_lines = ContextParser.trim_lines(entity_code_lines) entity_lines_range = [entity_code_lines[0][0], entity_code_lines[-1][0]] return entity_lines_range, entity_code_lines return None, None def trim_lines(code_lines: List[Tuple[int, str]]) -> List[Tuple[int, str]]: # Removes leading and trailing lines that are only whitespace, returning a new value # The passed value should be a list of tuples of line numbers and line strings (entity_code_lines) start = 0 end = len(code_lines) while start < end and not code_lines[start][1].strip(): start += 1 while end > start and not code_lines[end - 1][1].strip(): end -= 1 # if start == end, this will just be empty return code_lines[start:end] def find_lines(node: Any, kv: str) -> Generator[int, None, None]: # Hack to allow running checkov on json templates # CF scripts that are parsed using the yaml mechanism have a magic STARTLINE and ENDLINE property # CF scripts that are parsed using the json mechnism use dicts that have a marker if hasattr(node, "start_mark") and kv == STARTLINE: yield node.start_mark.line + 1 if hasattr(node, "end_mark") and kv == ENDLINE: yield node.end_mark.line + 1 if isinstance(node, list): for i in node: for x in ContextParser.find_lines(i, kv): yield x elif isinstance(node, dict): if kv in node: yield node[kv] def collect_skip_comments( entity_code_lines: List[Tuple[int, str]], resource_config: dict[str, Any] | None = None ) -> List[_SkippedCheck]: skipped_checks = collect_suppressions_for_context(code_lines=entity_code_lines) bc_id_mapping = metadata_integration.bc_to_ckv_id_mapping if resource_config: metadata = resource_config.get("Metadata") if metadata: ckv_skip = metadata.get("checkov", {}).get("skip", []) bc_skip = metadata.get("bridgecrew", {}).get("skip", []) if ckv_skip or bc_skip: for skip in itertools.chain(ckv_skip, bc_skip): skip_id = skip.get("id") skip_comment = skip.get("comment", "No comment provided") if skip_id is None: logging.warning("Check suppression is missing key 'id'") continue skipped_check: "_SkippedCheck" = {"id": skip_id, "suppress_comment": skip_comment} if bc_id_mapping and skipped_check["id"] in bc_id_mapping: skipped_check["bc_id"] = skipped_check["id"] skipped_check["id"] = bc_id_mapping[skipped_check["id"]] elif metadata_integration.check_metadata: skipped_check["bc_id"] = metadata_integration.get_bc_id(skipped_check["id"]) skipped_checks.append(skipped_check) return skipped_checks def search_deep_keys( search_text: str, cfn_dict: str | list[Any] | dict[str, Any], path: list[int | str] ) -> list[list[int | str]]: """Search deep for keys and get their values""" keys: list[list[int | str]] = [] if isinstance(cfn_dict, dict): for key in cfn_dict: pathprop = path[:] pathprop.append(key) if key == search_text: pathprop.append(cfn_dict[key]) keys.append(pathprop) # pop the last element off for nesting of found elements for # dict and list checks pathprop = pathprop[:-1] if isinstance(cfn_dict[key], dict): keys.extend(ContextParser.search_deep_keys(search_text, cfn_dict[key], pathprop)) elif isinstance(cfn_dict[key], list): for index, item in enumerate(cfn_dict[key]): pathproparr = pathprop[:] pathproparr.append(index) keys.extend(ContextParser.search_deep_keys(search_text, item, pathproparr)) elif isinstance(cfn_dict, list): for index, item in enumerate(cfn_dict): pathprop = list(path) pathprop.append(index) keys.extend(ContextParser.search_deep_keys(search_text, item, pathprop)) return keys def _set_in_dict(self, data_dict: dict[str, Any], map_list: list[Any], value: str) -> None: v = self._get_from_dict(data_dict, map_list[:-1]) # save the original marks so that we do not copy in the line numbers of the parameter element # but not all ref types will have these attributes start = None end = None if hasattr(v, "start_mark") and hasattr(v, "end_mark"): start = v.start_mark end = v.end_mark v[map_list[-1]] = value if hasattr(v[map_list[-1]], "start_mark") and start and end: v[map_list[-1]].start_mark = start v[map_list[-1]].end_mark = end def _get_from_dict(data_dict: dict[str, Any], map_list: list[Any]) -> list[Any] | dict[str, Any]: return reduce(operator.getitem, map_list, data_dict) def template_contains_key(template: dict[str, Any], key: str) -> bool: if ContextParser.search_deep_keys(key, template, []): return True return False
null
2,265
from __future__ import annotations import json import os from collections.abc import Iterable from pathlib import Path from typing import Tuple, Optional, List, Any, Pattern, Callable import jmespath import logging import re import yaml from yaml import YAMLError from checkov.cloudformation.parser import cfn_yaml from checkov.cloudformation.context_parser import ContextParser from checkov.cloudformation.parser.cfn_yaml import CfnParseError from checkov.common.models.consts import SLS_DEFAULT_VAR_PATTERN from checkov.common.parsers.node import DictNode, StrNode from checkov.common.resource_code_logger_filter import add_resource_code_filter_to_logger def _determine_variable_value_from_dict( source_dict: dict[str, Any], location_str: str | None, default: str | None ) -> Any: if location_str is None: return source_dict if default is not None: default = default.strip() # NOTE: String must be quoted to avoid issues with dashes and other reserved # characters. If we just wrap the whole thing, dot separators won't work so: # split and join with individually wrapped tokens. # Original: foo.bar-baz # Wrapped: "foo"."bar-baz" location = ".".join([f'"{token}"' for token in location_str.split(".")]) source_value = jmespath.search(location, source_dict) if source_value is None: return default return source_value def _self_var_data_lookup(group_dict: dict[str, Any], template: dict[str, Any]) -> Any: location = group_dict["loc"] default = group_dict.get("default") return _determine_variable_value_from_dict(template, location, default)
null
2,266
from __future__ import annotations import logging import os from typing import List, Dict, Tuple, Callable, Any from checkov.cloudformation import cfn_utils from checkov.cloudformation.context_parser import ContextParser as CfnContextParser from checkov.common.bridgecrew.check_type import CheckType from checkov.common.parallelizer.parallel_runner import parallel_runner from checkov.common.util.secrets import omit_secret_value_from_checks from checkov.serverless.base_registry import EntityDetails from checkov.serverless.parsers.context_parser import ContextParser as SlsContextParser from checkov.cloudformation.checks.resource.registry import cfn_registry from checkov.serverless.checks.complete.registry import complete_registry from checkov.serverless.checks.custom.registry import custom_registry from checkov.serverless.checks.function.registry import function_registry from checkov.serverless.checks.layer.registry import layer_registry from checkov.serverless.checks.package.registry import package_registry from checkov.serverless.checks.plugin.registry import plugin_registry from checkov.serverless.checks.provider.registry import provider_registry from checkov.serverless.checks.service.registry import service_registry from checkov.common.runners.base_runner import BaseRunner, filter_ignored_paths from checkov.runner_filter import RunnerFilter from checkov.common.output.record import Record from checkov.common.output.report import Report from checkov.common.output.extra_resource import ExtraResource from checkov.serverless.parsers.parser import parse from checkov.common.parsers.node import DictNode from checkov.serverless.parsers.parser import CFN_RESOURCES_TOKEN def _parallel_parse(f: str) -> tuple[str, tuple[dict[str, Any], list[tuple[int, str]]] | None]: """Thin wrapper to return filename with parsed content""" return f, parse(f) parallel_runner = ParallelRunner() def get_files_definitions( files: List[str], filepath_fn: Callable[[str], str] | None = None ) -> Tuple[Dict[str, dict[str, Any]], Dict[str, List[Tuple[int, str]]]]: results = parallel_runner.run_function(_parallel_parse, files) definitions = {} definitions_raw = {} for file, result in results: if result: path = filepath_fn(file) if filepath_fn else file definitions[path], definitions_raw[path] = result return definitions, definitions_raw
null
2,267
from __future__ import annotations import itertools import logging from collections import defaultdict from typing import List, Dict, Any from colorama import Style from prettytable import PrettyTable, SINGLE_BORDER from termcolor import colored from checkov.common.bridgecrew.severities import BcSeverities from checkov.common.models.enums import CheckResult from checkov.common.output.record import Record, DEFAULT_SEVERITY from checkov.common.output.common import compare_table_items_severity from checkov.policies_3d.record import Policy3dRecord def create_iac_code_blocks_output(record: Policy3dRecord) -> str: suppress_comment = "" check_message = colored('Check: {}: "{}"\n'.format(record.get_output_id(use_bc_ids=True), record.check_name), "white") guideline_message = Record.get_guideline_string(record.guideline) severity_message = f'\tSeverity: {record.severity.name}\n' if record.severity else '' resource_blocks = '' resource_block_ids = set() for iac_record in record.iac_records: resource_id = f'{iac_record.file_path}:{iac_record.resource}' if resource_id in resource_block_ids: # no need to print the same resource block twice continue resource_details = colored(f'\n\tResource: {iac_record.file_path}:{iac_record.resource}', attrs=['bold']) code_lines = Record.get_code_lines_string(iac_record.code_block) detail = Record.get_details_string(iac_record.details) caller_file_details = Record.get_caller_file_details_string(iac_record.caller_file_path, iac_record.caller_file_line_range) evaluation_message = Record.get_evaluation_string(iac_record.evaluations, iac_record.code_block) resource_blocks += f'{detail}{caller_file_details}{resource_details}{code_lines}{evaluation_message}' resource_block_ids.add(resource_id) if record.check_result["result"] == CheckResult.FAILED and resource_blocks: return f"{check_message}{severity_message}{guideline_message}{resource_blocks}" if record.check_result["result"] == CheckResult.SKIPPED: return f"{check_message}{severity_message}{suppress_comment}{guideline_message}" else: return f"{check_message}{severity_message}{guideline_message}" def render_cve_output(record: Policy3dRecord) -> str | None: if not record.vulnerabilities: # this shouldn't happen logging.error(f"'vulnerabilities' is not set for {record.check_id}") return None package_cves_details_map: dict[str, dict[str, Any]] = defaultdict(dict) for cve in record.vulnerabilities: image_name = cve.get('dockerImageName') package_name = cve.get('packageName', '') package_version = cve.get('packageVersion') severity_str = cve.get('severity', BcSeverities.NONE).upper() package_cves_details_map[package_name].setdefault("cves", []).append( { "id": cve.get('cveId'), "severity": severity_str } ) if package_name in package_cves_details_map: package_cves_details_map[package_name]["cves"].sort(key=compare_table_items_severity, reverse=True) package_cves_details_map[package_name]["current_version"] = package_version package_cves_details_map[package_name]["image_name"] = image_name if package_cves_details_map: return ( create_cli_cves_table( file_path=record.file_path, package_details_map=package_cves_details_map, ) ) return None def render_iac_violations_table(record: Policy3dRecord) -> str | None: if not record.iac_records: # this shouldn't happen logging.error(f"'iac_records' is not set for {record.check_id}") return None resource_violation_details_map: dict[str, dict[str, Any]] = defaultdict(dict) for iac_record in record.iac_records: resource = iac_record.resource severity = (iac_record.severity.name if iac_record.severity else DEFAULT_SEVERITY).upper() resource_violation_details_map[resource].setdefault('violations', []).append( { 'id': iac_record.bc_check_id, 'title': iac_record.check_name, 'severity': severity } ) if resource in resource_violation_details_map: resource_violation_details_map[resource]['violations'].sort(key=compare_table_items_severity, reverse=True) if len(resource_violation_details_map.keys()): return ( create_iac_violations_table( file_path=record.file_path, resource_violation_details_map=resource_violation_details_map, ) ) return None class Policy3dRecord(Record): def __init__(self, check_id: str, bc_check_id: str, check_name: str, check_result: _CheckResult, code_block: List[Tuple[int, str]], file_path: str, file_line_range: List[int], resource: str, evaluations: Optional[Dict[str, Any]], check_class: str, file_abs_path: str, severity: Optional[Severity], vulnerabilities: List[Dict[str, Any]], iac_records: List[Record], composed_from_iac_records: List[Record], composed_from_secrets_records: list[Record], composed_from_cves: list[Dict[str, Any]] ) -> None: super().__init__( check_id=check_id, bc_check_id=bc_check_id, check_name=check_name, check_result=check_result, code_block=code_block, file_path=file_path, file_line_range=file_line_range, resource=resource, evaluations=evaluations, check_class=check_class, file_abs_path=file_abs_path, severity=severity, ) self.vulnerabilities = vulnerabilities self.iac_records = iac_records self.composed_from_iac_records = composed_from_iac_records self.composed_from_secrets_records = composed_from_secrets_records self.composed_from_cves = composed_from_cves def create_cli_output(*records: list[Policy3dRecord]) -> str: cli_outputs = [] for record in itertools.chain(*records): iac_code_blocks_output = create_iac_code_blocks_output(record) if iac_code_blocks_output: cli_outputs.append(iac_code_blocks_output + Style.RESET_ALL) iac_violations_table = render_iac_violations_table(record) if iac_violations_table: cli_outputs.append(iac_violations_table + Style.RESET_ALL) cves_table = render_cve_output(record) if cves_table: cli_outputs.append(cves_table + Style.RESET_ALL) secrets_table = '' # noqa: F841 # TODO create a function for creating secrets table, when secrets get into 3d policies # Table should have the columns: Secret, Secrety Type, Violation ID, Validation Status (value in red) return "\n".join(cli_outputs)
null
2,268
from __future__ import annotations import os from enum import Enum from typing import Iterable, Callable, Any from checkov.arm.parser.parser import parse from checkov.common.runners.base_runner import filter_ignored_paths ARM_POSSIBLE_ENDINGS = [".json"] def filter_ignored_paths( root_dir: str, names: list[str] | list[os.DirEntry[str]], excluded_paths: list[str] | None, included_paths: Iterable[str] | None = None ) -> None: # we need to handle legacy logic, where directories to skip could be specified using the env var (default value above) # or a directory starting with '.'; these look only at directory basenames, not relative paths. # # But then any other excluded paths (specified via --skip-path or via the platform repo settings) should look at # the path name relative to the root folder. These can be files or directories. # Example: take the following dir tree: # . # ./dir1 # ./dir1/dir33 # ./dir1/.terraform # ./dir2 # ./dir2/dir33 # /.dir2/hello.yaml # # if excluded_paths = ['dir1/dir33', 'dir2/hello.yaml'], then we would scan dir1, but we would skip its subdirectories. We would scan # dir2 and its subdirectory, but we'd skip hello.yaml. # first handle the legacy logic - this will also remove files starting with '.' but that's probably fine # mostly this will just remove those problematic directories hardcoded above. included_paths = included_paths or [] for entry in list(names): path = entry.name if isinstance(entry, os.DirEntry) else entry if path in ignored_directories: safe_remove(names, entry) if path.startswith(".") and IGNORE_HIDDEN_DIRECTORY_ENV and path not in included_paths: safe_remove(names, entry) # now apply the new logic # TODO this is not going to work well on Windows, because paths specified in the platform will use /, and # paths specified via the CLI argument will presumably use \\ if excluded_paths: compiled = [] for p in excluded_paths: try: compiled.append(re.compile(p.replace(".terraform", r"\.terraform"))) except re.error: # do not add compiled paths that aren't regexes continue for entry in list(names): path = entry.name if isinstance(entry, os.DirEntry) else entry full_path = os.path.join(root_dir, path) if any(pattern.search(full_path) for pattern in compiled) or any(p in full_path for p in excluded_paths): safe_remove(names, entry) The provided code snippet includes necessary dependencies for implementing the `get_scannable_file_paths` function. Write a Python function `def get_scannable_file_paths(root_folder: str | None = None, excluded_paths: list[str] | None = None) -> set[str]` to solve the following problem: Finds ARM files Here is the function: def get_scannable_file_paths(root_folder: str | None = None, excluded_paths: list[str] | None = None) -> set[str]: """Finds ARM files""" file_paths: "set[str]" = set() if not root_folder: return file_paths for root, d_names, f_names in os.walk(root_folder): filter_ignored_paths(root, d_names, excluded_paths) filter_ignored_paths(root, f_names, excluded_paths) for file in f_names: file_ending = os.path.splitext(file)[1] if file_ending in ARM_POSSIBLE_ENDINGS: file_paths.add(os.path.join(root, file)) return file_paths
Finds ARM files
2,269
from __future__ import annotations import os from enum import Enum from typing import Iterable, Callable, Any from checkov.arm.parser.parser import parse from checkov.common.runners.base_runner import filter_ignored_paths def parse(filename: str) -> tuple[dict[str, Any], list[tuple[int, str]]] | tuple[None, None]: """Decode filename into an object""" template = None template_lines = None try: template, template_lines = load(filename) except IOError as e: if e.errno == 2: LOGGER.error(f"Template file not found: {filename}") elif e.errno == 21: LOGGER.error(f"Template references a directory, not a file: {filename}") elif e.errno == 13: LOGGER.error(f"Permission denied when accessing template file: {filename}") except UnicodeDecodeError: LOGGER.error(f"Cannot read file contents: {filename}") except ScannerError as err: if err.problem in ("found character '\\t' that cannot start any token", "found unknown escape character"): try: result = json_parse(filename, allow_nulls=False) if result: template, template_lines = result # type:ignore[assignment] # this is handled by the next line if isinstance(template, list): # should not happen and is more relevant for type safety template = template[0] except Exception: LOGGER.error(f"Template {filename} is malformed: {err.problem}") LOGGER.error(f"Tried to parse {filename} as JSON", exc_info=True) except YAMLError: LOGGER.info(f"Failed to parse {filename}") LOGGER.debug("With Exception", exc_info=True) if template is None or template_lines is None: return None, None return template, template_lines The provided code snippet includes necessary dependencies for implementing the `get_files_definitions` function. Write a Python function `def get_files_definitions( files: Iterable[str], filepath_fn: Callable[[str], str] | None = None ) -> tuple[dict[str, dict[str, Any]], dict[str, list[tuple[int, str]]], list[str]]` to solve the following problem: Parses ARM files into its definitions and raw data Here is the function: def get_files_definitions( files: Iterable[str], filepath_fn: Callable[[str], str] | None = None ) -> tuple[dict[str, dict[str, Any]], dict[str, list[tuple[int, str]]], list[str]]: """Parses ARM files into its definitions and raw data""" definitions = {} definitions_raw = {} parsing_errors = [] for file in files: result = parse(file) definition, definition_raw = result if definition is not None and definition_raw is not None: # this has to be a 'None' check path = filepath_fn(file) if filepath_fn else file definitions[path] = definition definitions_raw[path] = definition_raw else: parsing_errors.append(os.path.normpath(file)) return definitions, definitions_raw, parsing_errors
Parses ARM files into its definitions and raw data
2,270
from __future__ import annotations from typing import Any from checkov.common.util.consts import START_LINE, END_LINE def _generate_resource_key_recursive(conf: dict[str, Any] | list[str] | str, key: str, start_line: int, end_line: int, scanned_image_blocks: set[str], depth: int) -> str: if not isinstance(conf, dict): return key for k, value in conf.items(): if depth == 0 and k in SKIP_BLOCKS: continue if k in IMAGE_BLOCK_NAMES: scanned_image_blocks.add(k) if isinstance(value, dict) and value[START_LINE] <= start_line <= end_line <= value[END_LINE]: next_key = f'{key}.{k}' if key else k return _generate_resource_key_recursive(value, next_key, start_line, end_line, scanned_image_blocks, depth + 1) if isinstance(value, list): if value and isinstance(value[0], dict): next_key = f'{key}.{k}' if key else k for idx, entry in enumerate(value): if entry and isinstance(entry, dict) and entry[START_LINE] <= start_line <= end_line <= entry[END_LINE]: next_key += f'.{idx + 1}' break # There can be only one match in terms of line range return _generate_resource_key_recursive(value, next_key, start_line, end_line, scanned_image_blocks, depth + 1) if any(block_name in conf.keys() and block_name not in scanned_image_blocks and isinstance(conf[block_name], dict) and conf[block_name].get(START_LINE) <= start_line and conf[block_name].get(END_LINE) >= end_line for block_name in IMAGE_BLOCK_NAMES): # Avoid settling for a too general resource id, when there are blocks which usually contain image names, # and that these blocks were not scanned yet & match the line range. continue if depth == 0: # Indicates the first recursive call. a heuristic that top-level entities should usually be disregarded # in case they are not dictionaries. continue if isinstance(value, list): if key: return f'{key}.{k}' else: continue if isinstance(value, str): return key return key def generate_resource_key_recursive(conf: dict[str, Any] | list[str] | str, key: str, start_line: int, end_line: int) -> str: return _generate_resource_key_recursive(conf, key, start_line, end_line, set(), 0)
null
2,271
from __future__ import annotations import datetime import logging import json import subprocess from checkov.common.resource_code_logger_filter import add_resource_code_filter_to_logger from checkov.common.util.http_utils import request_wrapper from checkov.common.bridgecrew.platform_integration import BcPlatformIntegration from typing import Any def parse_gitlog(repository: str, source: str) -> dict[str, Any] | None: def request_wrapper( method: str, url: str, headers: dict[str, Any], data: Any | None = None, json: dict[str, Any] | None = None, should_call_raise_for_status: bool = False, params: dict[str, Any] | None = None, log_json_body: bool = True ) -> Response: class BcPlatformIntegration: def __init__(self) -> None: def clean(self) -> None: def init_instance(self, platform_integration_data: dict[str, Any]) -> None: def generate_instance_data(self) -> dict[str, Any]: def set_bc_api_url(self, new_url: str) -> None: def setup_api_urls(self) -> None: def is_prisma_integration(self) -> bool: def is_token_valid(token: str) -> bool: def is_bc_token(token: str | None) -> TypeGuard[str]: def get_auth_token(self) -> str: def setup_http_manager(self, ca_certificate: str | None = None, no_cert_verify: bool = False) -> None: def setup_bridgecrew_credentials( self, repo_id: str, skip_download: bool = False, source: SourceType | None = None, skip_fixes: bool = False, source_version: str | None = None, repo_branch: str | None = None, prisma_api_url: str | None = None, bc_api_url: str | None = None ) -> None: def set_s3_integration(self) -> None: def set_s3_client(self) -> None: def get_s3_role(self, repo_id: str) -> tuple[str, str, dict[str, Any]] | tuple[None, None, dict[str, Any]]: def _get_s3_creds(self, repo_id: str, token: str) -> dict[str, Any]: def is_integration_configured(self) -> bool: def persist_repository( self, root_dir: str | Path, files: list[str] | None = None, excluded_paths: list[str] | None = None, included_paths: list[str] | None = None, sast_languages: Set[SastLanguages] | None = None ) -> None: def persist_git_configuration(self, root_dir: str | Path, git_config_folders: list[str]) -> None: def adjust_sast_match_location_path(self, match: Match) -> None: def _delete_code_block_from_sast_report(report: Dict[str, Any]) -> None: def save_sast_report_locally(sast_scan_reports: Dict[str, Dict[str, Any]]) -> None: def persist_sast_scan_results(self, reports: List[Report]) -> None: def persist_cdk_scan_results(self, reports: List[Report]) -> None: def persist_scan_results(self, scan_reports: list[Report]) -> None: async def persist_reachability_alias_mapping(self, alias_mapping: Dict[str, Any]) -> None: def persist_assets_scan_results(self, assets_report: Optional[Dict[str, Any]]) -> None: def persist_reachability_scan_results(self, reachability_report: Optional[Dict[str, Any]]) -> None: def persist_image_scan_results(self, report: dict[str, Any] | None, file_path: str, image_name: str, branch: str) -> None: def persist_enriched_secrets(self, enriched_secrets: list[EnrichedSecret]) -> str | None: def persist_run_metadata(self, run_metadata: dict[str, str | list[str]]) -> None: def persist_all_logs_streams(self, logs_streams: Dict[str, StringIO]) -> None: def persist_graphs(self, graphs: dict[str, list[tuple[LibraryGraph, Optional[str]]]], absolute_root_folder: str = '') -> None: def persist_resource_subgraph_maps(self, resource_subgraph_maps: dict[str, dict[str, str]]) -> None: def commit_repository(self, branch: str) -> str | None: def persist_files(self, files_to_persist: list[FileToPersist]) -> None: def _persist_file(self, full_file_path: str, s3_file_key: str) -> None: def get_platform_run_config(self) -> None: def _get_run_config_query_params(self) -> str: def get_run_config_url(self) -> str: def get_customer_run_config(self) -> None: def get_reachability_run_config(self) -> Union[Dict[str, Any], None]: def get_runtime_run_config(self) -> None: def get_prisma_build_policies(self, policy_filter: str) -> None: def get_prisma_policy_filters(self) -> Dict[str, Dict[str, Any]]: def is_valid_policy_filter(policy_filter: dict[str, str], valid_filters: dict[str, dict[str, Any]] | None = None) -> bool: def get_public_run_config(self) -> None: def get_report_to_platform(self, args: argparse.Namespace, scan_reports: list[Report]) -> None: def persist_bc_api_key(self, args: argparse.Namespace) -> str | None: def persist_repo_id(self, args: argparse.Namespace) -> str: def get_repository(self, args: argparse.Namespace) -> str: def _upload_run(self, args: argparse.Namespace, scan_reports: list[Report]) -> None: def _input_orgname(self) -> str: def _input_visualize_results(self) -> str: def _input_levelup_results(self) -> str: def _input_email(self) -> str: def loading_output(msg: str) -> None: def repo_matches(self, repo_name: str) -> bool: def get_default_headers(self, request_type: str) -> dict[str, Any]: def get_sso_prismacloud_url(self, report_url: str) -> str: def setup_on_prem(self) -> None: def report_contributor_metrics(repository: str, source: str, bc_integration: BcPlatformIntegration) -> None: # ignore: type logging.debug(f"Attempting to get log history for repository {repository} under source {source}") request_body = parse_gitlog(repository, source) number_of_attempts = 1 contributors_report_api_url = f"{bc_integration.api_url}/api/v2/contributors/report" if request_body: while number_of_attempts <= 4: logging.debug(f'Uploading contributor metrics to {contributors_report_api_url}') response = request_wrapper( "POST", contributors_report_api_url, headers=bc_integration.get_default_headers("POST"), data=json.dumps(request_body) ) logging.debug(f'Request ID: {response.headers.get("x-amzn-requestid")}') logging.debug(f'Trace ID: {response.headers.get("x-amzn-trace-id")}') if response.status_code < 300: logging.debug( f"Successfully uploaded contributor metrics with status: {response.status_code}. number of attempts: {number_of_attempts}") break else: contributors_report_api_url = f"{bc_integration.api_url}/api/v1/contributors/report" failed_attempt = { 'message': f"Failed to upload contributor metrics with: {response.status_code} - {response.reason}. number of attempts: {number_of_attempts}", 'timestamp': str(datetime.datetime.now())} request_body['failedAttempts'].append(failed_attempt) logging.info(f"Failed to upload contributor metrics with: {response.status_code} - {response.reason}") number_of_attempts += 1
null
2,272
from __future__ import annotations import logging import os from collections.abc import Iterable from pathlib import Path from typing import TYPE_CHECKING, Callable, Any, Literal from dockerfile_parse.constants import COMMENT_INSTRUCTION from checkov.common.runners.base_runner import filter_ignored_paths from checkov.common.util.dockerfile import is_dockerfile from checkov.common.util.suppression import collect_suppressions_for_context from checkov.dockerfile.parser import parse def filter_ignored_paths( root_dir: str, names: list[str] | list[os.DirEntry[str]], excluded_paths: list[str] | None, included_paths: Iterable[str] | None = None ) -> None: # we need to handle legacy logic, where directories to skip could be specified using the env var (default value above) # or a directory starting with '.'; these look only at directory basenames, not relative paths. # # But then any other excluded paths (specified via --skip-path or via the platform repo settings) should look at # the path name relative to the root folder. These can be files or directories. # Example: take the following dir tree: # . # ./dir1 # ./dir1/dir33 # ./dir1/.terraform # ./dir2 # ./dir2/dir33 # /.dir2/hello.yaml # # if excluded_paths = ['dir1/dir33', 'dir2/hello.yaml'], then we would scan dir1, but we would skip its subdirectories. We would scan # dir2 and its subdirectory, but we'd skip hello.yaml. # first handle the legacy logic - this will also remove files starting with '.' but that's probably fine # mostly this will just remove those problematic directories hardcoded above. included_paths = included_paths or [] for entry in list(names): path = entry.name if isinstance(entry, os.DirEntry) else entry if path in ignored_directories: safe_remove(names, entry) if path.startswith(".") and IGNORE_HIDDEN_DIRECTORY_ENV and path not in included_paths: safe_remove(names, entry) # now apply the new logic # TODO this is not going to work well on Windows, because paths specified in the platform will use /, and # paths specified via the CLI argument will presumably use \\ if excluded_paths: compiled = [] for p in excluded_paths: try: compiled.append(re.compile(p.replace(".terraform", r"\.terraform"))) except re.error: # do not add compiled paths that aren't regexes continue for entry in list(names): path = entry.name if isinstance(entry, os.DirEntry) else entry full_path = os.path.join(root_dir, path) if any(pattern.search(full_path) for pattern in compiled) or any(p in full_path for p in excluded_paths): safe_remove(names, entry) def is_dockerfile(file: str) -> bool: if "ockerfile" not in file: # no need to check the full regex, if 'ockerfile' couldn't be found return False return re.fullmatch(DOCKERFILE_MASK, file) is not None The provided code snippet includes necessary dependencies for implementing the `get_scannable_file_paths` function. Write a Python function `def get_scannable_file_paths( root_folder: str | Path | None = None, excluded_paths: list[str] | None = None ) -> set[str]` to solve the following problem: Finds Dockerfiles Here is the function: def get_scannable_file_paths( root_folder: str | Path | None = None, excluded_paths: list[str] | None = None ) -> set[str]: """Finds Dockerfiles""" file_paths: "set[str]" = set() if not root_folder: return file_paths for root, d_names, f_names in os.walk(root_folder): filter_ignored_paths(root, d_names, excluded_paths) filter_ignored_paths(root, f_names, excluded_paths) for file in f_names: if is_dockerfile(file): file_path = os.path.join(root, file) file_paths.add(file_path) return file_paths
Finds Dockerfiles
2,273
from __future__ import annotations import logging import os from collections.abc import Iterable from pathlib import Path from typing import TYPE_CHECKING, Callable, Any, Literal from dockerfile_parse.constants import COMMENT_INSTRUCTION from checkov.common.runners.base_runner import filter_ignored_paths from checkov.common.util.dockerfile import is_dockerfile from checkov.common.util.suppression import collect_suppressions_for_context from checkov.dockerfile.parser import parse def parse(filename: str | Path) -> tuple[dict[str, list[_Instruction]], list[str]]: with open(filename) as dockerfile: dfp = DockerfileParser(fileobj=dockerfile) return dfp_group_by_instructions(dfp) The provided code snippet includes necessary dependencies for implementing the `get_files_definitions` function. Write a Python function `def get_files_definitions( files: Iterable[str], filepath_fn: Callable[[str], str] | None = None ) -> tuple[dict[str, dict[str, list[_Instruction]]], dict[str, list[str]]]` to solve the following problem: Parses Dockerfiles into its definitions and raw data Here is the function: def get_files_definitions( files: Iterable[str], filepath_fn: Callable[[str], str] | None = None ) -> tuple[dict[str, dict[str, list[_Instruction]]], dict[str, list[str]]]: """Parses Dockerfiles into its definitions and raw data""" definitions = {} definitions_raw = {} for file in files: try: result = parse(file) path = filepath_fn(file) if filepath_fn else file definitions[path], definitions_raw[path] = result except TypeError: logging.info(f"Dockerfile skipping {file} as it is not a valid dockerfile template") except UnicodeDecodeError: logging.info(f"Dockerfile skipping {file} as it can't be read as text file") return definitions, definitions_raw
Parses Dockerfiles into its definitions and raw data
2,274
from __future__ import annotations import logging import os from collections.abc import Iterable from pathlib import Path from typing import TYPE_CHECKING, Callable, Any, Literal from dockerfile_parse.constants import COMMENT_INSTRUCTION from checkov.common.runners.base_runner import filter_ignored_paths from checkov.common.util.dockerfile import is_dockerfile from checkov.common.util.suppression import collect_suppressions_for_context from checkov.dockerfile.parser import parse The provided code snippet includes necessary dependencies for implementing the `get_abs_path` function. Write a Python function `def get_abs_path(root_folder: str | None, file_path: str) -> str` to solve the following problem: Creates the abs path There are a few cases here. If -f was used, there could be a leading / because it's an absolute path, or there will be no leading slash; root_folder will always be none. If -d is used, root_folder will be the value given, and -f will start with a / (hardcoded above). The goal here is simply to get a valid path to the file (which dockerfile_path does not always give). Here is the function: def get_abs_path(root_folder: str | None, file_path: str) -> str: """Creates the abs path There are a few cases here. If -f was used, there could be a leading / because it's an absolute path, or there will be no leading slash; root_folder will always be none. If -d is used, root_folder will be the value given, and -f will start with a / (hardcoded above). The goal here is simply to get a valid path to the file (which dockerfile_path does not always give). """ if root_folder and file_path.startswith("/"): # remove the leading slash, if it exists file_path = file_path[1:] path_to_convert = os.path.join(root_folder, file_path) if root_folder else file_path return os.path.abspath(path_to_convert)
Creates the abs path There are a few cases here. If -f was used, there could be a leading / because it's an absolute path, or there will be no leading slash; root_folder will always be none. If -d is used, root_folder will be the value given, and -f will start with a / (hardcoded above). The goal here is simply to get a valid path to the file (which dockerfile_path does not always give).
2,275
from __future__ import annotations import logging import os from collections.abc import Iterable from pathlib import Path from typing import TYPE_CHECKING, Callable, Any, Literal from dockerfile_parse.constants import COMMENT_INSTRUCTION from checkov.common.runners.base_runner import filter_ignored_paths from checkov.common.util.dockerfile import is_dockerfile from checkov.common.util.suppression import collect_suppressions_for_context from checkov.dockerfile.parser import parse DOCKERFILE_STARTLINE: Literal["startline"] = "startline" DOCKERFILE_ENDLINE: Literal["endline"] = "endline" DOCKERFILE_VALUE: Literal["value"] = "value" def collect_suppressions_for_context(code_lines: Iterable[tuple[int, int | str]]) -> list[_SkippedCheck]: def build_definitions_context( definitions: dict[str, dict[str, list[_Instruction]]], definitions_raw: dict[str, list[str]] ) -> dict[str, dict[str, Any]]: definitions_context: dict[str, dict[str, Any]] = {} for file_path, definition in definitions.items(): file_path = str(file_path) definitions_context[file_path] = {} skipped_checks = [] if COMMENT_INSTRUCTION in definition: # collect skipped check comments comments = definition[COMMENT_INSTRUCTION] comment_lines = [(comment[DOCKERFILE_STARTLINE], comment[DOCKERFILE_VALUE]) for comment in comments] skipped_checks = collect_suppressions_for_context(code_lines=comment_lines) for instruction_name, instructions in definition.items(): if instruction_name == COMMENT_INSTRUCTION: continue definitions_context[file_path][instruction_name] = [] for instruction in instructions: start_line = instruction[DOCKERFILE_STARTLINE] end_line = instruction[DOCKERFILE_ENDLINE] code_lines = [ (line + 1, definitions_raw[file_path][line]) for line in range(start_line, end_line + 1) ] definition_resource = { "start_line": start_line + 1, # lines start with index 0 "end_line": end_line + 1, "code_lines": code_lines, "skipped_checks": skipped_checks, } definitions_context[file_path][instruction_name].append(definition_resource) return definitions_context
null
2,276
from __future__ import annotations from collections import OrderedDict from pathlib import Path from typing import TYPE_CHECKING from dockerfile_parse import DockerfileParser from dockerfile_parse.constants import COMMENT_INSTRUCTION from checkov.common.typing import _SkippedCheck from checkov.common.util.suppression import collect_suppressions_for_context class _SkippedCheck(TypedDict, total=False): bc_id: str | None id: str suppress_comment: str line_number: int | None def collect_suppressions_for_context(code_lines: Iterable[tuple[int, int | str]]) -> list[_SkippedCheck]: """Searches for suppressions in a config block to be used in a context""" skipped_checks = [] bc_id_mapping = metadata_integration.bc_to_ckv_id_mapping for line_number, line_text in code_lines: skip_search = re.search(COMMENT_REGEX, str(line_text)) if skip_search: skipped_check: _SkippedCheck = { "id": skip_search.group(2), "suppress_comment": skip_search.group(3)[1:] if skip_search.group(3) else "No comment provided", "line_number": line_number } # No matter which ID was used to skip, save the pair of IDs in the appropriate fields if bc_id_mapping and skipped_check["id"] in bc_id_mapping: skipped_check["bc_id"] = skipped_check["id"] skipped_check["id"] = bc_id_mapping[skipped_check["id"]] elif metadata_integration.check_metadata: skipped_check["bc_id"] = metadata_integration.get_bc_id(skipped_check["id"]) skipped_checks.append(skipped_check) return skipped_checks def collect_skipped_checks(parse_result: dict[str, list[_Instruction]]) -> list[_SkippedCheck]: skipped_checks = [] if COMMENT_INSTRUCTION in parse_result: # line number doesn't matter comment_lines = [(0, comment["value"]) for comment in parse_result[COMMENT_INSTRUCTION]] skipped_checks = collect_suppressions_for_context(code_lines=comment_lines) return skipped_checks
null
2,277
from __future__ import annotations import os import re from collections.abc import Iterable from checkov.common.runners.base_runner import ignored_directories, safe_remove from checkov.common.util.consts import DEFAULT_EXTERNAL_MODULES_DIR EXCLUDED_PATHS = [*ignored_directories, DEFAULT_EXTERNAL_MODULES_DIR, ".idea", ".git", "venv"] def safe_remove(names: list[Any], path: Any) -> None: if path in names: names.remove(path) The provided code snippet includes necessary dependencies for implementing the `filter_excluded_paths` function. Write a Python function `def filter_excluded_paths( root_dir: str, names: list[str] | list[os.DirEntry[str]], excluded_paths: Iterable[str] | None, ) -> None` to solve the following problem: Special build of checkov.common.runners.base_runner.filter_ignored_paths for Secrets scanning Here is the function: def filter_excluded_paths( root_dir: str, names: list[str] | list[os.DirEntry[str]], excluded_paths: Iterable[str] | None, ) -> None: """Special build of checkov.common.runners.base_runner.filter_ignored_paths for Secrets scanning""" # support for the --skip-path flag if excluded_paths: compiled = [] for p in excluded_paths: try: compiled.append(re.compile(p.replace(".terraform", r"\.terraform"))) except re.error: # do not add compiled paths that aren't regexes continue for entry in list(names): path = entry.name if isinstance(entry, os.DirEntry) else entry full_path = os.path.join(root_dir, path) if any(pattern.search(full_path) for pattern in compiled) or any(p in full_path for p in excluded_paths): safe_remove(names, entry) # support for our own excluded paths list for entry in list(names): path = entry.name if isinstance(entry, os.DirEntry) else entry if path in EXCLUDED_PATHS: safe_remove(names, entry)
Special build of checkov.common.runners.base_runner.filter_ignored_paths for Secrets scanning
2,278
from __future__ import annotations import logging from collections import defaultdict from typing import TYPE_CHECKING, Dict, List, Optional, TypedDict from checkov.common.util.data_structures_utils import pickle_deepcopy from checkov.common.util.secrets import omit_secret_value_from_line from checkov.common.secrets.consts import GIT_HISTORY_NOT_BEEN_REMOVED from checkov.secrets.git_types import EnrichedPotentialSecretMetadata, EnrichedPotentialSecret, Commit, ADDED, REMOVED, \ GIT_HISTORY_OPTIONS, CommitDiff def omit_secret_value_from_line(secret: str | None, line_text: str) -> str: if not secret or not isinstance(secret, str): return line_text secret_length = len(secret) secret_len_to_expose = min(secret_length // 4, 6) # no more than 6 characters should be exposed try: secret_index = line_text.index(secret) except ValueError: try: secret_index = line_text.index(json.dumps(secret)) except ValueError: return line_text censored_line = f'{line_text[:secret_index + secret_len_to_expose]}' \ f'{"*" * GENERIC_OBFUSCATION_LENGTH}' \ f'{line_text[secret_index + secret_length:]}' return censored_line CommitDiff = str def search_for_code_line(commit_diff: CommitDiff, secret_value: Optional[str], is_added: Optional[bool]) -> str: if not commit_diff: logging.warning(f'missing file name for {commit_diff}, hence no available code line') if secret_value is None: return '' splitted = commit_diff.split('\n') start_char = '+' if is_added else '-' for line in splitted: if line.startswith(start_char) and secret_value in line: # remove +/- in the beginning & spaces and omit return omit_secret_value_from_line(secret_value, line[1:].strip()) or '' return '' # not found
null
2,279
from __future__ import annotations import logging from collections import defaultdict from typing import TYPE_CHECKING, Dict, List, Optional, TypedDict from checkov.common.util.data_structures_utils import pickle_deepcopy from checkov.common.util.secrets import omit_secret_value_from_line from checkov.common.secrets.consts import GIT_HISTORY_NOT_BEEN_REMOVED from checkov.secrets.git_types import EnrichedPotentialSecretMetadata, EnrichedPotentialSecret, Commit, ADDED, REMOVED, \ GIT_HISTORY_OPTIONS, CommitDiff The provided code snippet includes necessary dependencies for implementing the `get_secret_key` function. Write a Python function `def get_secret_key(file_name: str, secret_hash: str, secret_type: str) -> str` to solve the following problem: One way to create a secret key for the secret map Here is the function: def get_secret_key(file_name: str, secret_hash: str, secret_type: str) -> str: """ One way to create a secret key for the secret map """ secret_key = f'{file_name}_{secret_hash}_{secret_type.replace(" ", "-")}' return secret_key
One way to create a secret key for the secret map
2,280
from __future__ import annotations import logging from typing import Any, Dict, List, Optional import yaml from checkov.common.bridgecrew.platform_integration import bc_integration from checkov.common.util.file_utils import decompress_file_gzip_base64 def modify_secrets_policy_to_detectors(policies_list: List[dict[str, Any]]) -> List[dict[str, Any]]: secrets_list = transforms_policies_to_detectors_list(policies_list) logging.debug(f"(modify_secrets_policy_to_detectors) len secrets_list = {len(secrets_list)}") return secrets_list bc_integration = BcPlatformIntegration() def load_detectors() -> list[dict[str, Any]]: detectors: List[dict[str, Any]] = [] try: customer_run_config_response = bc_integration.customer_run_config_response policies_list: List[dict[str, Any]] = [] if customer_run_config_response: policies_list = customer_run_config_response.get('secretsPolicies', []) except Exception as e: logging.error(f"Failed to get detectors from customer_run_config_response, error: {e}") return [] if policies_list: detectors = modify_secrets_policy_to_detectors(policies_list) if detectors: logging.info(f"Successfully loaded {len(detectors)} detectors from bc_integration") return detectors
null
2,281
from __future__ import annotations import logging from typing import Any, Dict, List, Optional import yaml from checkov.common.bridgecrew.platform_integration import bc_integration from checkov.common.util.file_utils import decompress_file_gzip_base64 def decompress_file_gzip_base64(compressed_file_body: str) -> bytes: def get_runnable_plugins(policies: List[Dict[str, Any]]) -> Dict[str, str]: runnables: dict[str, str] = {} for policy in policies: code = policy['code'] if code: try: code_dict = yaml.safe_load(code) if 'definition' in code_dict: if 'is_runnable' in code_dict['definition'] and 'value' in code_dict['definition']: encoded_payload = code_dict['definition']['value'] if isinstance(encoded_payload, list): encoded_payload = encoded_payload[0] decoded_payload = decompress_file_gzip_base64(encoded_payload) name: str = policy['title'] runnables[name] = decoded_payload.decode('utf8') except Exception as e: logging.warning(f"Could not parse runnable policy {policy['title']} due to: {e}") return runnables
null
2,282
from __future__ import annotations import json import re from re import Pattern from typing import Any, TYPE_CHECKING, Optional from detect_secrets.util.filetype import FileType from detect_secrets.plugins.keyword import DENYLIST from detect_secrets.plugins.keyword import AFFIX_REGEX from detect_secrets.plugins.keyword import CLOSING from detect_secrets.plugins.keyword import OPTIONAL_WHITESPACE from detect_secrets.plugins.keyword import QUOTE from detect_secrets.plugins.keyword import SECRET from checkov.secrets.parsers.terraform.multiline_parser import terraform_multiline_parser from checkov.secrets.parsers.terraform.single_line_parser import terraform_single_line_parser from checkov.secrets.parsers.yaml.multiline_parser import yml_multiline_parser from checkov.secrets.parsers.json.multiline_parser import json_multiline_parser FOLLOWED_BY_EQUAL_VALUE_KEYWORD_REGEX = re.compile( # e.g. var = MY_PASSWORD_123 r'{whitespace}({key})?={whitespace}({quote}?){words}{denylist}({closing})?(\3)'.format( key=KEY, whitespace=OPTIONAL_WHITESPACE, quote=QUOTE, words=AFFIX_REGEX, denylist=DENY_LIST_REGEX2, closing=CLOSING, ), flags=re.IGNORECASE, ) FUNCTION_CALL_AFTER_KEYWORD_REGEX = re.compile(r'({allowlist})\s*(:|=)\s*{suffix}'.format( allowlist=ALLOW_LIST_REGEX, suffix=AFFIX_REGEX, )) def get_processed_line(formatted_line: str, secret_value: str) -> str: def remove_fp_secrets_in_keys(detected_secrets: set[PotentialSecret], line: str, is_code_file: bool = False) -> None: formatted_line = line.replace('"', '').replace("'", '') secrets_to_remove = set() for detected_secret in detected_secrets: if not detected_secret.secret_value: continue processed_line = get_processed_line(formatted_line, detected_secret.secret_value) # Found keyword prefix as potential secret if processed_line.startswith(detected_secret.secret_value): secrets_to_remove.add(detected_secret) # found a function name at the end of the line if processed_line and FUNCTION_CALL_AFTER_KEYWORD_REGEX.search(processed_line): secrets_to_remove.add(detected_secret) # secret value is substring of keywork if is_code_file and FOLLOWED_BY_EQUAL_VALUE_KEYWORD_REGEX.search(processed_line): key, value = line.split("=", 1) if detected_secret.secret_value in key and detected_secret.secret_value in value: secrets_to_remove.add(detected_secret) detected_secrets -= secrets_to_remove
null
2,283
from __future__ import annotations import json import re from re import Pattern from typing import Any, TYPE_CHECKING, Optional from detect_secrets.util.filetype import FileType from detect_secrets.plugins.keyword import DENYLIST from detect_secrets.plugins.keyword import AFFIX_REGEX from detect_secrets.plugins.keyword import CLOSING from detect_secrets.plugins.keyword import OPTIONAL_WHITESPACE from detect_secrets.plugins.keyword import QUOTE from detect_secrets.plugins.keyword import SECRET from checkov.secrets.parsers.terraform.multiline_parser import terraform_multiline_parser from checkov.secrets.parsers.terraform.single_line_parser import terraform_single_line_parser from checkov.secrets.parsers.yaml.multiline_parser import yml_multiline_parser from checkov.secrets.parsers.json.multiline_parser import json_multiline_parser MAX_KEYWORD_LIMIT = 500 def format_reducing_noise_secret(string: str) -> str: return json.dumps(string) def extract_from_string(pattern: dict[Pattern[str], int] | None, string: str) -> set[str]: matches: set[str] = set() if not pattern: return matches for value_regex, group_number in pattern.items(): match = value_regex.search(string) if match: matches |= {match.group(group_number).rstrip('\n')} return matches def detect_secret( scanners: tuple[BasePlugin, ...], filename: str, line: str, line_number: int = 0, is_multiline: Optional[bool] = None, **kwargs: Any, ) -> set[PotentialSecret]: for scanner in scanners: matches = scanner.analyze_line(filename, line, line_number, **kwargs) if matches: if is_multiline: mark_set_multiline(matches) return matches return set() class BaseMultiLineParser(ABC): def get_lines_from_same_object( self, search_range: range, context: CodeSnippet | None, raw_context: CodeSnippet | None, line_length_limit: int = 0, ) -> set[str]: possible_keywords: set[str] = set() if not context or not raw_context: return possible_keywords for j in search_range: line = raw_context.lines[j] if line_length_limit and len(line) > line_length_limit: continue if self.consecutive_lines_in_same_object(raw_context=raw_context, other_line_idx=j) \ and not self.is_line_comment(line): possible_keywords.add(raw_context.lines[j]) if self.is_object_start(line=line) or self.is_object_end(line=line): return possible_keywords # No start of array detected, hence all found possible_keywords are irrelevant return set() def consecutive_lines_in_same_object( self, raw_context: CodeSnippet | None, other_line_idx: int, ) -> bool: pass def is_object_start( line: str, ) -> bool: pass def is_object_end( line: str, ) -> bool: pass def is_line_comment( line: str ) -> bool: pass def analyze_multiline_keyword_combinator( filename: str, scanners: tuple[BasePlugin, ...], multiline_parser: BaseMultiLineParser, line_number: int, context: CodeSnippet | None = None, raw_context: CodeSnippet | None = None, value_pattern: dict[Pattern[str], int] | None = None, secret_pattern: dict[Pattern[str], int] | None = None, is_added: bool = False, is_removed: bool = False, **kwargs: Any, ) -> set[PotentialSecret]: secrets: set[PotentialSecret] = set() if context is None or raw_context is None: return secrets value_secrets = extract_from_string(pattern=secret_pattern, string=context.target_line) for possible_secret in value_secrets: secret_adjust = format_reducing_noise_secret(possible_secret) potential_secrets = detect_secret( scanners=scanners, filename=filename, line=secret_adjust, line_number=line_number, is_added=is_added, is_removed=is_removed, is_multiline=True, # always true because we check here for multiline kwargs=kwargs ) if potential_secrets: possible_keywords: set[str] = set() backwards_range = range(context.target_index - 1, -1, -1) forward_range = range(context.target_index + 1, len(context.lines)) possible_keywords |= multiline_parser.get_lines_from_same_object( search_range=forward_range, context=context, raw_context=raw_context, line_length_limit=MAX_KEYWORD_LIMIT) possible_keywords |= multiline_parser.get_lines_from_same_object( search_range=backwards_range, context=context, raw_context=raw_context, line_length_limit=MAX_KEYWORD_LIMIT) for other_value in possible_keywords: if extract_from_string(pattern=value_pattern, string=other_value): secrets |= potential_secrets break return secrets
null
2,284
from enum import Enum from typing import List, Any, Set from pathlib import Path class BqlVersion(str, Enum): def __str__(self) -> str: return self.value V0_1 = '0.1' V0_2 = '0.2' def get_bql_version_from_string(version_str: str) -> str: for version in BqlVersion: if version.value == version_str: return version return ''
null
2,285
from typing import Dict, List, Any, Optional, Union from pydantic import BaseModel, model_serializer from checkov.common.sast.consts import SastLanguages class RuleMatch(BaseModel): check_id: str # noqa: CCE003 check_name: str # noqa: CCE003 check_cwe: Optional[Union[List[str], str]] # noqa: CCE003 check_owasp: Optional[Union[List[str], str]] # noqa: CCE003 severity: str # noqa: CCE003 matches: List[Match] # noqa: CCE003 metadata: Optional[RuleMatchMetadata] = None # noqa: CCE003 class PrismaReport(BaseModel): rule_match: Dict[SastLanguages, Dict[str, RuleMatch]] # noqa: CCE003 errors: Dict[str, List[str]] # noqa: CCE003 profiler: Dict[str, Profiler] # noqa: CCE003 run_metadata: Dict[str, Optional[Union[str, int, List[str]]]] # noqa: CCE003 imports: Dict[SastLanguages, Dict[str, Dict[str, Union[List[str], Dict[str, str]]]]] # noqa: CCE003 reachability_report: Dict[SastLanguages, Dict[str, Repositories]] # noqa: CCE003 class SastLanguages(Enum): def list(cls) -> List[Any]: return list(map(lambda c: c.value, cls)) def set(cls) -> Set["SastLanguages"]: return set(cls) PYTHON = 'python' JAVA = 'java' JAVASCRIPT = 'javascript' def create_empty_report(languages: List[SastLanguages]) -> PrismaReport: matches: Dict[SastLanguages, Dict[str, RuleMatch]] = {} for lang in languages: matches[lang] = {} return PrismaReport(rule_match=matches, errors={}, profiler={}, run_metadata={}, imports={}, reachability_report={})
null
2,286
from typing import Dict, List, Any, Optional, Union from pydantic import BaseModel, model_serializer from checkov.common.sast.consts import SastLanguages class Repositories(BaseModel): files: Dict[str, File] # noqa: CCE003 def serialize_reachability_report(report: Dict[str, Repositories]) -> Dict[str, Any]: result: Dict[str, Any] = {} for repo_path, files in report.items(): result[repo_path] = {"files": {}} for file_name, packages in files.files.items(): result[repo_path]["files"][file_name] = {"packages": {}} for package_name, package in packages.packages.items(): result[repo_path]["files"][file_name]["packages"][package_name] = {"alias": package.alias, "functions": []} for function in package.functions: result[repo_path]["files"][file_name]["packages"][package_name]["functions"].append(function.to_dict()) return result
null
2,287
from __future__ import annotations import logging import os.path from json import JSONDecodeError from typing import Dict, Set, Any import re import json import os MODULE_EXPORTS_PATTERN = r'module\.exports\s*=\s*({.*?});' def _parse_export(file_content: str, pattern: str) -> Dict[str, Any] | None: module_export_match = re.search(pattern, file_content, re.DOTALL) if module_export_match: module_exports_str = module_export_match.group(1) # for having for all the keys and values double quotes and removing spaces module_exports_str = re.sub(r'\s+', '', re.sub(r'([{\s,])(\w+):', r'\1"\2":', module_exports_str) .replace("'", "\"")) module_exports: Dict[str, Any] = json.loads(module_exports_str) return module_exports return None def parse_webpack_file(file_content: str, relevant_packages: Set[str]) -> Dict[str, Any]: output: Dict[str, Any] = {"packageAliases": {}} module_exports_json = _parse_export(file_content, MODULE_EXPORTS_PATTERN) if module_exports_json: aliases = module_exports_json.get("resolve", {}).get("alias", {}) for imported_name in aliases: package_name = aliases[imported_name] if package_name in relevant_packages: output["packageAliases"].setdefault(package_name, {"packageAliases": []})["packageAliases"].append(imported_name) return output
null
2,288
from __future__ import annotations import logging import os.path from json import JSONDecodeError from typing import Dict, Set, Any import re import json import os def parse_tsconfig_file(file_content: str, relevant_packages: Set[str]) -> Dict[str, Any]: output: Dict[str, Any] = {"packageAliases": {}} tsconfig_json = json.loads(file_content) paths = tsconfig_json.get("compilerOptions", {}).get("paths", {}) for imported_name in paths: for package_relative_path in paths[imported_name]: package_name = os.path.basename(package_relative_path) if package_name in relevant_packages: output["packageAliases"].setdefault(package_name, {"packageAliases": []})["packageAliases"].append(imported_name) return output
null
2,289
from __future__ import annotations import logging import os.path from json import JSONDecodeError from typing import Dict, Set, Any import re import json import os def parse_babel_file(file_content: str, relevant_packages: Set[str]) -> Dict[str, Any]: output: Dict[str, Any] = {"packageAliases": {}} babelrc_json = json.loads(file_content) plugins = babelrc_json.get("plugins", {}) for plugin in plugins: if len(plugin) > 1: plugin_object = plugin[1] aliases = plugin_object.get("alias", {}) for imported_name in aliases: package_name = aliases[imported_name] if package_name in relevant_packages: output["packageAliases"].setdefault(package_name, {"packageAliases": []})["packageAliases"].append(imported_name) return output
null
2,290
from __future__ import annotations import logging import os.path from json import JSONDecodeError from typing import Dict, Set, Any import re import json import os EXPORT_DEFAULT_PATTERN = r'export\s*default\s*({.*?});' def parse_rollup_file(file_content: str, relevant_packages: Set[str]) -> Dict[str, Any]: output: Dict[str, Any] = {"packageAliases": {}} export_default_match = re.search(EXPORT_DEFAULT_PATTERN, file_content, re.DOTALL) if export_default_match: export_default_str = export_default_match.group(1) # for having for all the keys and values doube quotes and removing spaces export_default_str = re.sub(r'\s+', '', re.sub(r'([{\s,])(\w+):', r'\1"\2":', export_default_str) .replace("'", "\"")) # Defining a regular expression pattern to match the elements within the "plugins" list pattern = r'alias\(\{[^)]*\}\)' matches = re.findall(pattern, export_default_str) for alias_object_str in matches: alias_object = json.loads(alias_object_str[6:-1]) # removing 'alias(' and ')' for entry in alias_object.get("entries", []): package_name = entry["replacement"] if entry["replacement"] in relevant_packages: imported_name = entry["find"] output["packageAliases"].setdefault(package_name, {"packageAliases": []})["packageAliases"].append(imported_name) return output
null
2,291
from __future__ import annotations import logging import os.path from json import JSONDecodeError from typing import Dict, Set, Any import re import json import os def parse_package_json_file(file_content: str, relevant_packages: Set[str]) -> Dict[str, Any]: output: Dict[str, Any] = {"packageAliases": {}} try: package_json = json.loads(file_content) except JSONDecodeError: logging.warning('unable to parse package json file') return output aliases: Dict[str, str] = dict() if "alias" in package_json: aliases.update(package_json["alias"]) if package_json.get("aliasify", {}).get("aliases"): aliases.update(package_json["aliasify"]["aliases"]) for imported_name in aliases: package_name = aliases[imported_name] if package_name in relevant_packages: output["packageAliases"].setdefault(package_name, {"packageAliases": []})["packageAliases"].append(imported_name) return output
null
2,292
from __future__ import annotations import logging import os.path from json import JSONDecodeError from typing import Dict, Set, Any import re import json import os MODULE_EXPORTS_PATTERN = r'module\.exports\s*=\s*({.*?});' def _parse_export(file_content: str, pattern: str) -> Dict[str, Any] | None: def parse_snowpack_file(file_content: str, relevant_packages: Set[str]) -> Dict[str, Any]: output: Dict[str, Any] = {"packageAliases": {}} module_exports_json = _parse_export(file_content, MODULE_EXPORTS_PATTERN) if module_exports_json: aliases = module_exports_json.get("alias", {}) for imported_name in aliases: package_name = aliases[imported_name] if package_name in relevant_packages: if package_name in relevant_packages: output["packageAliases"].setdefault(package_name, {"packageAliases": []})["packageAliases"].append(imported_name) return output
null
2,293
from __future__ import annotations import logging import os.path from json import JSONDecodeError from typing import Dict, Set, Any import re import json import os EXPORT_DEFAULT_PATTERN = r'export\s*default\s*({.*?});' def _parse_export(file_content: str, pattern: str) -> Dict[str, Any] | None: module_export_match = re.search(pattern, file_content, re.DOTALL) if module_export_match: module_exports_str = module_export_match.group(1) # for having for all the keys and values double quotes and removing spaces module_exports_str = re.sub(r'\s+', '', re.sub(r'([{\s,])(\w+):', r'\1"\2":', module_exports_str) .replace("'", "\"")) module_exports: Dict[str, Any] = json.loads(module_exports_str) return module_exports return None def parse_vite_file(file_content: str, relevant_packages: Set[str]) -> Dict[str, Any]: output: Dict[str, Any] = {"packageAliases": {}} export_default_match = _parse_export(file_content, EXPORT_DEFAULT_PATTERN) if export_default_match: aliases = export_default_match.get("resolve", {}).get("alias", {}) for imported_name in aliases: package_name = aliases[imported_name] if package_name in relevant_packages: output["packageAliases"].setdefault(package_name, {"packageAliases": []})["packageAliases"].append(imported_name) return output
null
2,294
from enum import Enum from typing import Optional, Dict from checkov.common.sast.consts import SastLanguages class ScaPackageFile(Enum): PACKAGE_JSON = 'package.json' PACKAGE_JSON_LOCK = 'package-lock.json' POM_XML = 'pom.xml' BUILD_GRADLE = 'build.gradle' PIPFILE = 'Pipfile' PIPFILE_LOCK = 'Pipfile.lock' def get_package_by_str(package_name: str) -> Optional[ScaPackageFile]: for enum_member in ScaPackageFile: if enum_member.value == package_name: return enum_member return None
null
2,295
from __future__ import annotations import logging from collections import defaultdict from datetime import datetime, timedelta from typing import TYPE_CHECKING, Any, Optional, Dict, List from checkov.common.bridgecrew.integration_features.features.policy_metadata_integration import ( integration as metadata_integration, ) from checkov.common.bridgecrew.platform_integration import bc_integration from checkov.common.bridgecrew.severities import Severities, Severity from checkov.common.models.enums import CheckResult, ScanDataFormat from checkov.common.output.extra_resource import ExtraResource from checkov.common.output.record import Record, DEFAULT_SEVERITY, SCA_PACKAGE_SCAN_CHECK_NAME, SCA_LICENSE_CHECK_NAME from checkov.common.packaging import version as packaging_version from checkov.common.sca.commons import ( get_file_path_for_record, get_resource_for_record, get_package_alias, UNFIXABLE_VERSION, get_package_type, normalize_twistcli_language, get_registry_url, get_package_lines, get_record_file_line_range, get_license_policy_and_package_alias ) from checkov.common.util.http_utils import request_wrapper from checkov.runner_filter import RunnerFilter from checkov.common.output.common import format_licenses_to_string def create_root_packages_list(root_packages_list: list[int], packages: list[dict[str, Any]], package: dict[str, Any], dependencies: Optional[Dict[str, List[int]]]) -> None: if dependencies: if package.get("root", ""): root_packages_list.append(packages.index(package)) else: # if we don't have dependencies, all packages will be "roots" root_packages_list.append(packages.index(package))
null
2,296
from __future__ import annotations import logging from collections import defaultdict from datetime import datetime, timedelta from typing import TYPE_CHECKING, Any, Optional, Dict, List from checkov.common.bridgecrew.integration_features.features.policy_metadata_integration import ( integration as metadata_integration, ) from checkov.common.bridgecrew.platform_integration import bc_integration from checkov.common.bridgecrew.severities import Severities, Severity from checkov.common.models.enums import CheckResult, ScanDataFormat from checkov.common.output.extra_resource import ExtraResource from checkov.common.output.record import Record, DEFAULT_SEVERITY, SCA_PACKAGE_SCAN_CHECK_NAME, SCA_LICENSE_CHECK_NAME from checkov.common.packaging import version as packaging_version from checkov.common.sca.commons import ( get_file_path_for_record, get_resource_for_record, get_package_alias, UNFIXABLE_VERSION, get_package_type, normalize_twistcli_language, get_registry_url, get_package_lines, get_record_file_line_range, get_license_policy_and_package_alias ) from checkov.common.util.http_utils import request_wrapper from checkov.runner_filter import RunnerFilter from checkov.common.output.common import format_licenses_to_string def _add_to_report_licenses_statuses( report: Report, check_class: str | None, scanned_file_path: str, rootless_file_path: str, runner_filter: RunnerFilter, packages_map: dict[str, dict[str, Any]], license_statuses: list[_LicenseStatus], sca_details: SCADetails | None = None, report_type: str | None = None, inline_suppressions_maps: _ScaSuppressionsMaps | None = None, ) -> dict[str, list[str]]: licenses_per_package_map: dict[str, list[str]] = defaultdict(list) for license_status in license_statuses: # filling 'licenses_per_package_map', will be used in the call to 'create_report_cve_record' for efficient # extracting of license per package package_name, package_version, license = ( license_status["package_name"], license_status["package_version"], license_status["license"], ) package_alias = get_package_alias(package_name, package_version) licenses_per_package_map[package_alias].append(license) policy = license_status["policy"] severity = metadata_integration.get_severity(policy) license_record = create_report_license_record( rootless_file_path=rootless_file_path, file_abs_path=scanned_file_path, check_class=check_class or "", licenses_status=license_status, package=packages_map.get(package_alias, {}), sca_details=sca_details, severity=severity ) vulnerability_details = license_record.vulnerability_details or {} # apply inline suppressions suppressed = apply_licenses_inline_suppressions( record=license_record, vulnerability_details=vulnerability_details, inline_suppressions_maps=inline_suppressions_maps ) if not suppressed and not runner_filter.should_run_check( check_id=policy, bc_check_id=policy, severity=severity, report_type=report_type, ): if runner_filter.checks: continue else: license_record.check_result = { "result": CheckResult.SKIPPED, "suppress_comment": f"{policy} is skipped", } report.add_resource(license_record.resource) report.add_record(license_record) return licenses_per_package_map def get_inline_suppressions_map(inline_suppressions: _ScaSuppressions | None = None) -> _ScaSuppressionsMaps | None: if not inline_suppressions: return None suppressions_map: _ScaSuppressionsMaps = {} # fill cves suppressions map cve_suppresion_by_cve_map: dict[str, _SuppressedCves] = {} inline_suppressions_by_cve: list[_SuppressedCves] = inline_suppressions.get("cves", {}).get("byCve", []) for cve_suppression in inline_suppressions_by_cve: cve_id = cve_suppression.get("cveId") if cve_id: cve_suppresion_by_cve_map[cve_id] = cve_suppression # fill licenses suppressions map licenses_suppressions_by_policy_and_package_map: dict[str, _SuppressedLicenses] = {} inline_suppressions_by_license: list[_SuppressedLicenses] = inline_suppressions.get("licenses", {}).get("byPackage", []) for license_suppression in inline_suppressions_by_license: if license_suppression.get("licensePolicy") and license_suppression.get("packageName"): key = get_license_policy_and_package_alias(license_suppression["licensePolicy"], license_suppression["packageName"]) licenses_suppressions_by_policy_and_package_map[key] = license_suppression suppressions_map['cve_suppresion_by_cve_map'] = cve_suppresion_by_cve_map suppressions_map[ 'licenses_suppressions_by_policy_and_package_map'] = licenses_suppressions_by_policy_and_package_map return suppressions_map def add_to_reports_cves_and_packages( report: Report, check_class: str | None, scanned_file_path: str, rootless_file_path: str, runner_filter: RunnerFilter, vulnerabilities: list[dict[str, Any]], packages: list[dict[str, Any]], packages_map: dict[str, dict[str, Any]], licenses_per_package_map: dict[str, list[str]], used_private_registry: bool = False, dependencies: dict[str, List[int]] | None = None, sca_details: SCADetails | None = None, report_type: str | None = None, inline_suppressions_maps: _ScaSuppressionsMaps | None = None, scan_data_format: ScanDataFormat = ScanDataFormat.TWISTCLI, file_line_range: list[int] | None = None ) -> None: is_dependency_tree_flow = bool(dependencies) vulnerable_packages, root_packages_list = create_vulnerable_packages_dict(vulnerabilities, packages, is_dependency_tree_flow) for package in packages: package_name, package_version = package["name"], package["version"] package_alias = get_package_alias(package_name, package_version) if package_alias in vulnerable_packages: package["cves"] = vulnerable_packages[package_alias] else: # adding resources without cves for adding them also in the output-bom-repors add_extra_resources_to_report(report, scanned_file_path, rootless_file_path, package, package_alias, licenses_per_package_map, sca_details) if is_dependency_tree_flow: add_to_reports_dependency_tree_cves(check_class, packages_map, licenses_per_package_map, packages, report, root_packages_list, rootless_file_path, runner_filter, scanned_file_path, used_private_registry, scan_data_format, sca_details, report_type, inline_suppressions_maps) else: # twistlock scan results. for vulnerability in vulnerabilities: package_name, package_version = vulnerability["packageName"], vulnerability["packageVersion"] add_cve_record_to_report(vulnerability_details=vulnerability, package_name=package_name, package_version=package_version, packages_map=packages_map, rootless_file_path=rootless_file_path, scanned_file_path=scanned_file_path, check_class=check_class or "", licenses_per_package_map=licenses_per_package_map, runner_filter=runner_filter, sca_details=sca_details, scan_data_format=scan_data_format, report_type=report_type, report=report, inline_suppressions_maps=inline_suppressions_maps, file_line_range=file_line_range, used_private_registry=used_private_registry) class ScanDataFormat(Enum): TWISTCLI = 1 PLATFORM = 2 DEPENDENCY_TREE = 3 def get_package_alias(package_name: str, package_version: str) -> str: return f"{package_name}@{package_version}" class RunnerFilter(object): # NOTE: This needs to be static because different filters may be used at load time versus runtime # (see note in BaseCheckRegistery.register). The concept of which checks are external is # logically a "static" concept anyway, so this makes logical sense. __EXTERNAL_CHECK_IDS: Set[str] = set() def __init__( self, framework: Optional[List[str]] = None, checks: Union[str, List[str], None] = None, skip_checks: Union[str, List[str], None] = None, include_all_checkov_policies: bool = True, download_external_modules: bool = False, external_modules_download_path: str = DEFAULT_EXTERNAL_MODULES_DIR, evaluate_variables: bool = True, runners: Optional[List[str]] = None, skip_framework: Optional[List[str]] = None, excluded_paths: Optional[List[str]] = None, all_external: bool = False, var_files: Optional[List[str]] = None, skip_cve_package: Optional[List[str]] = None, use_enforcement_rules: bool = False, filtered_policy_ids: Optional[List[str]] = None, show_progress_bar: Optional[bool] = True, run_image_referencer: bool = False, enable_secret_scan_all_files: bool = False, block_list_secret_scan: Optional[List[str]] = None, deep_analysis: bool = False, repo_root_for_plan_enrichment: Optional[List[str]] = None, resource_attr_to_omit: Optional[Dict[str, Set[str]]] = None, enable_git_history_secret_scan: bool = False, git_history_timeout: str = '12h', git_history_last_commit_scanned: Optional[str] = None, # currently not exposed by a CLI flag report_sast_imports: bool = False, remove_default_sast_policies: bool = False, report_sast_reachability: bool = False ) -> None: checks = convert_csv_string_arg_to_list(checks) skip_checks = convert_csv_string_arg_to_list(skip_checks) self.skip_invalid_secrets = skip_checks and any(skip_check.capitalize() == ValidationStatus.INVALID.value for skip_check in skip_checks) self.use_enforcement_rules = use_enforcement_rules self.enforcement_rule_configs: Dict[str, Severity | Dict[CodeCategoryType, Severity]] = {} # we will store the lowest value severity we find in checks, and the highest value we find in skip-checks # so the logic is "run all checks >= severity" and/or "skip all checks <= severity" self.check_threshold = None self.skip_check_threshold = None self.checks = [] self.bc_cloned_checks: dict[str, list[dict[str, Any]]] = defaultdict(list) self.skip_checks = [] self.skip_checks_regex_patterns = defaultdict(list) self.show_progress_bar = show_progress_bar # split out check/skip thresholds so we can access them easily later for val in (checks or []): if val.upper() in Severities: val = val.upper() if not self.check_threshold or self.check_threshold.level > Severities[val].level: self.check_threshold = Severities[val] else: self.checks.append(val) # Get regex patterns to split checks and remove it from skip checks: updated_skip_checks = set(skip_checks) for val in (skip_checks or []): splitted_check = val.split(":") # In case it's not expected pattern if len(splitted_check) != 2: continue self.skip_checks_regex_patterns[splitted_check[0]].append(splitted_check[1]) updated_skip_checks -= {val} skip_checks = list(updated_skip_checks) for val in (skip_checks or []): if val.upper() in Severities: val = val.upper() if not self.skip_check_threshold or self.skip_check_threshold.level < Severities[val].level: self.skip_check_threshold = Severities[val] else: self.skip_checks.append(val) self.include_all_checkov_policies = include_all_checkov_policies if not framework or "all" in framework: self.framework_flag_values = [] else: self.framework_flag_values = framework self.framework: "Iterable[str]" = framework if framework else ["all"] if skip_framework: if "all" in self.framework: if runners is None: runners = [] self.framework = set(runners) - set(skip_framework) else: self.framework = set(self.framework) - set(skip_framework) logging.debug(f"Resultant set of frameworks (removing skipped frameworks): {','.join(self.framework)}") self.download_external_modules = download_external_modules self.external_modules_download_path = external_modules_download_path self.evaluate_variables = evaluate_variables self.excluded_paths = excluded_paths or [] self.all_external = all_external self.var_files = var_files self.skip_cve_package = skip_cve_package self.filtered_policy_ids = filtered_policy_ids or [] self.run_image_referencer = run_image_referencer self.enable_secret_scan_all_files = enable_secret_scan_all_files self.block_list_secret_scan = block_list_secret_scan self.suppressed_policies: List[str] = [] self.deep_analysis = deep_analysis self.repo_root_for_plan_enrichment = repo_root_for_plan_enrichment self.resource_attr_to_omit: DefaultDict[str, Set[str]] = RunnerFilter._load_resource_attr_to_omit( resource_attr_to_omit ) self.sast_languages: Set[SastLanguages] = RunnerFilter.get_sast_languages(framework, skip_framework) if self.sast_languages and any(item for item in self.framework if item.startswith(CheckType.SAST) or item == 'all'): self.framework = [item for item in self.framework if not item.startswith(CheckType.SAST)] self.framework.append(CheckType.SAST) elif not self.sast_languages: # remove all SAST and CDK frameworks self.framework = [ item for item in self.framework if not item.startswith(CheckType.SAST) and item != CheckType.CDK ] self.enable_git_history_secret_scan: bool = enable_git_history_secret_scan if self.enable_git_history_secret_scan: self.git_history_timeout = convert_to_seconds(git_history_timeout) self.framework = [CheckType.SECRETS] logging.debug("Scan secrets history was enabled ignoring other frameworks") self.git_history_last_commit_scanned = git_history_last_commit_scanned self.report_sast_imports = report_sast_imports self.remove_default_sast_policies = remove_default_sast_policies self.report_sast_reachability = report_sast_reachability def _load_resource_attr_to_omit(resource_attr_to_omit_input: Optional[Dict[str, Set[str]]]) -> DefaultDict[str, Set[str]]: resource_attributes_to_omit: DefaultDict[str, Set[str]] = defaultdict(set) # In order to create new object (and not a reference to the given one) if resource_attr_to_omit_input: resource_attributes_to_omit.update(resource_attr_to_omit_input) return resource_attributes_to_omit def apply_enforcement_rules(self, enforcement_rule_configs: Dict[str, CodeCategoryConfiguration]) -> None: self.enforcement_rule_configs = {} for report_type, code_category in CodeCategoryMapping.items(): if isinstance(code_category, list): self.enforcement_rule_configs[report_type] = {c: enforcement_rule_configs.get(c).soft_fail_threshold for c in code_category} # type:ignore[union-attr] # will not be None else: config = enforcement_rule_configs.get(code_category) if not config: raise Exception(f'Could not find an enforcement rule config for category {code_category} (runner: {report_type})') self.enforcement_rule_configs[report_type] = config.soft_fail_threshold def extract_enforcement_rule_threshold(self, check_id: str, report_type: str) -> Severity: if 'sca_' in report_type and '_LIC_' in check_id: return cast("dict[CodeCategoryType, Severity]", self.enforcement_rule_configs[report_type])[CodeCategoryType.LICENSES] elif 'sca_' in report_type: # vulnerability return cast("dict[CodeCategoryType, Severity]", self.enforcement_rule_configs[report_type])[CodeCategoryType.VULNERABILITIES] else: return cast(Severity, self.enforcement_rule_configs[report_type]) def should_run_check( self, check: BaseCheck | BaseGraphCheck | BaseSastCheck | None = None, check_id: str | None = None, bc_check_id: str | None = None, severity: Severity | None = None, report_type: str | None = None, file_origin_paths: List[str] | None = None, root_folder: str | None = None ) -> bool: if check: check_id = check.id bc_check_id = check.bc_id severity = check.severity assert check_id is not None # nosec (for mypy (and then for bandit)) check_threshold: Optional[Severity] skip_check_threshold: Optional[Severity] # apply enforcement rules if specified, but let --check/--skip-check with a severity take priority if self.use_enforcement_rules and report_type: if not self.check_threshold and not self.skip_check_threshold: check_threshold = self.extract_enforcement_rule_threshold(check_id, report_type) skip_check_threshold = None else: check_threshold = self.check_threshold skip_check_threshold = self.skip_check_threshold else: if self.use_enforcement_rules: # this is a warning for us (but there is nothing the user can do about it) logging.debug(f'Use enforcement rules is true, but check {check_id} was not passed to the runner filter with a report type') check_threshold = self.check_threshold skip_check_threshold = self.skip_check_threshold run_severity = severity and check_threshold and severity.level >= check_threshold.level explicit_run = self.checks and self.check_matches(check_id, bc_check_id, self.checks) implicit_run = not self.checks and not check_threshold is_external = RunnerFilter.is_external_check(check_id) is_policy_filtered = self.is_policy_filtered(check_id) # True if this check is present in the allow list, or if there is no allow list # this is not necessarily the return value (need to apply other filters) should_run_check = ( run_severity or explicit_run or implicit_run or (is_external and self.all_external) ) if not should_run_check: logging.debug(f'Should run check {check_id}: False') return False # If a policy is not present in the list of filtered policies, it should not be run - implicitly or explicitly. # It can, however, be skipped. if not is_policy_filtered: logging.debug(f'not is_policy_filtered {check_id}: should_run_check = False') should_run_check = False skip_severity = severity and skip_check_threshold and severity.level <= skip_check_threshold.level explicit_skip = self.skip_checks and self.check_matches(check_id, bc_check_id, self.skip_checks) regex_match = self._match_regex_pattern(check_id, file_origin_paths, root_folder) should_skip_check = ( skip_severity or explicit_skip or regex_match or (not bc_check_id and not self.include_all_checkov_policies and not is_external and not explicit_run) or (bc_check_id in self.suppressed_policies and bc_check_id not in self.bc_cloned_checks) ) logging.debug(f'skip_severity = {skip_severity}, explicit_skip = {explicit_skip}, regex_match = {regex_match}, suppressed_policies: {self.suppressed_policies}') logging.debug( f'bc_check_id = {bc_check_id}, include_all_checkov_policies = {self.include_all_checkov_policies}, is_external = {is_external}, explicit_run: {explicit_run}') if should_skip_check: result = False logging.debug(f'should_skip_check {check_id}: {should_skip_check}') elif should_run_check: result = True logging.debug(f'should_run_check {check_id}: {result}') else: result = False logging.debug(f'default {check_id}: {result}') return result def _match_regex_pattern(self, check_id: str, file_origin_paths: List[str] | None, root_folder: str | None) -> bool: """ Check if skip check_id for a certain file_types, according to given path pattern """ if not file_origin_paths: return False regex_patterns = self.skip_checks_regex_patterns.get(check_id, []) # In case skip is generic, for example, CKV_AZURE_*. generic_check_id = f"{'_'.join(i for i in check_id.split('_')[:-1])}_*" generic_check_regex_patterns = self.skip_checks_regex_patterns.get(generic_check_id, []) regex_patterns.extend(generic_check_regex_patterns) if not regex_patterns: return False for pattern in regex_patterns: if not pattern: continue full_regex_pattern = fr"^{root_folder}/{pattern}" if root_folder else pattern try: if any(re.search(full_regex_pattern, path) for path in file_origin_paths): return True except Exception as exc: logging.error( "Invalid regex pattern has been supplied", extra={"regex_pattern": pattern, "exc": str(exc)} ) return False def check_matches(check_id: str, bc_check_id: Optional[str], pattern_list: List[str]) -> bool: return any( (fnmatch.fnmatch(check_id, pattern) or (bc_check_id and fnmatch.fnmatch(bc_check_id, pattern))) for pattern in pattern_list) def within_threshold(self, severity: Severity) -> bool: above_min = (not self.check_threshold) or self.check_threshold.level <= severity.level below_max = self.skip_check_threshold and self.skip_check_threshold.level >= severity.level return above_min and not below_max def secret_validation_status_matches(secret_validation_status: str, statuses_list: list[str]) -> bool: return secret_validation_status in statuses_list def notify_external_check(check_id: str) -> None: RunnerFilter.__EXTERNAL_CHECK_IDS.add(check_id) def is_external_check(check_id: str) -> bool: return check_id in RunnerFilter.__EXTERNAL_CHECK_IDS def is_policy_filtered(self, check_id: str) -> bool: if not self.filtered_policy_ids: return True return check_id in self.filtered_policy_ids def to_dict(self) -> Dict[str, Any]: result: Dict[str, Any] = {} for key, value in self.__dict__.items(): result[key] = value return result def from_dict(obj: Dict[str, Any]) -> RunnerFilter: framework = obj.get('framework') checks = obj.get('checks') skip_checks = obj.get('skip_checks') include_all_checkov_policies = obj.get('include_all_checkov_policies') if include_all_checkov_policies is None: include_all_checkov_policies = True download_external_modules = obj.get('download_external_modules') if download_external_modules is None: download_external_modules = False external_modules_download_path = obj.get('external_modules_download_path') if external_modules_download_path is None: external_modules_download_path = DEFAULT_EXTERNAL_MODULES_DIR evaluate_variables = obj.get('evaluate_variables') if evaluate_variables is None: evaluate_variables = True runners = obj.get('runners') skip_framework = obj.get('skip_framework') excluded_paths = obj.get('excluded_paths') all_external = obj.get('all_external') if all_external is None: all_external = False var_files = obj.get('var_files') skip_cve_package = obj.get('skip_cve_package') use_enforcement_rules = obj.get('use_enforcement_rules') if use_enforcement_rules is None: use_enforcement_rules = False filtered_policy_ids = obj.get('filtered_policy_ids') show_progress_bar = obj.get('show_progress_bar') if show_progress_bar is None: show_progress_bar = True run_image_referencer = obj.get('run_image_referencer') if run_image_referencer is None: run_image_referencer = False enable_secret_scan_all_files = bool(obj.get('enable_secret_scan_all_files')) block_list_secret_scan = obj.get('block_list_secret_scan') runner_filter = RunnerFilter(framework, checks, skip_checks, include_all_checkov_policies, download_external_modules, external_modules_download_path, evaluate_variables, runners, skip_framework, excluded_paths, all_external, var_files, skip_cve_package, use_enforcement_rules, filtered_policy_ids, show_progress_bar, run_image_referencer, enable_secret_scan_all_files, block_list_secret_scan) return runner_filter def set_suppressed_policies(self, policy_level_suppressions: List[str]) -> None: logging.debug(f"Received the following policy-level suppressions, that will be skipped from running: {policy_level_suppressions}") self.suppressed_policies = policy_level_suppressions def get_sast_languages(frameworks: Optional[List[str]], skip_framework: Optional[List[str]]) -> Set[SastLanguages]: langs: Set[SastLanguages] = set() if not frameworks or (skip_framework and "sast" in skip_framework): return langs if 'all' in frameworks: sast_languages = SastLanguages.set() skip_framework = [] if not skip_framework else [f.split("sast_")[-1] for f in skip_framework] return set([lang for lang in sast_languages if lang.value not in skip_framework]) for framework in frameworks: if framework in [CheckType.SAST, CheckType.CDK]: for sast_lang in SastLanguages: langs.add(sast_lang) return langs if not framework.startswith(CheckType.SAST): continue lang = '_'.join(framework.split('_')[1:]) langs.add(SastLanguages[lang.upper()]) return langs class SCADetails: package_types: dict[str, str] = field(default_factory=dict) class Report: def __init__(self, check_type: str): self.check_type = check_type self.passed_checks: list[Record] = [] self.failed_checks: list[Record] = [] self.skipped_checks: list[Record] = [] self.parsing_errors: list[str] = [] self.resources: set[str] = set() self.extra_resources: set[ExtraResource] = set() self.image_cached_results: List[dict[str, Any]] = [] self.error_status: ErrorStatus = ErrorStatus.SUCCESS def errors(self) -> Dict[str, List[str]]: return dict() def set_error_status(self, error_status: ErrorStatus) -> None: self.error_status = error_status def add_parsing_errors(self, errors: "Iterable[str]") -> None: for file in errors: self.add_parsing_error(file) def add_parsing_error(self, file: str) -> None: if file: self.parsing_errors.append(file) def add_resource(self, resource: str) -> None: self.resources.add(resource) def add_record(self, record: Record) -> None: if record.check_result["result"] == CheckResult.PASSED: self.passed_checks.append(record) if record.check_result["result"] == CheckResult.FAILED: self.failed_checks.append(record) if record.check_result["result"] == CheckResult.SKIPPED: self.skipped_checks.append(record) def get_summary(self) -> Dict[str, Union[int, str]]: return { "passed": len(self.passed_checks), "failed": len(self.failed_checks), "skipped": len(self.skipped_checks), "parsing_errors": len(self.parsing_errors), "resource_count": len(self.resources), "checkov_version": version, } def get_json(self) -> str: return json.dumps(self.get_dict(), indent=4, cls=CustomJSONEncoder) def get_all_records(self) -> List[Record]: return self.failed_checks + self.passed_checks + self.skipped_checks def get_dict(self, is_quiet: bool = False, url: str | None = None, full_report: bool = False, s3_setup_failed: bool = False, support_path: str | None = None) -> dict[str, Any]: if not url and not s3_setup_failed: url = "Add an api key '--bc-api-key <api-key>' to see more detailed insights via https://bridgecrew.cloud" elif s3_setup_failed: url = S3_UPLOAD_DETAILS_MESSAGE if is_quiet: return { "check_type": self.check_type, "results": { "failed_checks": [check.__dict__ for check in self.failed_checks] }, "summary": self.get_summary(), } if full_report: return { "check_type": self.check_type, "checks": { "passed_checks": [check.__dict__ for check in self.passed_checks], "failed_checks": [check.__dict__ for check in self.failed_checks], "skipped_checks": [check.__dict__ for check in self.skipped_checks] }, "image_cached_results": [res.__dict__ for res in self.image_cached_results] } else: result = { "check_type": self.check_type, "results": { "passed_checks": [check.__dict__ for check in self.passed_checks], "failed_checks": [check.__dict__ for check in self.failed_checks], "skipped_checks": [check.__dict__ for check in self.skipped_checks], "parsing_errors": list(self.parsing_errors), }, "summary": self.get_summary(), "url": url, } if support_path: result["support_path"] = support_path return result def get_exit_code(self, exit_code_thresholds: Union[_ExitCodeThresholds, _ScaExitCodeThresholds]) -> int: """ Returns the appropriate exit code depending on the flags that are passed in. :return: Exit code 0 or 1. """ hard_fail_on_parsing_errors = os.getenv(PARSE_ERROR_FAIL_FLAG, "false").lower() == 'true' logging.debug(f'In get_exit_code; exit code thresholds: {exit_code_thresholds}, hard_fail_on_parsing_errors: {hard_fail_on_parsing_errors}') if self.parsing_errors and hard_fail_on_parsing_errors: logging.debug('hard_fail_on_parsing_errors is True and there were parsing errors - returning 1') return 1 if not self.failed_checks: logging.debug('No failed checks in this report - returning 0') return 0 # we will have two different sets of logic in this method, determined by this variable. # if we are using enforcement rules, then there are two different sets of thresholds that apply for licenses and vulnerabilities # and we have to handle that throughout while processing the report # if we are not using enforcement rules, then we can combine licenses and vulnerabilities like normal and same as all other report types # this determination is made in runner_registry.get_fail_thresholds has_split_enforcement = CodeCategoryType.LICENSES in exit_code_thresholds hard_fail_threshold: Optional[Severity | Dict[str, Severity]] soft_fail: Optional[bool | Dict[str, bool]] if has_split_enforcement: sca_thresholds = cast(_ScaExitCodeThresholds, exit_code_thresholds) # these three are the same even in split enforcement rules generic_thresholds = cast(_ExitCodeThresholds, next(iter(sca_thresholds.values()))) soft_fail_on_checks = generic_thresholds['soft_fail_checks'] soft_fail_threshold = generic_thresholds['soft_fail_threshold'] hard_fail_on_checks = generic_thresholds['hard_fail_checks'] # these two can be different for licenses / vulnerabilities hard_fail_threshold = {category: thresholds['hard_fail_threshold'] for category, thresholds in sca_thresholds.items()} # type:ignore[index] # thinks it's an object, can't possibly be more clear soft_fail = {category: thresholds['soft_fail'] for category, thresholds in sca_thresholds.items()} # type:ignore[index] # thinks it's an object failed_checks_by_category = { CodeCategoryType.LICENSES: [fc for fc in self.failed_checks if '_LIC_' in fc.check_id], CodeCategoryType.VULNERABILITIES: [fc for fc in self.failed_checks if '_VUL_' in fc.check_id] } has_soft_fail_values = soft_fail_on_checks or soft_fail_threshold if all( not failed_checks_by_category[cast(CodeCategoryType, c)] or ( not has_soft_fail_values and not (hard_fail_threshold[c] or hard_fail_on_checks) and soft_fail[c] ) for c in sca_thresholds.keys() ): logging.debug( 'No failed checks, or soft_fail is True and soft_fail_on and hard_fail_on are empty for all SCA types - returning 0') return 0 if any( not has_soft_fail_values and not (hard_fail_threshold[c] or hard_fail_on_checks) and failed_checks_by_category[cast(CodeCategoryType, c)] for c in sca_thresholds.keys() ): logging.debug('There are failed checks and all soft/hard fail args are empty for one or more SCA reports - returning 1') return 1 else: non_sca_thresholds = cast(_ExitCodeThresholds, exit_code_thresholds) soft_fail_on_checks = non_sca_thresholds['soft_fail_checks'] soft_fail_threshold = non_sca_thresholds['soft_fail_threshold'] hard_fail_on_checks = non_sca_thresholds['hard_fail_checks'] hard_fail_threshold = non_sca_thresholds['hard_fail_threshold'] soft_fail = non_sca_thresholds['soft_fail'] has_soft_fail_values = soft_fail_on_checks or soft_fail_threshold has_hard_fail_values = hard_fail_threshold or hard_fail_on_checks if not has_soft_fail_values and not has_hard_fail_values and soft_fail: logging.debug('Soft_fail is True and soft_fail_on and hard_fail_on are empty - returning 0') return 0 elif not has_soft_fail_values and not has_hard_fail_values: logging.debug('There are failed checks and all soft/hard fail args are empty - returning 1') return 1 for failed_check in self.failed_checks: check_id = failed_check.check_id bc_check_id = failed_check.bc_check_id severity = failed_check.severity secret_validation_status = failed_check.validation_status if hasattr(failed_check, 'validation_status') else '' hf_threshold: Severity sf: bool if has_split_enforcement: category = CodeCategoryType.LICENSES if '_LIC_' in check_id else CodeCategoryType.VULNERABILITIES hard_fail_threshold = cast(Dict[str, Severity], hard_fail_threshold) hf_threshold = hard_fail_threshold[category] soft_fail = cast(Dict[str, bool], soft_fail) sf = soft_fail[category] else: hard_fail_threshold = cast(Severity, hard_fail_threshold) hf_threshold = hard_fail_threshold soft_fail = cast(bool, soft_fail) sf = soft_fail soft_fail_severity = severity and soft_fail_threshold and severity.level <= soft_fail_threshold.level hard_fail_severity = severity and hf_threshold and severity.level >= hf_threshold.level explicit_soft_fail = RunnerFilter.check_matches(check_id, bc_check_id, soft_fail_on_checks) explicit_hard_fail = RunnerFilter.check_matches(check_id, bc_check_id, hard_fail_on_checks) explicit_secrets_soft_fail = RunnerFilter.secret_validation_status_matches(secret_validation_status, soft_fail_on_checks) explicit_secrets_hard_fail = RunnerFilter.secret_validation_status_matches(secret_validation_status, hard_fail_on_checks) implicit_soft_fail = not explicit_hard_fail and not explicit_secrets_hard_fail and not soft_fail_on_checks and not soft_fail_threshold implicit_hard_fail = not explicit_soft_fail and not soft_fail_severity and not explicit_secrets_soft_fail if explicit_hard_fail or \ (hard_fail_severity and not explicit_soft_fail) or \ (implicit_hard_fail and not implicit_soft_fail and not sf): logging.debug(f'Check {check_id} (BC ID: {bc_check_id}, severity: {severity.level if severity else None} triggered hard fail - returning 1') return 1 logging.debug('No failed check triggered hard fail - returning 0') return 0 def is_empty(self, full: bool = False) -> bool: checks_count = ( len(self.passed_checks) + len(self.failed_checks) + len(self.skipped_checks) + len(self.parsing_errors) ) if full: checks_count += len(self.resources) + len(self.extra_resources) + len(self.image_cached_results) return checks_count == 0 def add_errors_to_output(self) -> str: ret_value = '' for error_title, errors_messages in self.errors.items(): ret_value += colored(f"Encountered {error_title} error - {len(errors_messages)} times\n\n", "red") return ret_value def print_console( self, is_quiet: bool = False, is_compact: bool = False, created_baseline_path: str | None = None, baseline: Baseline | None = None, use_bc_ids: bool = False, summary_position: str = 'top', openai_api_key: str | None = None, ) -> str: summary = self.get_summary() output_data = colored(f"{self.check_type} scan results:\n", "blue") if self.parsing_errors: message = "\nPassed checks: {}, Failed checks: {}, Skipped checks: {}, Parsing errors: {}\n\n".format( summary["passed"], summary["failed"], summary["skipped"], summary["parsing_errors"], ) else: if self.check_type == CheckType.SCA_PACKAGE or self.check_type.lower().startswith(CheckType.SAST): message = f"\nFailed checks: {summary['failed']}, Skipped checks: {summary['skipped']}\n\n" else: message = f"\nPassed checks: {summary['passed']}, Failed checks: {summary['failed']}, Skipped checks: {summary['skipped']}\n\n" if summary_position == 'top': output_data += colored(message, "cyan") # output for vulnerabilities is different if self.check_type in (CheckType.SCA_PACKAGE, CheckType.SCA_IMAGE): if self.failed_checks or self.skipped_checks: create_cli_output = create_sca_package_cli_output_v2 output_data += create_cli_output(self.check_type == CheckType.SCA_PACKAGE, self.failed_checks, self.skipped_checks) elif self.check_type == CheckType.POLICY_3D: if self.failed_checks or self.skipped_checks: output_data += create_3d_policy_cli_output(self.failed_checks, self.skipped_checks) # type:ignore[arg-type] else: if self.check_type.lower().startswith(CheckType.SAST): output_data += colored(f"Source code files scanned: {summary.get(SOURCE_FILES_COUNT, -1)}, " f"Policies found: {summary.get(POLICY_COUNT, -1)}\n\n", "cyan") policies_errors: str = str(summary.get(POLICIES_ERRORS, "")) if policies_errors: output_data += colored(f"Policy parsing failures ({summary.get(POLICIES_ERRORS_COUNT)}):\n{policies_errors}\n\n", "red") if not is_quiet: for record in self.passed_checks: output_data += record.to_string(compact=is_compact, use_bc_ids=use_bc_ids) if self.failed_checks: OpenAi(api_key=openai_api_key).enhance_records(runner_type=self.check_type, records=self.failed_checks) for record in self.failed_checks: output_data += record.to_string(compact=is_compact, use_bc_ids=use_bc_ids) if not is_quiet: for record in self.skipped_checks: output_data += record.to_string(compact=is_compact, use_bc_ids=use_bc_ids) if not is_quiet: for file in self.parsing_errors: output_data += colored(f"Error parsing file {file}ֿ\n", "red") if created_baseline_path: output_data += colored( f"Created a checkov baseline file at {created_baseline_path}", "blue", ) if baseline: output_data += colored( f"Baseline analysis report using {baseline.path} - only new failed checks with respect to the baseline are reported", "blue", ) if summary_position == 'bottom': output_data += colored(message, "cyan") return output_data def _print_parsing_error_console(file: str) -> None: print(colored(f"Error parsing file {file}", "red")) def get_junit_xml_string(ts: list[TestSuite]) -> str: return to_xml_report_string(ts) def print_failed_github_md(self, use_bc_ids: bool = False) -> str: result = [] for record in self.failed_checks: result.append( [ record.get_output_id(use_bc_ids), record.file_path, record.resource, record.check_name, record.guideline, ] ) if result: table = tabulate( result, headers=["check_id", "file", "resource", "check_name", "guideline"], tablefmt="github", showindex=True, ) output_data = f"### {self.check_type} scan results:\n\n{table}\n\n---\n" return output_data else: return "\n\n---\n\n" def get_test_suite(self, properties: Optional[Dict[str, Any]] = None, use_bc_ids: bool = False) -> TestSuite: """Creates a test suite for the JUnit XML report""" test_cases = [] records = self.passed_checks + self.failed_checks + self.skipped_checks for record in records: severity = BcSeverities.NONE if record.severity: severity = record.severity.name if self.check_type == CheckType.SCA_PACKAGE: if record.check_name != SCA_PACKAGE_SCAN_CHECK_NAME: continue if not record.vulnerability_details: # this shouldn't normally happen logging.warning(f"Vulnerability check without details {record.file_path}") continue check_id = record.vulnerability_details["id"] test_name_detail = f"{record.vulnerability_details['package_name']}: {record.vulnerability_details['package_version']}" class_name = f"{record.file_path}.{record.vulnerability_details['package_name']}" else: check_id = record.bc_check_id if use_bc_ids else record.check_id test_name_detail = record.check_name class_name = f"{record.file_path}.{record.resource}" test_name = f"[{severity}][{check_id}] {test_name_detail}" test_case = TestCase(name=test_name, file=record.file_path, classname=class_name) if record.check_result["result"] == CheckResult.FAILED: test_case.add_failure_info( message=record.check_name, output=self._create_test_case_failure_output(record) ) if record.check_result["result"] == CheckResult.SKIPPED: if self.check_type == CheckType.SCA_PACKAGE: test_case.add_skipped_info(f"{check_id} skipped for {test_name_detail}") else: test_case.add_skipped_info(record.check_result.get("suppress_comment", "")) test_cases.append(test_case) test_suite = TestSuite(name=f"{self.check_type} scan", test_cases=test_cases, properties=properties) return test_suite def create_test_suite_properties_block(config: argparse.Namespace) -> Dict[str, Any]: """Creates a dictionary without 'None' values for the JUnit XML properties block""" properties = {k: v for k, v in config.__dict__.items() if v is not None} return properties def _create_test_case_failure_output(self, record: Record) -> str: """Creates the failure output for a JUnit XML test case IaC example: Resource: azurerm_network_security_rule.fail_rdp File: /main.tf: 71-83 Guideline: https://docs.bridgecrew.io/docs/bc_azr_networking_2 71 | resource "azurerm_network_security_rule" "fail_rdp" { 72 | resource_group_name = azurerm_resource_group.example.name 73 | network_security_group_name=azurerm_network_security_group.example_rdp.name 74 | name = "fail_security_rule" 75 | direction = "Inbound" 76 | access = "Allow" 77 | protocol = "TCP" 78 | source_port_range = "*" 79 | destination_port_range = "3389" 80 | source_address_prefix = "*" 81 | destination_address_prefix = "*" 82 | priority = 120 83 | } SCA example: Description: Django before 1.11.27, 2.x before 2.2.9, and 3.x before 3.0.1 allows account takeover. Link: https://nvd.nist.gov/vuln/detail/CVE-2019-19844 Published Date: 2019-12-18T20:15:00+01:00 Base Score: 9.8 Vector: CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H Risk Factors: ['Attack complexity: low', 'Attack vector: network', 'Critical severity', 'Has fix'] Resource: requirements.txt.django File: /requirements.txt: 0-0 0 | django: 1.2 """ failure_output = [] if self.check_type == CheckType.SCA_PACKAGE: if record.vulnerability_details: lowest_fixed_version = record.vulnerability_details.get('lowest_fixed_version') if lowest_fixed_version is not None: fix = lowest_fixed_version else: fixlist = record.vulnerability_details.get('fixed_versions') if fixlist is not None: fix = fixlist failure_output.extend( [ "", f"Description: {record.description}", f"Link: {record.vulnerability_details.get('link')}", f"Published Date: {record.vulnerability_details.get('published_date')}", f"Base Score: {record.vulnerability_details.get('cvss')}", f"Vector: {record.vulnerability_details.get('vector')}", f"Risk Factors: {record.vulnerability_details.get('risk_factors')}", "Fix Details:", f" Status: {record.vulnerability_details.get('status')}", f" Fixed Version: {fix}", ] ) else: # this shouldn't normally happen logging.warning(f"Vulnerability check without details {record.file_path}") failure_output.extend( [ "", f"Resource: {record.resource}", ] ) if record.file_path: file_line = f"File: {record.file_path}" if record.file_line_range: file_line += f": {record.file_line_range[0]}-{record.file_line_range[1]}" failure_output.append(file_line) if self.check_type != CheckType.SCA_PACKAGE: failure_output.append(f"Guideline: {record.guideline}") if record.code_block: failure_output.append("") failure_output.append(record._code_line_string(code_block=record.code_block, colorized=False)) return "\n".join(failure_output) def print_json(self) -> None: print(self.get_json()) def enrich_plan_report( report: "Report", enriched_resources: Dict[str, Dict[str, Any]] ) -> "Report": # This enriches reports with the appropriate filepath, line numbers, and codeblock for record in report.failed_checks: resource_raw_id = Report.get_plan_resource_raw_id(record.resource) enriched_resource = enriched_resources.get(resource_raw_id) if enriched_resource: record.file_path = enriched_resource["scanned_file"] record.file_line_range = enriched_resource["entity_lines_range"] record.code_block = enriched_resource["entity_code_lines"] return report def handle_skipped_checks( report: "Report", enriched_resources: Dict[str, Dict[str, Any]] ) -> "Report": module_address_len = len("module.") skip_records = [] for record in report.failed_checks: resource_raw_id = Report.get_plan_resource_raw_id(record.resource) resource_skips = enriched_resources.get(resource_raw_id, {}).get( "skipped_checks", [] ) for skip in resource_skips: if record.check_id in skip["id"]: # Mark for removal and add it as a skipped record. It is not safe to remove # the record from failed_checks immediately because we're iterating over it skip_records.append(record) record.check_result["result"] = CheckResult.SKIPPED record.check_result["suppress_comment"] = skip["suppress_comment"] report.add_record(record) if record.resource_address and record.resource_address.startswith("module."): module_path = record.resource_address[module_address_len:record.resource_address.index('.', module_address_len + 1)] module_enrichments = enriched_resources.get(module_path, {}) for module_skip in module_enrichments.get("skipped_checks", []): if record.check_id in module_skip["id"]: skip_records.append(record) record.check_result["result"] = CheckResult.SKIPPED record.check_result["suppress_comment"] = module_skip["suppress_comment"] report.add_record(record) for record in skip_records: if record in report.failed_checks: report.failed_checks.remove(record) return report def get_plan_resource_raw_id(resource_id: str) -> str: """ return the resource raw id without the modules and the indexes example: from resource_id='module.module_name.type.name[1]' return 'type.name' """ resource_raw_id = ".".join(resource_id.split(".")[-2:]) if '[' in resource_raw_id: resource_raw_id = resource_raw_id[:resource_raw_id.index('[')] return resource_raw_id def from_reduced_json(cls, json_report: dict[str, Any], check_type: str) -> Report: report = Report(check_type) report.image_cached_results = json_report['image_cached_results'] all_json_records = json_report["checks"]["passed_checks"] + \ json_report["checks"]["failed_checks"] + \ json_report["checks"]["skipped_checks"] for json_record in all_json_records: report.add_record( Record.from_reduced_json(json_record) ) return report class _ScaSuppressionsMaps(TypedDict, total=False): cve_suppresion_by_cve_map: dict[str, _SuppressedCves] licenses_suppressions_by_policy_and_package_map: dict[str, _SuppressedLicenses] class _ScaSuppressions(TypedDict, total=False): cves: _CvesSuppressions licenses: _LicensesSuppressions class _LicenseStatus(TypedDict): package_name: str package_version: str policy: str license: str status: str def add_to_report_sca_data( report: Report, check_class: str | None, scanned_file_path: str, rootless_file_path: str, runner_filter: RunnerFilter, vulnerabilities: list[dict[str, Any]], packages: list[dict[str, Any]], license_statuses: list[_LicenseStatus], used_private_registry: bool = False, dependencies: dict[str, list[int]] | None = None, sca_details: SCADetails | None = None, report_type: str | None = None, inline_suppressions: _ScaSuppressions | None = None, file_line_range: list[int] | None = None ) -> None: inline_suppressions_maps: _ScaSuppressionsMaps | None = get_inline_suppressions_map(inline_suppressions) packages_map: dict[str, dict[str, Any]] = {get_package_alias(p["name"], p["version"]): p for p in packages} licenses_per_package_map: dict[str, list[str]] = \ _add_to_report_licenses_statuses(report, check_class, scanned_file_path, rootless_file_path, runner_filter, packages_map, license_statuses, sca_details, report_type, inline_suppressions_maps) # if dependencies is empty list it means we got results via DependencyTree scan but no dependencies have found. add_to_reports_cves_and_packages(report=report, check_class=check_class, scanned_file_path=scanned_file_path, rootless_file_path=rootless_file_path, runner_filter=runner_filter, vulnerabilities=vulnerabilities, packages=packages, packages_map=packages_map, licenses_per_package_map=licenses_per_package_map, sca_details=sca_details, report_type=report_type, scan_data_format=ScanDataFormat.DEPENDENCY_TREE, dependencies=dependencies, inline_suppressions_maps=inline_suppressions_maps, file_line_range=file_line_range, used_private_registry=used_private_registry)
null
2,297
from __future__ import annotations import logging from collections import defaultdict from datetime import datetime, timedelta from typing import TYPE_CHECKING, Any, Optional, Dict, List from checkov.common.bridgecrew.integration_features.features.policy_metadata_integration import ( integration as metadata_integration, ) from checkov.common.bridgecrew.platform_integration import bc_integration from checkov.common.bridgecrew.severities import Severities, Severity from checkov.common.models.enums import CheckResult, ScanDataFormat from checkov.common.output.extra_resource import ExtraResource from checkov.common.output.record import Record, DEFAULT_SEVERITY, SCA_PACKAGE_SCAN_CHECK_NAME, SCA_LICENSE_CHECK_NAME from checkov.common.packaging import version as packaging_version from checkov.common.sca.commons import ( get_file_path_for_record, get_resource_for_record, get_package_alias, UNFIXABLE_VERSION, get_package_type, normalize_twistcli_language, get_registry_url, get_package_lines, get_record_file_line_range, get_license_policy_and_package_alias ) from checkov.common.util.http_utils import request_wrapper from checkov.runner_filter import RunnerFilter from checkov.common.output.common import format_licenses_to_string def _get_request_input(packages: list[dict[str, Any]]) -> list[dict[str, Any]]: return [ {"name": package.get("name", ""), "version": package.get("version", ""), "lang": normalize_twistcli_language(package.get("type", ""))} for package in packages ] def _extract_license_statuses(response_json: dict[str, list[dict[str, str]]]) -> list[_LicenseStatus]: license_statuses: list[_LicenseStatus] = [ { "package_name": license_violation.get("name", ""), "package_version": license_violation.get("version", ""), "policy": license_violation.get("policy", "BC_LIC1"), "license": license_violation.get("license", ""), "status": license_violation.get("status", "COMPLIANT") } for license_violation in response_json.get("violations", []) ] return license_statuses bc_integration = BcPlatformIntegration() def request_wrapper( method: str, url: str, headers: dict[str, Any], data: Any | None = None, json: dict[str, Any] | None = None, should_call_raise_for_status: bool = False, params: dict[str, Any] | None = None, log_json_body: bool = True ) -> Response: # using of "retry" mechanism for 'requests.request' due to unpredictable 'ConnectionError' and 'HttpError' # instances that appears from time to time. # 'ConnectionError' instances that appeared: # * 'Connection aborted.', ConnectionResetError(104, 'Connection reset by peer'). # * 'Connection aborted.', OSError(107, 'Socket not connected'). # 'HTTPError' instances that appeared: # * 403 Client Error: Forbidden for url. # * 504 Server Error: Gateway Time-out for url. request_max_tries = int(os.getenv('REQUEST_MAX_TRIES', 3)) sleep_between_request_tries = float(os.getenv('SLEEP_BETWEEN_REQUEST_TRIES', 1)) for i in range(request_max_tries): try: headers["X-Request-Id"] = str(uuid.uuid4()) response = requests.request( method=method, url=url, headers=headers, data=data, json=json, params=params, timeout=DEFAULT_TIMEOUT, ) if should_call_raise_for_status: response.raise_for_status() return response except requests.exceptions.ConnectionError as connection_error: logging.error(f"Connection error on request {method}:{url},\ndata:\n{data}\njson:{json if log_json_body else 'Redacted'}\nheaders:{headers}") if i != request_max_tries - 1: sleep_secs = sleep_between_request_tries * (i + 1) logging.info(f"retrying attempt number {i + 2} in {sleep_secs} seconds") time.sleep(sleep_secs) continue logging.exception("request_wrapper connection error") raise connection_error except requests.exceptions.HTTPError as http_error: status_code = 520 # set unknown error, if http_error.response is None if http_error.response is not None: status_code = http_error.response.status_code logging.error(f"HTTP error on request {method}:{url},\ndata:\n{data}\njson:{json if log_json_body else 'Redacted'}\nheaders:{headers}") if (status_code >= 500 or status_code == 403) and i != request_max_tries - 1: sleep_secs = sleep_between_request_tries * (i + 1) logging.info(f"retrying attempt number {i + 2} in {sleep_secs} seconds") time.sleep(sleep_secs) continue logging.error("request_wrapper http error", exc_info=True) raise http_error else: raise Exception("Unexpected behavior: the method \'request_wrapper\' should be terminated inside the above for-" "loop") class _LicenseStatus(TypedDict): package_name: str package_version: str policy: str license: str status: str def get_license_statuses(packages: list[dict[str, Any]]) -> list[_LicenseStatus]: requests_input = _get_request_input(packages) if not requests_input: return [] try: response = request_wrapper( method="POST", url=f"{bc_integration.api_url}/api/v1/vulnerabilities/packages/get-licenses-violations", headers=bc_integration.get_default_headers("POST"), json={"packages": requests_input}, should_call_raise_for_status=True ) response_json = response.json() license_statuses: list[_LicenseStatus] = _extract_license_statuses(response_json) return license_statuses except Exception: error_message = ( "failing when trying to get licenses-violations. it is apparently some unexpected " "connection issue. please try later. in case it keep happening. please report." ) logging.info(error_message, exc_info=True) return []
null
2,298
from __future__ import annotations import logging from collections import defaultdict from datetime import datetime, timedelta from typing import TYPE_CHECKING, Any, Optional, Dict, List from checkov.common.bridgecrew.integration_features.features.policy_metadata_integration import ( integration as metadata_integration, ) from checkov.common.bridgecrew.platform_integration import bc_integration from checkov.common.bridgecrew.severities import Severities, Severity from checkov.common.models.enums import CheckResult, ScanDataFormat from checkov.common.output.extra_resource import ExtraResource from checkov.common.output.record import Record, DEFAULT_SEVERITY, SCA_PACKAGE_SCAN_CHECK_NAME, SCA_LICENSE_CHECK_NAME from checkov.common.packaging import version as packaging_version from checkov.common.sca.commons import ( get_file_path_for_record, get_resource_for_record, get_package_alias, UNFIXABLE_VERSION, get_package_type, normalize_twistcli_language, get_registry_url, get_package_lines, get_record_file_line_range, get_license_policy_and_package_alias ) from checkov.common.util.http_utils import request_wrapper from checkov.runner_filter import RunnerFilter from checkov.common.output.common import format_licenses_to_string def _get_request_input(packages: list[dict[str, Any]]) -> list[dict[str, Any]]: return [ {"name": package.get("name", ""), "version": package.get("version", ""), "lang": normalize_twistcli_language(package.get("type", ""))} for package in packages ] def _extract_license_statuses(response_json: dict[str, list[dict[str, str]]]) -> list[_LicenseStatus]: license_statuses: list[_LicenseStatus] = [ { "package_name": license_violation.get("name", ""), "package_version": license_violation.get("version", ""), "policy": license_violation.get("policy", "BC_LIC1"), "license": license_violation.get("license", ""), "status": license_violation.get("status", "COMPLIANT") } for license_violation in response_json.get("violations", []) ] return license_statuses bc_integration = BcPlatformIntegration() class _ImageReferencerLicenseStatus(TypedDict): image_name: str licenses: list[_LicenseStatus] The provided code snippet includes necessary dependencies for implementing the `get_license_statuses_async` function. Write a Python function `async def get_license_statuses_async( session: ClientSession, packages: list[dict[str, Any]], image_name: str ) -> _ImageReferencerLicenseStatus` to solve the following problem: This is an async implementation of `get_license_statuses`. The only change is we're getting a session as an input, and the asyncio behavior is managed in the calling method. Here is the function: async def get_license_statuses_async( session: ClientSession, packages: list[dict[str, Any]], image_name: str ) -> _ImageReferencerLicenseStatus: """ This is an async implementation of `get_license_statuses`. The only change is we're getting a session as an input, and the asyncio behavior is managed in the calling method. """ requests_input = _get_request_input(packages) url = f"{bc_integration.api_url}/api/v1/vulnerabilities/packages/get-licenses-violations" if not requests_input: return {'image_name': image_name, 'licenses': []} try: async with session.request("POST", url, headers=bc_integration.get_default_headers("POST"), json={"packages": requests_input}) as resp: response_json = await resp.json() license_statuses = _extract_license_statuses(response_json) return {'image_name': image_name, 'licenses': license_statuses} except Exception as e: error_message = ( "failing when trying to get licenses-violations. it is apparently some unexpected " "connection issue. please try later. in case it keeps happening, please report." f"Error: {str(e)}" ) logging.info(error_message, exc_info=True) return {'image_name': image_name, 'licenses': []}
This is an async implementation of `get_license_statuses`. The only change is we're getting a session as an input, and the asyncio behavior is managed in the calling method.
2,299
from __future__ import annotations import logging from typing import List, Optional, Any, cast from checkov.common.output.common import SCADetails def should_run_scan(runner_filter_checks: Optional[List[str]]) -> bool: return not (runner_filter_checks and all( not (check.startswith("CKV_CVE") or check.startswith("BC_CVE") or check.startswith("BC_LIC")) for check in runner_filter_checks))
null
2,300
from __future__ import annotations import logging from typing import List, Optional, Any, cast from checkov.common.output.common import SCADetails UNFIXABLE_VERSION = "N/A" def get_fix_version(vulnerability_details: dict[str, Any]) -> str: if "fix_version" in vulnerability_details: return str(vulnerability_details["fix_version"]) if "lowest_fixed_version" in vulnerability_details: return str(vulnerability_details["lowest_fixed_version"]) return UNFIXABLE_VERSION
null
2,301
from __future__ import annotations import logging from collections.abc import Sequence from json import JSONDecoder from json.decoder import WHITESPACE, WHITESPACE_STR, BACKSLASH, STRINGCHUNK, JSONArray from typing import Any, Callable, Pattern, Match from json.scanner import NUMBER_RE from checkov.common.parsers.node import StrNode, DictNode, ListNode from checkov.common.parsers.json.errors import NullError, DuplicateError, DecodeError def _decode_uXXXX(s: str, pos: int) -> int: esc = s[pos + 1:pos + 5] if len(esc) == 4 and esc[1] not in 'xX': try: return int(esc, 16) except ValueError: pass msg = 'Invalid \\uXXXX escape' raise DecodeError(msg, s, pos) class DecodeError(ValueError): """Subclass of ValueError with the following additional properties: msg: The unformatted error message doc: The JSON document being parsed pos: The start index of doc where parsing failed lineno: The line corresponding to pos colno: The column corresponding to pos """ # Note that this exception is used from _json def __init__(self, msg: str, doc: str, pos: int, _key: str = " ") -> None: lineno = doc.count("\n", 0, pos) + 1 colno = pos - doc.rfind("\n", 0, pos) errmsg = "%s: line %d column %d (char %d)" % (msg, lineno, colno, pos) ValueError.__init__(self, errmsg) self.msg = msg self.doc = doc self.pos = pos self.lineno = lineno self.colno = colno def __reduce__(self) -> tuple[Type[DecodeError], tuple[str, str, int]]: return self.__class__, (self.msg, self.doc, self.pos) The provided code snippet includes necessary dependencies for implementing the `py_scanstring` function. Write a Python function `def py_scanstring( s: str, end: int, strict: bool = True, _b: dict[str, str] = BACKSLASH, _m: Callable[[str | Pattern[str], int], Match[str]] = STRINGCHUNK.match ) -> tuple[str, int]` to solve the following problem: Scan the string s for a JSON string. End is the index of the character in s after the quote that started the JSON string. Unescapes all valid JSON string escape sequences and raises ValueError on attempt to decode an invalid string. If strict is False then literal control characters are allowed in the string. Returns a tuple of the decoded string and the index of the character in s after the end quote. Here is the function: def py_scanstring( s: str, end: int, strict: bool = True, _b: dict[str, str] = BACKSLASH, _m: Callable[[str | Pattern[str], int], Match[str]] = STRINGCHUNK.match ) -> tuple[str, int]: """Scan the string s for a JSON string. End is the index of the character in s after the quote that started the JSON string. Unescapes all valid JSON string escape sequences and raises ValueError on attempt to decode an invalid string. If strict is False then literal control characters are allowed in the string. Returns a tuple of the decoded string and the index of the character in s after the end quote.""" chunks: list[str] = [] _append = chunks.append begin = end - 1 while 1: chunk = _m(s, end) if chunk is None: raise DecodeError('Unterminated string starting at', s, begin) end = chunk.end() content, terminator = chunk.groups() # Content is contains zero or more unescaped string characters if content: _append(content) # Terminator is the end of string, a literal control character, # or a backslash denoting that an escape sequence follows if terminator == '"': break if terminator != '\\': if strict: msg = 'Invalid control character {0!r} at'.format(terminator) raise DecodeError(msg, s, end) _append(terminator) continue try: esc = s[end] except IndexError as err: raise DecodeError('Unterminated string starting at', s, begin) from err # If not a unicode escape sequence, must be in the lookup table if esc != 'u': try: char = _b[esc] except KeyError as err: msg = 'Invalid \\escape: {0!r}'.format(esc) raise DecodeError(msg, s, end) from err end += 1 else: uni = _decode_uXXXX(s, end) end += 5 if 0xd800 <= uni <= 0xdbff and s[end:end + 2] == '\\u': uni2 = _decode_uXXXX(s, end + 1) if 0xdc00 <= uni2 <= 0xdfff: uni = 0x10000 + (((uni - 0xd800) << 10) | (uni2 - 0xdc00)) end += 6 char = chr(uni) _append(char) return ''.join(chunks), end
Scan the string s for a JSON string. End is the index of the character in s after the quote that started the JSON string. Unescapes all valid JSON string escape sequences and raises ValueError on attempt to decode an invalid string. If strict is False then literal control characters are allowed in the string. Returns a tuple of the decoded string and the index of the character in s after the end quote.
2,302
from __future__ import annotations import logging from collections.abc import Sequence from json import JSONDecoder from json.decoder import WHITESPACE, WHITESPACE_STR, BACKSLASH, STRINGCHUNK, JSONArray from typing import Any, Callable, Pattern, Match from json.scanner import NUMBER_RE from checkov.common.parsers.node import StrNode, DictNode, ListNode from checkov.common.parsers.json.errors import NullError, DuplicateError, DecodeError class Decoder(JSONDecoder): """ Converts a json string, where datetime and timedelta objects were converted into strings using the DateTimeAwareJSONEncoder, into a python object. """ def __init__(self, *args: Any, **kwargs: Any) -> None: self.allow_nulls = kwargs.pop("allow_nulls", True) JSONDecoder.__init__(self, *args, **kwargs) self.parse_object = self.json_object self.parse_array = self.json_array self.parse_string = py_scanstring self.memo: dict[str, str] = {} setattr(self, "object_pairs_hook", self.check_duplicates) # noqa: B010 # it is method assignment self.scan_once = py_make_scanner(self) self.newline_indexes: list[int] = [] def decode(self, s: str, _w: Callable[..., Any] | None = None) -> Any: """Overridden to retrieve indexes """ self.newline_indexes = find_indexes(s) obj = super().decode(s) return obj def json_array( self, s_and_end: tuple[str, int], scan_once: Callable[[str, int], tuple[Any, int]], **kwargs: Any ) -> tuple[ListNode, int]: """ Convert JSON array to be a list_node object """ values, end = JSONArray(s_and_end, scan_once, **kwargs) s, start = s_and_end beg_mark, end_mark = get_beg_end_mark(s, start, end, self.newline_indexes) return ListNode(values, beg_mark, end_mark), end def json_object( self, s_and_end: tuple[str, int], strict: bool, scan_once: Callable[[str, int], tuple[Any, int]], object_hook: Callable[[dict[str, Any], Mark, Mark], Any], object_pairs_hook: Callable[[list[tuple[str, Any]], Mark, Mark], Any], memo: dict[str, str] | None = None, _w: Callable[[str | Pattern[str], int], Match[str]] = WHITESPACE.match, _ws: str = WHITESPACE_STR, ) -> tuple[DictNode, int]: """ Custom Cfn JSON Object to store keys with start and end times """ s, end = s_and_end orginal_end = end pairs = [] # type:ignore[var-annotated] # overload var, don't bother fixing the type pairs_append = pairs.append # Backwards compatibility if memo is None: memo = {} memo_get = memo.setdefault # Use a slice to prevent IndexError from being raised, the following # check will raise a more specific ValueError if the string is empty nextchar = s[end:end + 1] # Normally we expect nextchar == '"' if nextchar != '"': if nextchar in _ws: end = _w(s, end).end() nextchar = s[end:end + 1] # Trivial empty object if nextchar == '}': if object_pairs_hook is not None: try: beg_mark, end_mark = get_beg_end_mark(s, orginal_end, end + 1, self.newline_indexes) result = object_pairs_hook(pairs, beg_mark, end_mark) return result, end + 1 except DuplicateError as err: raise DecodeError('Duplicate found', s, end) from err except NullError as err: raise DecodeError('Null Error', s, end) from err pairs = {} if object_hook is not None: beg_mark, end_mark = get_beg_end_mark(s, orginal_end, end + 1, self.newline_indexes) pairs = object_hook(pairs, beg_mark, end_mark) return pairs, end + 1 if nextchar != '"': raise DecodeError('Expecting property name enclosed in double quotes', s, end) end += 1 while True: begin = end - 1 key, end = py_scanstring(s, end, strict) # print(lineno, colno, obj) # print(key, lineno, colno) key = memo_get(key, key) # To skip some function call overhead we optimize the fast paths where # the JSON key separator is ": " or just ":". if s[end:end + 1] != ':': end = _w(s, end).end() if s[end:end + 1] != ':': raise DecodeError('Expecting \':\' delimiter', s, end) end += 1 try: if s[end] in _ws: end += 1 if s[end] in _ws: end = _w(s, end + 1).end() except IndexError: pass beg_mark, end_mark = get_beg_end_mark(s, begin, begin + len(key), self.newline_indexes) try: value, end = scan_once(s, end) except StopIteration as err: logging.debug("Failed to scan string", exc_info=True) raise DecodeError('Expecting value', s, end_mark.line) from err key_str = StrNode(key, beg_mark, end_mark) pairs_append((key_str, value)) try: nextchar = s[end] if nextchar in _ws: end = _w(s, end + 1).end() nextchar = s[end] except IndexError: nextchar = '' end += 1 if nextchar == '}': break if nextchar != ',': raise DecodeError('Expecting \',\' delimiter', s, end - 1) end = _w(s, end).end() nextchar = s[end:end + 1] end += 1 if nextchar != '"': raise DecodeError( 'Expecting property name enclosed in double quotes', s, end - 1) if object_pairs_hook is not None: try: beg_mark, end_mark = get_beg_end_mark(s, orginal_end, end, self.newline_indexes) result = object_pairs_hook(pairs, beg_mark, end_mark) except DuplicateError as err: raise DecodeError('Duplicate found', s, begin, key) from err except NullError as err: raise DecodeError('Null Error', s, begin, key) from err return result, end pairs = dict(pairs) if object_hook is not None: beg_mark, end_mark = get_beg_end_mark(s, orginal_end, end, self.newline_indexes) pairs = object_hook(pairs, beg_mark, end_mark) return pairs, end def check_duplicates(self, ordered_pairs: list[tuple[str, Any]], beg_mark: Mark, end_mark: Mark) -> DictNode: """ Check for duplicate keys on the current level, this is not desirable because a dict does not support this. It overwrites it with the last occurance, which can give unexpected results """ mapping = DictNode({}, beg_mark, end_mark) for key, value in ordered_pairs: if not self.allow_nulls and value is None: raise NullError('"{}"'.format(key)) if key in mapping: raise DuplicateError('"{}"'.format(key)) mapping[key] = value return mapping The provided code snippet includes necessary dependencies for implementing the `py_make_scanner` function. Write a Python function `def py_make_scanner(context: Decoder) -> Callable[[str, int], tuple[Any, int]]` to solve the following problem: Make python based scanner For this use case we will not use the C based scanner Here is the function: def py_make_scanner(context: Decoder) -> Callable[[str, int], tuple[Any, int]]: """ Make python based scanner For this use case we will not use the C based scanner """ parse_object = context.parse_object parse_array = context.parse_array parse_string = context.parse_string match_number = NUMBER_RE.match strict = context.strict parse_float = context.parse_float parse_int = context.parse_int parse_constant = context.parse_constant object_hook = context.object_hook object_pairs_hook = context.object_pairs_hook memo = context.memo # pylint: disable=R0911 # Based on Python standard function def _scan_once(string: str, idx: int) -> tuple[Any, int]: """ Scan once internal function """ try: nextchar = string[idx] except IndexError as err: raise StopIteration(idx) from err try: nextchar_plus_1 = string[idx + 1] except IndexError: nextchar_plus_1 = None try: nextchar_plus_2 = string[idx + 2] except IndexError: nextchar_plus_2 = None if nextchar == '"' and (nextchar_plus_1 != '"' or nextchar_plus_2 != '"'): return parse_string(string, idx + 1, strict) if nextchar == '"' and nextchar_plus_1 == '"' and nextchar_plus_2 == '"': result, end = parse_string(string, idx + 3, strict) return result, end + 2 if nextchar == '{': return parse_object( (string, idx + 1), strict, scan_once, object_hook, object_pairs_hook, memo) # type:ignore[arg-type] # mypy bug if nextchar == '[': return parse_array((string, idx + 1), _scan_once) if nextchar == 'n' and string[idx:idx + 4] == 'null': return None, idx + 4 if nextchar == 't' and string[idx:idx + 4] == 'true': return True, idx + 4 if nextchar == 'f' and string[idx:idx + 5] == 'false': return False, idx + 5 m = match_number(string, idx) if m is not None: integer, frac, exp = m.groups() if frac or exp: res = parse_float(integer + (frac or '') + (exp or '')) else: res = parse_int(integer) return res, m.end() if nextchar == 'N' and string[idx:idx + 3] == 'NaN': return parse_constant('NaN'), idx + 3 if nextchar == 'I' and string[idx:idx + 8] == 'Infinity': return parse_constant('Infinity'), idx + 8 if nextchar == '-' and string[idx:idx + 9] == '-Infinity': return parse_constant('-Infinity'), idx + 9 raise StopIteration(idx) def scan_once(string: str, idx: int) -> tuple[Any, int]: """ Scan Once""" try: return _scan_once(string, idx) finally: memo.clear() return _scan_once
Make python based scanner For this use case we will not use the C based scanner
2,303
from __future__ import annotations import logging from collections.abc import Sequence from json import JSONDecoder from json.decoder import WHITESPACE, WHITESPACE_STR, BACKSLASH, STRINGCHUNK, JSONArray from typing import Any, Callable, Pattern, Match from json.scanner import NUMBER_RE from checkov.common.parsers.node import StrNode, DictNode, ListNode from checkov.common.parsers.json.errors import NullError, DuplicateError, DecodeError The provided code snippet includes necessary dependencies for implementing the `find_indexes` function. Write a Python function `def find_indexes(s: str, ch: str = "\n") -> list[int]` to solve the following problem: Finds all instances of given char and returns list of indexes Here is the function: def find_indexes(s: str, ch: str = "\n") -> list[int]: """Finds all instances of given char and returns list of indexes """ return [i for i, ltr in enumerate(s) if ltr == ch]
Finds all instances of given char and returns list of indexes
2,304
from __future__ import annotations import logging from collections.abc import Sequence from json import JSONDecoder from json.decoder import WHITESPACE, WHITESPACE_STR, BACKSLASH, STRINGCHUNK, JSONArray from typing import Any, Callable, Pattern, Match from json.scanner import NUMBER_RE from checkov.common.parsers.node import StrNode, DictNode, ListNode from checkov.common.parsers.json.errors import NullError, DuplicateError, DecodeError class Mark: """Mark of line and column""" __slots__ = ("column", "line") def __init__(self, line: int, column: int) -> None: self.line = line self.column = column def count_occurrences(arr: Sequence[int], key: int) -> int: """Binary search indexes to replace str.count """ n = len(arr) left = 0 right = n - 1 count = 0 while (left <= right): mid = int((right + left) / 2) if (arr[mid] <= key): count = mid + 1 left = mid + 1 else: right = mid - 1 return count def largest_less_than(indexes: list[int], line_num: int, pos: int) -> int: """Replacement func for python str.rfind using indexes """ return indexes[line_num - 1] if indexes and count_occurrences(indexes, pos) else -1 The provided code snippet includes necessary dependencies for implementing the `get_beg_end_mark` function. Write a Python function `def get_beg_end_mark(s: str, start: int, end: int, indexes: list[int]) -> tuple[Mark, Mark]` to solve the following problem: Get the Start and End Mark Here is the function: def get_beg_end_mark(s: str, start: int, end: int, indexes: list[int]) -> tuple[Mark, Mark]: """Get the Start and End Mark """ beg_lineno = count_occurrences(indexes, start) beg_colno = start - largest_less_than(indexes, beg_lineno, start) beg_mark = Mark(beg_lineno, beg_colno) offset = 1 if len(indexes) > 1 else 0 end_lineno = count_occurrences(indexes, end) - offset end_colno = end - largest_less_than(indexes, end_lineno, end) end_mark = Mark(end_lineno, end_colno) return beg_mark, end_mark
Get the Start and End Mark
2,305
from __future__ import annotations import os from logging import Logger, Filter, LogRecord from checkov.common.util.type_forcers import convert_str_to_bool class ResourceCodeFilter(Filter): """ A custom logger filter designed to decide if we want to filter some logs from the default logger. Could be used to reduce logs size. First use case is to log without the actual code of resources, which takes a lot of the logs size. The default is to log everything in order to keep api the same. """ CODE_TEMPLATES: list[str] = [] def __init__(self, allow_code_logging: bool = True): super().__init__() self.allow_code_logging = allow_code_logging def filter(self, record: LogRecord) -> bool: if self.allow_code_logging: return True if hasattr(record, "mask"): # Allows filtering using `logging.info("<msg>", extra={"mask": True})` mask = record.mask if not isinstance(mask, bool): raise Exception(f"Expected to get `mask` as boolean for logging function, instead got: {mask} of type {type(mask)}") return not record.mask msg = record.msg return self._filter_based_on_msg(msg) def _filter_based_on_msg(self, msg: str) -> bool: for code_template in ResourceCodeFilter.CODE_TEMPLATES: if code_template in msg: return False return True def convert_str_to_bool(bool_str: bool | str) -> bool: if isinstance(bool_str, str): bool_str_lower = bool_str.lower() if bool_str_lower in ("true", '"true"'): return True elif bool_str_lower in ("false", '"false"'): return False # If we got here it must be a boolean, mypy doesn't understand it, so we use cast return typing.cast(bool, bool_str) def add_resource_code_filter_to_logger(logger: Logger, allow_code_logging: bool | None = None) -> None: if allow_code_logging is None: allow_code_logging_res = convert_str_to_bool(os.environ.get("CHECKOV_ALLOW_CODE_LOGGING", True)) if isinstance(allow_code_logging_res, bool): allow_code_logging = allow_code_logging_res else: raise Exception(f"Failed to get correct result for env variable - `CHECKOV_ALLOW_CODE_LOGGING`. " f"Got {allow_code_logging_res}") resource_code_filter = ResourceCodeFilter(allow_code_logging=allow_code_logging) logger.addFilter(resource_code_filter)
null
2,306
from __future__ import annotations from checkov.common.util.update_checker import UpdateChecker def check_for_update(package: str, version: str) -> str | None: try: checker = UpdateChecker() result = checker.check(package, version) if result is None: return None return result.available_version except Exception: # nosec return None
null
2,307
from __future__ import annotations import logging from typing import Dict, Any, List, Optional, Type, TYPE_CHECKING from checkov.common.checks_infra.solvers import ( EqualsAttributeSolver, NotEqualsAttributeSolver, RegexMatchAttributeSolver, NotRegexMatchAttributeSolver, ExistsAttributeSolver, AnyResourceSolver, ContainsAttributeSolver, NotExistsAttributeSolver, WithinAttributeSolver, NotContainsAttributeSolver, StartingWithAttributeSolver, NotStartingWithAttributeSolver, EndingWithAttributeSolver, NotEndingWithAttributeSolver, AndSolver, OrSolver, NotSolver, ConnectionExistsSolver, ConnectionNotExistsSolver, AndConnectionSolver, OrConnectionSolver, WithinFilterSolver, GreaterThanAttributeSolver, GreaterThanOrEqualAttributeSolver, LessThanAttributeSolver, LessThanOrEqualAttributeSolver, SubsetAttributeSolver, NotSubsetAttributeSolver, IsEmptyAttributeSolver, IsNotEmptyAttributeSolver, LengthEqualsAttributeSolver, LengthNotEqualsAttributeSolver, LengthGreaterThanAttributeSolver, LengthLessThanAttributeSolver, LengthLessThanOrEqualAttributeSolver, LengthGreaterThanOrEqualAttributeSolver, IsTrueAttributeSolver, IsFalseAttributeSolver, IntersectsAttributeSolver, NotIntersectsAttributeSolver, EqualsIgnoreCaseAttributeSolver, NotEqualsIgnoreCaseAttributeSolver, RangeIncludesAttributeSolver, RangeNotIncludesAttributeSolver, NumberOfWordsEqualsAttributeSolver, NumberOfWordsNotEqualsAttributeSolver, NumberOfWordsGreaterThanAttributeSolver, NumberOfWordsGreaterThanOrEqualAttributeSolver, NumberOfWordsLessThanAttributeSolver, NumberOfWordsLessThanOrEqualAttributeSolver, NotWithinAttributeSolver, ) from checkov.common.checks_infra.solvers.connections_solvers.connection_one_exists_solver import \ ConnectionOneExistsSolver from checkov.common.graph.checks_infra.base_check import BaseGraphCheck from checkov.common.graph.checks_infra.base_parser import BaseGraphCheckParser from checkov.common.graph.checks_infra.enums import SolverType from checkov.common.graph.checks_infra.solvers.base_solver import BaseSolver from checkov.common.util.type_forcers import force_list operators_to_complex_solver_classes: dict[str, Type[BaseComplexSolver]] = { "and": AndSolver, "or": OrSolver, "not": NotSolver, } def get_complex_operator(raw_check: Dict[str, Any]) -> Optional[str]: for operator in operators_to_complex_solver_classes.keys(): if raw_check.get(operator): return operator return None
null
2,308
from __future__ import annotations import json import logging import os from pathlib import Path from typing import Any, TYPE_CHECKING import yaml from checkov.common.checks_infra.checks_parser import GraphCheckParser from checkov.common.graph.checks_infra.base_parser import BaseGraphCheckParser from checkov.common.graph.checks_infra.registry import BaseRegistry from checkov.common.resource_code_logger_filter import add_resource_code_filter_to_logger from checkov.runner_filter import RunnerFilter from checkov.common.checks_infra.resources_types import resources_types class Registry(BaseRegistry): def __init__(self, checks_dir: str, parser: BaseGraphCheckParser | None = None) -> None: parser = parser or BaseGraphCheckParser() super().__init__(parser) self.checks: list[BaseGraphCheck] = [] self.checks_dir = checks_dir self.logger = logging.getLogger(__name__) add_resource_code_filter_to_logger(self.logger) def load_checks(self) -> None: if self.checks: # checks were previously loaded return self._load_checks_from_dir(self.checks_dir, False) def _load_checks_from_dir(self, directory: str, external_check: bool) -> None: dir = os.path.expanduser(directory) self.logger.debug(f"Loading external checks from {dir}") for root, d_names, f_names in os.walk(dir): self.logger.debug(f"Searching through {d_names} and {f_names}") for file in f_names: file_ending = os.path.splitext(file)[1] if file_ending in CHECKS_POSSIBLE_ENDING: with open(os.path.join(root, file), "r") as f: if dir != self.checks_dir: self.logger.info(f"loading {file}") if file_ending == ".json": check_json = json.load(f) else: check_yaml = yaml.safe_load(f) check_json = json.loads(json.dumps(check_yaml)) if not isinstance(check_json, dict): self.logger.error(f"Loaded data from JSON is not Dict. Skipping. Data: {check_json}.") continue if not self.parser.validate_check_config(file_path=f.name, raw_check=check_json): # proper log messages are generated inside the method continue check = self.parser.parse_raw_check( check_json, resources_types=self._get_resource_types(check_json), check_path=f'{root}/{file}' ) if not any(c for c in self.checks if check.id == c.id): if external_check: # Note the external check; used in the should_run_check logic RunnerFilter.notify_external_check(check.id) self.checks.append(check) def load_external_checks(self, dir: str) -> None: self._load_checks_from_dir(dir, True) def _get_resource_types(check_json: dict[str, dict[str, Any]]) -> list[str] | None: provider = check_json.get("scope", {}).get("provider", "").lower() return resources_types.get(provider) _registry_instances: dict[str, Registry] = {} class GraphCheckParser(BaseGraphCheckParser): def validate_check_config(self, file_path: str, raw_check: dict[str, dict[str, Any]]) -> bool: missing_fields = [] # check existence of metadata block if "metadata" in raw_check: metadata = raw_check["metadata"] if "id" not in metadata: missing_fields.append("metadata.id") if "name" not in metadata: missing_fields.append("metadata.name") if "category" not in metadata: missing_fields.append("metadata.category") else: missing_fields.extend(("metadata.id", "metadata.name", "metadata.category")) # check existence of definition block if "definition" not in raw_check: missing_fields.append("definition") if missing_fields: logging.warning(f"Custom policy {file_path} is missing required fields {', '.join(missing_fields)}") return False # check if definition block is not obviously invalid definition = raw_check["definition"] if not isinstance(definition, (list, dict)): logging.warning( f"Custom policy {file_path} has an invalid 'definition' block type '{type(definition).__name__}', " "needs to be either a 'list' or 'dict'" ) return False return True def parse_raw_check(self, raw_check: Dict[str, Dict[str, Any]], **kwargs: Any) -> BaseGraphCheck: providers = self._get_check_providers(raw_check) policy_definition = raw_check.get("definition", {}) check = self._parse_raw_check(policy_definition, kwargs.get("resources_types"), providers) check.id = raw_check.get("metadata", {}).get("id", "") check.name = raw_check.get("metadata", {}).get("name", "") check.category = raw_check.get("metadata", {}).get("category", "") check.frameworks = raw_check.get("metadata", {}).get("frameworks", []) check.guideline = raw_check.get("metadata", {}).get("guideline") check.check_path = kwargs.get("check_path", "") solver = self.get_check_solver(check) check.set_solver(solver) return check def _get_check_providers(raw_check: Dict[str, Any]) -> List[str]: providers = raw_check.get("scope", {}).get("provider", [""]) if isinstance(providers, list): return providers elif isinstance(providers, str): return [providers] else: return [""] def _parse_raw_check(self, raw_check: Dict[str, Any], resources_types: Optional[List[str]], providers: Optional[List[str]]) -> BaseGraphCheck: check = BaseGraphCheck() complex_operator = get_complex_operator(raw_check) if complex_operator: check.type = SolverType.COMPLEX check.operator = complex_operator sub_solvers = raw_check.get(complex_operator, []) # this allows flexibility for specifying the child conditions, and makes "not" more intuitive by # not requiring an actual list if isinstance(sub_solvers, dict): sub_solvers = [sub_solvers] for sub_solver in sub_solvers: check.sub_checks.append(self._parse_raw_check(sub_solver, resources_types, providers)) resources_types_of_sub_solvers = [ force_list(q.resource_types) for q in check.sub_checks if q is not None and q.resource_types is not None ] check.resource_types = list(set(sum(resources_types_of_sub_solvers, []))) if any(q.type in [SolverType.CONNECTION, SolverType.COMPLEX_CONNECTION] for q in check.sub_checks): check.type = SolverType.COMPLEX_CONNECTION else: resource_type = raw_check.get("resource_types", []) if ( not resource_type or (isinstance(resource_type, str) and resource_type.lower() == "all") or (isinstance(resource_type, list) and resource_type[0].lower() == "all") ): check.resource_types = resources_types or [] elif "provider" in resource_type and providers: for provider in providers: check.resource_types.append(f"provider.{provider.lower()}") elif isinstance(resource_type, str): # for the case the "resource_types" value is a string, which can result in a silent exception check.resource_types = [resource_type] else: check.resource_types = resource_type connected_resources_type = raw_check.get("connected_resource_types", []) if connected_resources_type == ["All"] or connected_resources_type == "all": check.connected_resources_types = resources_types or [] else: check.connected_resources_types = connected_resources_type condition_type = raw_check.get("cond_type", "") check.type = condition_type_to_solver_type.get(condition_type) if condition_type == "": check.operator = "any" else: check.operator = raw_check.get("operator", "") check.attribute = raw_check.get("attribute") check.attribute_value = raw_check.get("value") return check def get_solver_type_method(check: BaseGraphCheck) -> Optional[BaseAttributeSolver]: check.is_jsonpath_check = check.operator.startswith(JSONPATH_PREFIX) if check.is_jsonpath_check: solver = check.operator.replace(JSONPATH_PREFIX, '') else: solver = check.operator return operators_to_attributes_solver_classes.get(solver, lambda *args: None)( check.resource_types, check.attribute, check.attribute_value, check.is_jsonpath_check ) def get_check_solver(self, check: BaseGraphCheck) -> BaseSolver: sub_solvers: List[BaseSolver] = [] if check.sub_checks: sub_solvers = [] for sub_solver in check.sub_checks: sub_solvers.append(self.get_check_solver(sub_solver)) type_to_solver = { SolverType.COMPLEX_CONNECTION: operator_to_complex_connection_solver_classes.get( check.operator, lambda *args: None )(sub_solvers, check.operator), SolverType.COMPLEX: operators_to_complex_solver_classes.get(check.operator, lambda *args: None)( sub_solvers, check.resource_types ), SolverType.ATTRIBUTE: self.get_solver_type_method(check), SolverType.CONNECTION: operator_to_connection_solver_classes.get(check.operator, lambda *args: None)( check.resource_types, check.connected_resources_types ), SolverType.FILTER: operator_to_filter_solver_classes.get(check.operator, lambda *args: None)( check.resource_types, check.attribute, check.attribute_value ), } solver = type_to_solver.get(check.type) # type:ignore[arg-type] # if not str will return None if not solver: raise NotImplementedError(f"solver type {check.type} with operator {check.operator} is not supported") return solver def get_graph_checks_registry(check_type: str) -> Registry: if not _registry_instances.get(check_type): _registry_instances[check_type] = Registry( parser=GraphCheckParser(), checks_dir=f"{Path(__file__).parent.parent.parent}/{check_type}/checks/graph_checks", ) return _registry_instances[check_type]
null
2,309
from __future__ import annotations import argparse import itertools import json import logging import os import re import platform import sys import time from collections import defaultdict from collections.abc import Iterable from io import StringIO from pathlib import Path from typing import List, Dict, Any, Optional, cast, TYPE_CHECKING, Type, Literal from checkov.common.bridgecrew.check_type import CheckType from checkov.common.bridgecrew.code_categories import CodeCategoryMapping, CodeCategoryType from checkov.common.bridgecrew.platform_integration import bc_integration from checkov.common.bridgecrew.integration_features.features.policy_metadata_integration import \ integration as metadata_integration from checkov.common.bridgecrew.integration_features.features.repo_config_integration import \ integration as repo_config_integration from checkov.common.bridgecrew.integration_features.features.licensing_integration import \ integration as licensing_integration from checkov.common.bridgecrew.integration_features.integration_feature_registry import integration_feature_registry from checkov.common.bridgecrew.platform_errors import ModuleNotEnabledError from checkov.common.bridgecrew.severities import Severities from checkov.common.images.image_referencer import ImageReferencer from checkov.common.logger_streams import logger_streams from checkov.common.models.enums import ErrorStatus, ParallelizationType from checkov.common.output.csv import CSVSBOM from checkov.common.output.cyclonedx import CycloneDX from checkov.common.output.gitlab_sast import GitLabSast from checkov.common.output.report import Report, merge_reports from checkov.common.output.sarif import Sarif from checkov.common.output.spdx import SPDX from checkov.common.parallelizer.parallel_runner import parallel_runner from checkov.common.resource_code_logger_filter import add_resource_code_filter_to_logger from checkov.common.sast.consts import CDKLanguages from checkov.common.typing import _ExitCodeThresholds, _BaseRunner, _ScaExitCodeThresholds, LibraryGraph from checkov.common.util import data_structures_utils from checkov.common.util.banner import tool as tool_name from checkov.common.util.consts import S3_UPLOAD_DETAILS_MESSAGE from checkov.common.util.data_structures_utils import pickle_deepcopy from checkov.common.util.json_utils import CustomJSONEncoder from checkov.common.util.secrets_omitter import SecretsOmitter from checkov.common.util.type_forcers import convert_csv_string_arg_to_list, force_list from checkov.logging_init import log_stream, erase_log_stream from checkov.sca_image.runner import Runner as image_runner from checkov.common.secrets.consts import SECRET_VALIDATION_STATUSES from checkov.terraform.context_parsers.registry import parser_registry from checkov.terraform.tf_parser import TFParser class RunnerRegistry: def __init__( self, banner: str, runner_filter: RunnerFilter, *runners: _BaseRunner, tool: str = tool_name, secrets_omitter_class: Type[SecretsOmitter] = SecretsOmitter, ) -> None: self.logger = logging.getLogger(__name__) add_resource_code_filter_to_logger(self.logger) self.runner_filter = runner_filter self.runners = list(runners) self.banner = banner self.sca_supported_ir_report: Optional[Report] = None self.scan_reports: list[Report] = [] self.image_referencing_runners = self._get_image_referencing_runners() self.filter_runner_framework() self.tool = tool self._check_type_to_report_map: dict[str, Report] = {} # used for finding reports with the same check type self.licensing_integration = licensing_integration # can be maniuplated by unit tests self.secrets_omitter_class = secrets_omitter_class self.check_type_to_graph: dict[str, list[tuple[LibraryGraph, Optional[str]]]] = {} self.check_type_to_resource_subgraph_map: dict[str, dict[str, str]] = {} for runner in runners: if isinstance(runner, image_runner): runner.image_referencers = self.image_referencing_runners def run( self, root_folder: Optional[str] = None, external_checks_dir: Optional[List[str]] = None, files: Optional[List[str]] = None, collect_skip_comments: bool = True, repo_root_for_plan_enrichment: list[str | Path] | None = None, ) -> list[Report]: if not self.runners: logging.error('There are no runners to run. This can happen if you specify a file type and a framework that are not compatible ' '(e.g., `--file xyz.yaml --framework terraform`), or if you specify a framework with missing dependencies (e.g., ' 'helm or kustomize, which require those tools to be on your system). Running with LOG_LEVEL=DEBUG may provide more information.') return [] elif len(self.runners) == 1: runner_check_type = self.runners[0].check_type if self.licensing_integration.is_runner_valid(runner_check_type): reports: Iterable[Report | list[Report]] = [ self.runners[0].run(root_folder, external_checks_dir=external_checks_dir, files=files, runner_filter=self.runner_filter, collect_skip_comments=collect_skip_comments)] else: # This is the only runner, so raise a clear indication of failure raise ModuleNotEnabledError(f'The framework "{runner_check_type}" is part of the "{self.licensing_integration.get_subscription_for_runner(runner_check_type).name}" module, which is not enabled in the platform') else: valid_runners = [] invalid_runners = [] platform_integration_data = None if parallel_runner.type == ParallelizationType.SPAWN: platform_integration_data = bc_integration.generate_instance_data() for runner in self.runners: if self.licensing_integration.is_runner_valid(runner.check_type): valid_runners.append( (runner, root_folder, external_checks_dir, files, self.runner_filter, collect_skip_comments, platform_integration_data) ) else: invalid_runners.append(runner) # if all runners are disabled (most likely to occur if the user specified --framework for only disabled runners) # then raise a clear error # if some frameworks are disabled and the user used --framework, log a warning so they see it # if some frameworks are disabled and the user did not use --framework, then log at a lower level so that we have it for troubleshooting if not valid_runners: runners_categories = os.linesep.join([f'{runner.check_type}: {self.licensing_integration.get_subscription_for_runner(runner.check_type).name}' for runner in invalid_runners]) error_message = f'All the frameworks are disabled because they are not enabled in the platform. ' \ f'You must subscribe to one or more of the categories below to get results for these frameworks.{os.linesep}{runners_categories}' logging.error(error_message) raise ModuleNotEnabledError(error_message) elif invalid_runners: for runner in invalid_runners: level = logging.INFO if runner.check_type in self.runner_filter.framework_flag_values: level = logging.WARNING logging.log(level, f'The framework "{runner.check_type}" is part of the "{self.licensing_integration.get_subscription_for_runner(runner.check_type).name}" module, which is not enabled in the platform') valid_runners = self._merge_runners(valid_runners) parallel_runner_results = parallel_runner.run_function( func=_parallel_run, items=valid_runners, group_size=1, ) reports = [] full_check_type_to_graph = {} full_check_type_to_resource_subgraph_map = {} for result in parallel_runner_results: if result is not None: report, check_type, graphs, resource_subgraph_map, subprocess_log_stream = result reports.append(report) if subprocess_log_stream is not None: # only sub processes need to add their logs streams, # the logs of all others methods already exists in the main stream if parallel_runner.running_as_process(): logger_streams.add_stream(f'{check_type or time.time()}', subprocess_log_stream) if check_type is not None: if graphs is not None: full_check_type_to_graph[check_type] = graphs if resource_subgraph_map is not None: full_check_type_to_resource_subgraph_map[check_type] = resource_subgraph_map self.check_type_to_graph = full_check_type_to_graph self.check_type_to_resource_subgraph_map = full_check_type_to_resource_subgraph_map merged_reports = self._merge_reports(reports) if bc_integration.bc_api_key: self.secrets_omitter_class(merged_reports).omit() post_scan_reports = integration_feature_registry.run_post_scan(merged_reports) if post_scan_reports: merged_reports.extend(post_scan_reports) for scan_report in merged_reports: self._handle_report(scan_report, repo_root_for_plan_enrichment) if not self.check_type_to_graph: self.check_type_to_graph = {runner.check_type: self.extract_graphs_from_runner(runner) for runner in self.runners if runner.graph_manager} if not self.check_type_to_resource_subgraph_map: self.check_type_to_resource_subgraph_map = {runner.check_type: runner.resource_subgraph_map for runner in self.runners if runner.resource_subgraph_map is not None} return self.scan_reports def _merge_runners(self, runners: Any) -> list[_BaseRunner]: sast_runner = None cdk_runner = None merged_runners = [] for runner in runners: if runner[0].check_type == CheckType.CDK: cdk_runner = runner continue if runner[0].check_type == CheckType.SAST: merged_runners.append(runner) sast_runner = runner continue merged_runners.append(runner) if cdk_runner: if sast_runner: for lang in CDKLanguages.set(): sast_runner[0].cdk_langs.append(lang) else: merged_runners.append(cdk_runner) return merged_runners def _merge_reports(self, reports: Iterable[Report | list[Report]]) -> list[Report]: """Merges reports with the same check_type""" merged_reports = [] for report in reports: if report is None: # this only happens, when an uncaught exception occurs continue sub_reports: list[Report] = force_list(report) for sub_report in sub_reports: if sub_report.check_type in self._check_type_to_report_map: merge_reports(self._check_type_to_report_map[sub_report.check_type], sub_report) else: self._check_type_to_report_map[sub_report.check_type] = sub_report merged_reports.append(sub_report) if self.should_add_sca_results_to_sca_supported_ir_report(sub_report, sub_reports): if self.sca_supported_ir_report: merge_reports(self.sca_supported_ir_report, sub_report) else: self.sca_supported_ir_report = pickle_deepcopy(sub_report) return merged_reports def should_add_sca_results_to_sca_supported_ir_report(sub_report: Report, sub_reports: list[Report]) -> bool: if sub_report.check_type == 'sca_image' and bc_integration.customer_run_config_response: # The regular sca report if len(sub_reports) == 1: return True # Dup report: first - regular iac, second - IR. we are checking that report fw is in the IR supported list. if len(sub_reports) == 2 and sub_reports[0].check_type in bc_integration.customer_run_config_response.get('supportedIrFw', []): return True return False def _handle_report(self, scan_report: Report, repo_root_for_plan_enrichment: list[str | Path] | None) -> None: integration_feature_registry.run_post_runner(scan_report) if metadata_integration.check_metadata: RunnerRegistry.enrich_report_with_guidelines(scan_report) if repo_root_for_plan_enrichment and not self.runner_filter.deep_analysis: enriched_resources = RunnerRegistry.get_enriched_resources( repo_roots=repo_root_for_plan_enrichment, download_external_modules=self.runner_filter.download_external_modules, ) scan_report = Report("terraform_plan").enrich_plan_report(scan_report, enriched_resources) scan_report = Report("terraform_plan").handle_skipped_checks(scan_report, enriched_resources) self.scan_reports.append(scan_report) def save_output_to_file(self, file_name: str, data: str, data_format: str) -> None: try: file_path = Path(file_name) file_path.parent.mkdir(parents=True, exist_ok=True) file_path.write_text(data) logging.info(f"\nWrote output in {data_format} format to the file '{file_name}')") except EnvironmentError: logging.error(f"\nAn error occurred while writing {data_format} results to file: {file_name}", exc_info=True) def is_error_in_reports(reports: List[Report]) -> bool: return any(scan_report.error_status != ErrorStatus.SUCCESS for scan_report in reports) def get_fail_thresholds(config: argparse.Namespace, report_type: str) -> _ExitCodeThresholds | _ScaExitCodeThresholds: soft_fail = config.soft_fail soft_fail_on_checks = [] soft_fail_threshold = None # these specifically check the --hard-fail-on and --soft-fail-on args, NOT enforcement rules, so # we don't care about SCA as a special case # soft fail on the highest severity threshold in the list for val in convert_csv_string_arg_to_list(config.soft_fail_on): if val.upper() in Severities: val = val.upper() if not soft_fail_threshold or Severities[val].level > soft_fail_threshold.level: soft_fail_threshold = Severities[val] elif val.capitalize() in SECRET_VALIDATION_STATUSES: soft_fail_on_checks.append(val.capitalize()) else: soft_fail_on_checks.append(val) logging.debug(f'Soft fail severity threshold: {soft_fail_threshold.level if soft_fail_threshold else None}') logging.debug(f'Soft fail checks: {soft_fail_on_checks}') hard_fail_on_checks = [] hard_fail_threshold = None # hard fail on the lowest threshold in the list for val in convert_csv_string_arg_to_list(config.hard_fail_on): if val.upper() in Severities: val = val.upper() if not hard_fail_threshold or Severities[val].level < hard_fail_threshold.level: hard_fail_threshold = Severities[val] elif val.capitalize() in SECRET_VALIDATION_STATUSES: hard_fail_on_checks.append(val.capitalize()) else: hard_fail_on_checks.append(val) logging.debug(f'Hard fail severity threshold: {hard_fail_threshold.level if hard_fail_threshold else None}') logging.debug(f'Hard fail checks: {hard_fail_on_checks}') if not config.use_enforcement_rules: logging.debug('Use enforcement rules is FALSE') # if there is a severity in either the soft-fail-on list or hard-fail-on list, then we will ignore enforcement rules and skip this # it means that SCA will not be treated as having two different thresholds in that case # if the lists only contain check IDs, then we will merge them with the enforcement rule value elif not soft_fail and not soft_fail_threshold and not hard_fail_threshold: if 'sca_' in report_type: code_category_types = cast(List[CodeCategoryType], CodeCategoryMapping[report_type]) category_rules = { category: repo_config_integration.code_category_configs[category] for category in code_category_types } return cast(_ScaExitCodeThresholds, { category: { 'soft_fail': category_rules[category].is_global_soft_fail(), 'soft_fail_checks': soft_fail_on_checks, 'soft_fail_threshold': soft_fail_threshold, 'hard_fail_checks': hard_fail_on_checks, 'hard_fail_threshold': category_rules[category].hard_fail_threshold } for category in code_category_types }) else: code_category_type = cast(CodeCategoryType, CodeCategoryMapping[report_type]) # not a list enf_rule = repo_config_integration.code_category_configs[code_category_type] if enf_rule: logging.debug('Use enforcement rules is TRUE') hard_fail_threshold = enf_rule.hard_fail_threshold soft_fail = enf_rule.is_global_soft_fail() logging.debug(f'Using enforcement rule hard fail threshold for this report: {hard_fail_threshold.name}') else: logging.debug(f'Use enforcement rules is TRUE, but did not find an enforcement rule for report type {report_type}, so falling back to CLI args') else: logging.debug('Soft fail was true or a severity was used in soft fail on / hard fail on; ignoring enforcement rules') return { 'soft_fail': soft_fail, 'soft_fail_checks': soft_fail_on_checks, 'soft_fail_threshold': soft_fail_threshold, 'hard_fail_checks': hard_fail_on_checks, 'hard_fail_threshold': hard_fail_threshold } def print_reports( self, scan_reports: List[Report], config: argparse.Namespace, url: Optional[str] = None, created_baseline_path: Optional[str] = None, baseline: Optional[Baseline] = None, ) -> Literal[0, 1]: output_formats: "dict[str, str]" = {} if config.output_file_path and "," in config.output_file_path: output_paths = config.output_file_path.split(",") for idx, output_format in enumerate(config.output): output_formats[output_format] = output_paths[idx] else: output_formats = {output_format: CONSOLE_OUTPUT for output_format in config.output} exit_codes = [] cli_reports = [] report_jsons = [] sarif_reports = [] junit_reports = [] github_reports = [] cyclonedx_reports = [] gitlab_reports = [] spdx_reports = [] csv_sbom_report = CSVSBOM() try: if config.skip_resources_without_violations: for report in scan_reports: report.extra_resources = set() except AttributeError: # config attribute wasn't set, defaults to False and print extra resources to report pass data_outputs: dict[str, str] = defaultdict(str) for report in scan_reports: if not report.is_empty(): if "json" in config.output: report_jsons.append(report.get_dict(is_quiet=config.quiet, url=url, s3_setup_failed=bc_integration.s3_setup_failed, support_path=bc_integration.support_repo_path)) if "junitxml" in config.output: junit_reports.append(report) if "github_failed_only" in config.output: github_reports.append(report.print_failed_github_md(use_bc_ids=config.output_bc_ids)) if "sarif" in config.output: sarif_reports.append(report) if "cli" in config.output: cli_reports.append(report) if "gitlab_sast" in config.output: gitlab_reports.append(report) if not report.is_empty() or len(report.extra_resources): if any(cyclonedx in config.output for cyclonedx in CYCLONEDX_OUTPUTS): cyclonedx_reports.append(report) if "spdx" in config.output: spdx_reports.append(report) if "csv" in config.output: git_org = "" git_repository = "" if 'repo_id' in config and config.repo_id is not None: git_org, git_repository = config.repo_id.split('/') csv_sbom_report.add_report(report=report, git_org=git_org, git_repository=git_repository) logging.debug(f'Getting exit code for report {report.check_type}') exit_code_thresholds = self.get_fail_thresholds(config, report.check_type) exit_codes.append(report.get_exit_code(exit_code_thresholds)) if "github_failed_only" in config.output: github_output = "".join(github_reports) self._print_to_console( output_formats=output_formats, output_format="github_failed_only", output=github_output, ) data_outputs["github_failed_only"] = github_output if "cli" in config.output: if not config.quiet: print(f"{self.banner}\n") cli_output = '' if (bc_integration.runtime_run_config_response and bc_integration.runtime_run_config_response.get('isRepoInRuntime', False)): cli_output += f"The '{bc_integration.repo_id}' repository was discovered In a running environment\n\n" if len(cli_reports) > 0: cli_output += cli_reports[0].add_errors_to_output() for report in cli_reports: cli_output += report.print_console( is_quiet=config.quiet, is_compact=config.compact, created_baseline_path=created_baseline_path, baseline=baseline, use_bc_ids=config.output_bc_ids, summary_position=config.summary_position, openai_api_key=config.openai_api_key, ) self._print_to_console( output_formats=output_formats, output_format="cli", output=cli_output, url=url, support_path=bc_integration.support_repo_path ) # Remove colors from the cli output ansi_escape = re.compile(r'(?:\x1B[@-_]|[\x80-\x9F])[0–9:;<=>?]*[ -/]*[@-~]') data_outputs['cli'] = ansi_escape.sub('', cli_output) if "sarif" in config.output: sarif = Sarif(reports=sarif_reports, tool=self.tool) output_format = output_formats["sarif"] if "cli" not in config.output and output_format == CONSOLE_OUTPUT: print(self.banner) for report in sarif_reports: if "cli" not in config.output and output_format == CONSOLE_OUTPUT: print(report.print_console( is_quiet=config.quiet, is_compact=config.compact, created_baseline_path=created_baseline_path, baseline=baseline, use_bc_ids=config.output_bc_ids, summary_position=config.summary_position )) if output_format == CONSOLE_OUTPUT: if not config.output_file_path or "," in config.output_file_path: # don't write to file, if an explicit file path was set sarif.write_sarif_output() del output_formats["sarif"] if "cli" not in config.output: if url: print(f"More details: {url}") elif bc_integration.s3_setup_failed: print(S3_UPLOAD_DETAILS_MESSAGE) if bc_integration.support_repo_path: print(f"\nPath for uploaded logs (give this to support if raising an issue): {bc_integration.support_repo_path}") if CONSOLE_OUTPUT in output_formats.values(): print(OUTPUT_DELIMITER) data_outputs["sarif"] = json.dumps(sarif.json, cls=CustomJSONEncoder) if "json" in config.output: if config.compact and report_jsons: self.strip_code_blocks_from_json(report_jsons) report_json_output: "list[dict[str, Any]] | dict[str, Any]" = report_jsons if not report_jsons: report_json_output = Report("").get_summary() elif len(report_jsons) == 1: report_json_output = report_jsons[0] json_output = json.dumps(report_json_output, indent=4, cls=CustomJSONEncoder) self._print_to_console( output_formats=output_formats, output_format="json", output=json_output, ) data_outputs["json"] = json.dumps(report_json_output, cls=CustomJSONEncoder) if "junitxml" in config.output: properties = Report.create_test_suite_properties_block(config) if junit_reports: test_suites = [ report.get_test_suite(properties=properties, use_bc_ids=config.output_bc_ids) for report in junit_reports ] else: test_suites = [Report("").get_test_suite(properties=properties)] junit_output = Report.get_junit_xml_string(test_suites) self._print_to_console( output_formats=output_formats, output_format="junitxml", output=junit_output, ) data_outputs['junitxml'] = junit_output if any(cyclonedx in config.output for cyclonedx in CYCLONEDX_OUTPUTS): cyclonedx = CycloneDX(repo_id=metadata_integration.bc_integration.repo_id, reports=cyclonedx_reports) for cyclonedx_format in CYCLONEDX_OUTPUTS: if cyclonedx_format not in config.output: # only the XML or JSON format was chosen continue if cyclonedx_format == "cyclonedx": cyclonedx_output = cyclonedx.get_xml_output() elif cyclonedx_format == "cyclonedx_json": cyclonedx_output = cyclonedx.get_json_output() else: # this shouldn't happen logging.error(f"CycloneDX output format '{cyclonedx_format}' not supported") continue self._print_to_console( output_formats=output_formats, output_format=cyclonedx_format, output=cyclonedx_output, ) data_outputs[cyclonedx_format] = cyclonedx_output if "gitlab_sast" in config.output: gl_sast = GitLabSast(reports=gitlab_reports) self._print_to_console( output_formats=output_formats, output_format="gitlab_sast", output=json.dumps(gl_sast.sast_json, indent=4), ) data_outputs["gitlab_sast"] = json.dumps(gl_sast.sast_json) if "spdx" in config.output: spdx = SPDX(repo_id=metadata_integration.bc_integration.repo_id, reports=spdx_reports) spdx_output = spdx.get_tag_value_output() self._print_to_console( output_formats=output_formats, output_format="spdx", output=spdx_output, ) data_outputs["spdx"] = spdx_output if "csv" in config.output: is_api_key = False if 'bc_api_key' in config and config.bc_api_key is not None: is_api_key = True csv_sbom_report.persist_report(is_api_key=is_api_key, output_path=config.output_file_path) # Save output to file file_names = { 'cli': 'results_cli.txt', 'github_failed_only': 'results_github_failed_only.md', 'sarif': 'results_sarif.sarif', 'json': 'results_json.json', 'junitxml': 'results_junitxml.xml', 'cyclonedx': 'results_cyclonedx.xml', 'cyclonedx_json': 'results_cyclonedx.json', 'gitlab_sast': 'results_gitlab_sast.json', 'spdx': 'results_spdx.spdx', } if config.output_file_path: if output_formats: for output_format, output_path in output_formats.items(): self.save_output_to_file( file_name=output_path, data=data_outputs[output_format], data_format=output_format, ) else: for output in config.output: if output in file_names: self.save_output_to_file( file_name=f'{config.output_file_path}/{file_names[output]}', data=data_outputs[output], data_format=output, ) exit_code = 1 if 1 in exit_codes else 0 return cast(Literal[0, 1], exit_code) def _print_to_console(self, output_formats: dict[str, str], output_format: str, output: str, url: str | None = None, support_path: str | None = None) -> None: """Prints the output to console, if needed""" output_dest = output_formats[output_format] if output_dest == CONSOLE_OUTPUT: del output_formats[output_format] if platform.system() == 'Windows': sys.stdout.buffer.write(output.encode("utf-8")) else: print(output) if url: print(f"More details: {url}") elif bc_integration.s3_setup_failed: print(S3_UPLOAD_DETAILS_MESSAGE) if support_path: print(f"\nPath for uploaded logs (give this to support if raising an issue): {support_path}") if CONSOLE_OUTPUT in output_formats.values(): print(OUTPUT_DELIMITER) def print_iac_bom_reports(self, output_path: str, scan_reports: list[Report], output_types: list[str], account_id: str) -> dict[str, str]: output_files = { 'cyclonedx': 'results_cyclonedx.xml', 'csv': 'results_iac.csv' } # create cyclonedx report if 'cyclonedx' in output_types: cyclonedx_output_path = output_files['cyclonedx'] cyclonedx = CycloneDX(reports=scan_reports, repo_id=metadata_integration.bc_integration.repo_id, export_iac_only=True) cyclonedx_output = cyclonedx.get_xml_output() self.save_output_to_file(file_name=os.path.join(output_path, cyclonedx_output_path), data=cyclonedx_output, data_format="cyclonedx") # create csv report if 'csv' in output_types: csv_sbom_report = CSVSBOM() for report in scan_reports: if not report.is_empty(): git_org, git_repository = self.extract_git_info_from_account_id(account_id) csv_sbom_report.add_report(report=report, git_org=git_org, git_repository=git_repository) csv_sbom_report.persist_report_iac(file_name=output_files['csv'], output_path=output_path) return {key: os.path.join(output_path, value) for key, value in output_files.items()} def filter_runner_framework(self) -> None: if not self.runner_filter: return if not self.runner_filter.framework: return if "all" in self.runner_filter.framework: return self.runners = [runner for runner in self.runners if runner.check_type in self.runner_filter.framework] def filter_runners_for_files(self, files: List[str]) -> None: if not files: return self.runners = [runner for runner in self.runners if any(runner.should_scan_file(file) for file in files)] logging.debug(f'Filtered runners based on file type(s). Result: {[r.check_type for r in self.runners]}') def remove_runner(self, runner: _BaseRunner) -> None: if runner in self.runners: self.runners.remove(runner) def enrich_report_with_guidelines(scan_report: Report) -> None: for record in itertools.chain(scan_report.failed_checks, scan_report.passed_checks, scan_report.skipped_checks): guideline = metadata_integration.get_guideline(record.check_id) if guideline: record.set_guideline(guideline) def get_enriched_resources( repo_roots: list[str | Path], download_external_modules: bool ) -> dict[str, dict[str, Any]]: from checkov.terraform.modules.module_objects import TFDefinitionKey repo_definitions = {} for repo_root in repo_roots: parsing_errors: dict[str, Exception] = {} repo_root = os.path.abspath(repo_root) tf_definitions: dict[TFDefinitionKey, dict[str, list[dict[str, Any]]]] = TFParser().parse_directory( directory=repo_root, # assume plan file is in the repo-root out_parsing_errors=parsing_errors, download_external_modules=download_external_modules, ) repo_definitions[repo_root] = {'tf_definitions': tf_definitions, 'parsing_errors': parsing_errors} enriched_resources = {} for repo_root, parse_results in repo_definitions.items(): definitions = cast("dict[TFDefinitionKey, dict[str, list[dict[str, Any]]]]", parse_results['tf_definitions']) for full_file_path, definition in definitions.items(): definitions_context = parser_registry.enrich_definitions_context((full_file_path, definition)) abs_scanned_file = full_file_path.file_path scanned_file = os.path.relpath(abs_scanned_file, repo_root) for block_type, block_value in definition.items(): if block_type in CHECK_BLOCK_TYPES: for entity in block_value: context_parser = parser_registry.context_parsers[block_type] definition_path = context_parser.get_entity_context_path(entity) entity_id = ".".join(definition_path) entity_context_path = [block_type] + definition_path entity_context = data_structures_utils.get_inner_dict( definitions_context[full_file_path], entity_context_path ) entity_lines_range = [ entity_context.get("start_line"), entity_context.get("end_line"), ] entity_code_lines = entity_context.get("code_lines") skipped_checks = entity_context.get("skipped_checks") enriched_resources[entity_id] = { "entity_code_lines": entity_code_lines, "entity_lines_range": entity_lines_range, "scanned_file": scanned_file, "skipped_checks": skipped_checks, } return enriched_resources def _get_image_referencing_runners(self) -> set[ImageReferencer]: image_referencing_runners: set[ImageReferencer] = set() for runner in self.runners: if issubclass(runner.__class__, ImageReferencer): image_referencing_runners.add(cast(ImageReferencer, runner)) return image_referencing_runners def strip_code_blocks_from_json(report_jsons: List[Dict[str, Any]]) -> None: for report in report_jsons: results = report.get('results', {}) for result in results.values(): for result_dict in result: if isinstance(result_dict, dict): result_dict["code_block"] = None result_dict["connected_node"] = None def extract_git_info_from_account_id(account_id: str) -> tuple[str, str]: if '/' in account_id: account_id_list = account_id.split('/') git_org = '/'.join(account_id_list[0:-1]) git_repository = account_id_list[-1] else: git_org, git_repository = "", "" return git_org, git_repository def extract_graphs_from_runner(runner: _BaseRunner) -> list[tuple[LibraryGraph, Optional[str]]]: # exist only for terraform all_graphs = getattr(runner, 'all_graphs', None) if all_graphs: return all_graphs # type:ignore[no-any-return] elif runner.graph_manager: return [(runner.graph_manager.get_reader_endpoint(), None)] return [] bc_integration = BcPlatformIntegration() class Report: def __init__(self, check_type: str): self.check_type = check_type self.passed_checks: list[Record] = [] self.failed_checks: list[Record] = [] self.skipped_checks: list[Record] = [] self.parsing_errors: list[str] = [] self.resources: set[str] = set() self.extra_resources: set[ExtraResource] = set() self.image_cached_results: List[dict[str, Any]] = [] self.error_status: ErrorStatus = ErrorStatus.SUCCESS def errors(self) -> Dict[str, List[str]]: return dict() def set_error_status(self, error_status: ErrorStatus) -> None: self.error_status = error_status def add_parsing_errors(self, errors: "Iterable[str]") -> None: for file in errors: self.add_parsing_error(file) def add_parsing_error(self, file: str) -> None: if file: self.parsing_errors.append(file) def add_resource(self, resource: str) -> None: self.resources.add(resource) def add_record(self, record: Record) -> None: if record.check_result["result"] == CheckResult.PASSED: self.passed_checks.append(record) if record.check_result["result"] == CheckResult.FAILED: self.failed_checks.append(record) if record.check_result["result"] == CheckResult.SKIPPED: self.skipped_checks.append(record) def get_summary(self) -> Dict[str, Union[int, str]]: return { "passed": len(self.passed_checks), "failed": len(self.failed_checks), "skipped": len(self.skipped_checks), "parsing_errors": len(self.parsing_errors), "resource_count": len(self.resources), "checkov_version": version, } def get_json(self) -> str: return json.dumps(self.get_dict(), indent=4, cls=CustomJSONEncoder) def get_all_records(self) -> List[Record]: return self.failed_checks + self.passed_checks + self.skipped_checks def get_dict(self, is_quiet: bool = False, url: str | None = None, full_report: bool = False, s3_setup_failed: bool = False, support_path: str | None = None) -> dict[str, Any]: if not url and not s3_setup_failed: url = "Add an api key '--bc-api-key <api-key>' to see more detailed insights via https://bridgecrew.cloud" elif s3_setup_failed: url = S3_UPLOAD_DETAILS_MESSAGE if is_quiet: return { "check_type": self.check_type, "results": { "failed_checks": [check.__dict__ for check in self.failed_checks] }, "summary": self.get_summary(), } if full_report: return { "check_type": self.check_type, "checks": { "passed_checks": [check.__dict__ for check in self.passed_checks], "failed_checks": [check.__dict__ for check in self.failed_checks], "skipped_checks": [check.__dict__ for check in self.skipped_checks] }, "image_cached_results": [res.__dict__ for res in self.image_cached_results] } else: result = { "check_type": self.check_type, "results": { "passed_checks": [check.__dict__ for check in self.passed_checks], "failed_checks": [check.__dict__ for check in self.failed_checks], "skipped_checks": [check.__dict__ for check in self.skipped_checks], "parsing_errors": list(self.parsing_errors), }, "summary": self.get_summary(), "url": url, } if support_path: result["support_path"] = support_path return result def get_exit_code(self, exit_code_thresholds: Union[_ExitCodeThresholds, _ScaExitCodeThresholds]) -> int: """ Returns the appropriate exit code depending on the flags that are passed in. :return: Exit code 0 or 1. """ hard_fail_on_parsing_errors = os.getenv(PARSE_ERROR_FAIL_FLAG, "false").lower() == 'true' logging.debug(f'In get_exit_code; exit code thresholds: {exit_code_thresholds}, hard_fail_on_parsing_errors: {hard_fail_on_parsing_errors}') if self.parsing_errors and hard_fail_on_parsing_errors: logging.debug('hard_fail_on_parsing_errors is True and there were parsing errors - returning 1') return 1 if not self.failed_checks: logging.debug('No failed checks in this report - returning 0') return 0 # we will have two different sets of logic in this method, determined by this variable. # if we are using enforcement rules, then there are two different sets of thresholds that apply for licenses and vulnerabilities # and we have to handle that throughout while processing the report # if we are not using enforcement rules, then we can combine licenses and vulnerabilities like normal and same as all other report types # this determination is made in runner_registry.get_fail_thresholds has_split_enforcement = CodeCategoryType.LICENSES in exit_code_thresholds hard_fail_threshold: Optional[Severity | Dict[str, Severity]] soft_fail: Optional[bool | Dict[str, bool]] if has_split_enforcement: sca_thresholds = cast(_ScaExitCodeThresholds, exit_code_thresholds) # these three are the same even in split enforcement rules generic_thresholds = cast(_ExitCodeThresholds, next(iter(sca_thresholds.values()))) soft_fail_on_checks = generic_thresholds['soft_fail_checks'] soft_fail_threshold = generic_thresholds['soft_fail_threshold'] hard_fail_on_checks = generic_thresholds['hard_fail_checks'] # these two can be different for licenses / vulnerabilities hard_fail_threshold = {category: thresholds['hard_fail_threshold'] for category, thresholds in sca_thresholds.items()} # type:ignore[index] # thinks it's an object, can't possibly be more clear soft_fail = {category: thresholds['soft_fail'] for category, thresholds in sca_thresholds.items()} # type:ignore[index] # thinks it's an object failed_checks_by_category = { CodeCategoryType.LICENSES: [fc for fc in self.failed_checks if '_LIC_' in fc.check_id], CodeCategoryType.VULNERABILITIES: [fc for fc in self.failed_checks if '_VUL_' in fc.check_id] } has_soft_fail_values = soft_fail_on_checks or soft_fail_threshold if all( not failed_checks_by_category[cast(CodeCategoryType, c)] or ( not has_soft_fail_values and not (hard_fail_threshold[c] or hard_fail_on_checks) and soft_fail[c] ) for c in sca_thresholds.keys() ): logging.debug( 'No failed checks, or soft_fail is True and soft_fail_on and hard_fail_on are empty for all SCA types - returning 0') return 0 if any( not has_soft_fail_values and not (hard_fail_threshold[c] or hard_fail_on_checks) and failed_checks_by_category[cast(CodeCategoryType, c)] for c in sca_thresholds.keys() ): logging.debug('There are failed checks and all soft/hard fail args are empty for one or more SCA reports - returning 1') return 1 else: non_sca_thresholds = cast(_ExitCodeThresholds, exit_code_thresholds) soft_fail_on_checks = non_sca_thresholds['soft_fail_checks'] soft_fail_threshold = non_sca_thresholds['soft_fail_threshold'] hard_fail_on_checks = non_sca_thresholds['hard_fail_checks'] hard_fail_threshold = non_sca_thresholds['hard_fail_threshold'] soft_fail = non_sca_thresholds['soft_fail'] has_soft_fail_values = soft_fail_on_checks or soft_fail_threshold has_hard_fail_values = hard_fail_threshold or hard_fail_on_checks if not has_soft_fail_values and not has_hard_fail_values and soft_fail: logging.debug('Soft_fail is True and soft_fail_on and hard_fail_on are empty - returning 0') return 0 elif not has_soft_fail_values and not has_hard_fail_values: logging.debug('There are failed checks and all soft/hard fail args are empty - returning 1') return 1 for failed_check in self.failed_checks: check_id = failed_check.check_id bc_check_id = failed_check.bc_check_id severity = failed_check.severity secret_validation_status = failed_check.validation_status if hasattr(failed_check, 'validation_status') else '' hf_threshold: Severity sf: bool if has_split_enforcement: category = CodeCategoryType.LICENSES if '_LIC_' in check_id else CodeCategoryType.VULNERABILITIES hard_fail_threshold = cast(Dict[str, Severity], hard_fail_threshold) hf_threshold = hard_fail_threshold[category] soft_fail = cast(Dict[str, bool], soft_fail) sf = soft_fail[category] else: hard_fail_threshold = cast(Severity, hard_fail_threshold) hf_threshold = hard_fail_threshold soft_fail = cast(bool, soft_fail) sf = soft_fail soft_fail_severity = severity and soft_fail_threshold and severity.level <= soft_fail_threshold.level hard_fail_severity = severity and hf_threshold and severity.level >= hf_threshold.level explicit_soft_fail = RunnerFilter.check_matches(check_id, bc_check_id, soft_fail_on_checks) explicit_hard_fail = RunnerFilter.check_matches(check_id, bc_check_id, hard_fail_on_checks) explicit_secrets_soft_fail = RunnerFilter.secret_validation_status_matches(secret_validation_status, soft_fail_on_checks) explicit_secrets_hard_fail = RunnerFilter.secret_validation_status_matches(secret_validation_status, hard_fail_on_checks) implicit_soft_fail = not explicit_hard_fail and not explicit_secrets_hard_fail and not soft_fail_on_checks and not soft_fail_threshold implicit_hard_fail = not explicit_soft_fail and not soft_fail_severity and not explicit_secrets_soft_fail if explicit_hard_fail or \ (hard_fail_severity and not explicit_soft_fail) or \ (implicit_hard_fail and not implicit_soft_fail and not sf): logging.debug(f'Check {check_id} (BC ID: {bc_check_id}, severity: {severity.level if severity else None} triggered hard fail - returning 1') return 1 logging.debug('No failed check triggered hard fail - returning 0') return 0 def is_empty(self, full: bool = False) -> bool: checks_count = ( len(self.passed_checks) + len(self.failed_checks) + len(self.skipped_checks) + len(self.parsing_errors) ) if full: checks_count += len(self.resources) + len(self.extra_resources) + len(self.image_cached_results) return checks_count == 0 def add_errors_to_output(self) -> str: ret_value = '' for error_title, errors_messages in self.errors.items(): ret_value += colored(f"Encountered {error_title} error - {len(errors_messages)} times\n\n", "red") return ret_value def print_console( self, is_quiet: bool = False, is_compact: bool = False, created_baseline_path: str | None = None, baseline: Baseline | None = None, use_bc_ids: bool = False, summary_position: str = 'top', openai_api_key: str | None = None, ) -> str: summary = self.get_summary() output_data = colored(f"{self.check_type} scan results:\n", "blue") if self.parsing_errors: message = "\nPassed checks: {}, Failed checks: {}, Skipped checks: {}, Parsing errors: {}\n\n".format( summary["passed"], summary["failed"], summary["skipped"], summary["parsing_errors"], ) else: if self.check_type == CheckType.SCA_PACKAGE or self.check_type.lower().startswith(CheckType.SAST): message = f"\nFailed checks: {summary['failed']}, Skipped checks: {summary['skipped']}\n\n" else: message = f"\nPassed checks: {summary['passed']}, Failed checks: {summary['failed']}, Skipped checks: {summary['skipped']}\n\n" if summary_position == 'top': output_data += colored(message, "cyan") # output for vulnerabilities is different if self.check_type in (CheckType.SCA_PACKAGE, CheckType.SCA_IMAGE): if self.failed_checks or self.skipped_checks: create_cli_output = create_sca_package_cli_output_v2 output_data += create_cli_output(self.check_type == CheckType.SCA_PACKAGE, self.failed_checks, self.skipped_checks) elif self.check_type == CheckType.POLICY_3D: if self.failed_checks or self.skipped_checks: output_data += create_3d_policy_cli_output(self.failed_checks, self.skipped_checks) # type:ignore[arg-type] else: if self.check_type.lower().startswith(CheckType.SAST): output_data += colored(f"Source code files scanned: {summary.get(SOURCE_FILES_COUNT, -1)}, " f"Policies found: {summary.get(POLICY_COUNT, -1)}\n\n", "cyan") policies_errors: str = str(summary.get(POLICIES_ERRORS, "")) if policies_errors: output_data += colored(f"Policy parsing failures ({summary.get(POLICIES_ERRORS_COUNT)}):\n{policies_errors}\n\n", "red") if not is_quiet: for record in self.passed_checks: output_data += record.to_string(compact=is_compact, use_bc_ids=use_bc_ids) if self.failed_checks: OpenAi(api_key=openai_api_key).enhance_records(runner_type=self.check_type, records=self.failed_checks) for record in self.failed_checks: output_data += record.to_string(compact=is_compact, use_bc_ids=use_bc_ids) if not is_quiet: for record in self.skipped_checks: output_data += record.to_string(compact=is_compact, use_bc_ids=use_bc_ids) if not is_quiet: for file in self.parsing_errors: output_data += colored(f"Error parsing file {file}ֿ\n", "red") if created_baseline_path: output_data += colored( f"Created a checkov baseline file at {created_baseline_path}", "blue", ) if baseline: output_data += colored( f"Baseline analysis report using {baseline.path} - only new failed checks with respect to the baseline are reported", "blue", ) if summary_position == 'bottom': output_data += colored(message, "cyan") return output_data def _print_parsing_error_console(file: str) -> None: print(colored(f"Error parsing file {file}", "red")) def get_junit_xml_string(ts: list[TestSuite]) -> str: return to_xml_report_string(ts) def print_failed_github_md(self, use_bc_ids: bool = False) -> str: result = [] for record in self.failed_checks: result.append( [ record.get_output_id(use_bc_ids), record.file_path, record.resource, record.check_name, record.guideline, ] ) if result: table = tabulate( result, headers=["check_id", "file", "resource", "check_name", "guideline"], tablefmt="github", showindex=True, ) output_data = f"### {self.check_type} scan results:\n\n{table}\n\n---\n" return output_data else: return "\n\n---\n\n" def get_test_suite(self, properties: Optional[Dict[str, Any]] = None, use_bc_ids: bool = False) -> TestSuite: """Creates a test suite for the JUnit XML report""" test_cases = [] records = self.passed_checks + self.failed_checks + self.skipped_checks for record in records: severity = BcSeverities.NONE if record.severity: severity = record.severity.name if self.check_type == CheckType.SCA_PACKAGE: if record.check_name != SCA_PACKAGE_SCAN_CHECK_NAME: continue if not record.vulnerability_details: # this shouldn't normally happen logging.warning(f"Vulnerability check without details {record.file_path}") continue check_id = record.vulnerability_details["id"] test_name_detail = f"{record.vulnerability_details['package_name']}: {record.vulnerability_details['package_version']}" class_name = f"{record.file_path}.{record.vulnerability_details['package_name']}" else: check_id = record.bc_check_id if use_bc_ids else record.check_id test_name_detail = record.check_name class_name = f"{record.file_path}.{record.resource}" test_name = f"[{severity}][{check_id}] {test_name_detail}" test_case = TestCase(name=test_name, file=record.file_path, classname=class_name) if record.check_result["result"] == CheckResult.FAILED: test_case.add_failure_info( message=record.check_name, output=self._create_test_case_failure_output(record) ) if record.check_result["result"] == CheckResult.SKIPPED: if self.check_type == CheckType.SCA_PACKAGE: test_case.add_skipped_info(f"{check_id} skipped for {test_name_detail}") else: test_case.add_skipped_info(record.check_result.get("suppress_comment", "")) test_cases.append(test_case) test_suite = TestSuite(name=f"{self.check_type} scan", test_cases=test_cases, properties=properties) return test_suite def create_test_suite_properties_block(config: argparse.Namespace) -> Dict[str, Any]: """Creates a dictionary without 'None' values for the JUnit XML properties block""" properties = {k: v for k, v in config.__dict__.items() if v is not None} return properties def _create_test_case_failure_output(self, record: Record) -> str: """Creates the failure output for a JUnit XML test case IaC example: Resource: azurerm_network_security_rule.fail_rdp File: /main.tf: 71-83 Guideline: https://docs.bridgecrew.io/docs/bc_azr_networking_2 71 | resource "azurerm_network_security_rule" "fail_rdp" { 72 | resource_group_name = azurerm_resource_group.example.name 73 | network_security_group_name=azurerm_network_security_group.example_rdp.name 74 | name = "fail_security_rule" 75 | direction = "Inbound" 76 | access = "Allow" 77 | protocol = "TCP" 78 | source_port_range = "*" 79 | destination_port_range = "3389" 80 | source_address_prefix = "*" 81 | destination_address_prefix = "*" 82 | priority = 120 83 | } SCA example: Description: Django before 1.11.27, 2.x before 2.2.9, and 3.x before 3.0.1 allows account takeover. Link: https://nvd.nist.gov/vuln/detail/CVE-2019-19844 Published Date: 2019-12-18T20:15:00+01:00 Base Score: 9.8 Vector: CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H Risk Factors: ['Attack complexity: low', 'Attack vector: network', 'Critical severity', 'Has fix'] Resource: requirements.txt.django File: /requirements.txt: 0-0 0 | django: 1.2 """ failure_output = [] if self.check_type == CheckType.SCA_PACKAGE: if record.vulnerability_details: lowest_fixed_version = record.vulnerability_details.get('lowest_fixed_version') if lowest_fixed_version is not None: fix = lowest_fixed_version else: fixlist = record.vulnerability_details.get('fixed_versions') if fixlist is not None: fix = fixlist failure_output.extend( [ "", f"Description: {record.description}", f"Link: {record.vulnerability_details.get('link')}", f"Published Date: {record.vulnerability_details.get('published_date')}", f"Base Score: {record.vulnerability_details.get('cvss')}", f"Vector: {record.vulnerability_details.get('vector')}", f"Risk Factors: {record.vulnerability_details.get('risk_factors')}", "Fix Details:", f" Status: {record.vulnerability_details.get('status')}", f" Fixed Version: {fix}", ] ) else: # this shouldn't normally happen logging.warning(f"Vulnerability check without details {record.file_path}") failure_output.extend( [ "", f"Resource: {record.resource}", ] ) if record.file_path: file_line = f"File: {record.file_path}" if record.file_line_range: file_line += f": {record.file_line_range[0]}-{record.file_line_range[1]}" failure_output.append(file_line) if self.check_type != CheckType.SCA_PACKAGE: failure_output.append(f"Guideline: {record.guideline}") if record.code_block: failure_output.append("") failure_output.append(record._code_line_string(code_block=record.code_block, colorized=False)) return "\n".join(failure_output) def print_json(self) -> None: print(self.get_json()) def enrich_plan_report( report: "Report", enriched_resources: Dict[str, Dict[str, Any]] ) -> "Report": # This enriches reports with the appropriate filepath, line numbers, and codeblock for record in report.failed_checks: resource_raw_id = Report.get_plan_resource_raw_id(record.resource) enriched_resource = enriched_resources.get(resource_raw_id) if enriched_resource: record.file_path = enriched_resource["scanned_file"] record.file_line_range = enriched_resource["entity_lines_range"] record.code_block = enriched_resource["entity_code_lines"] return report def handle_skipped_checks( report: "Report", enriched_resources: Dict[str, Dict[str, Any]] ) -> "Report": module_address_len = len("module.") skip_records = [] for record in report.failed_checks: resource_raw_id = Report.get_plan_resource_raw_id(record.resource) resource_skips = enriched_resources.get(resource_raw_id, {}).get( "skipped_checks", [] ) for skip in resource_skips: if record.check_id in skip["id"]: # Mark for removal and add it as a skipped record. It is not safe to remove # the record from failed_checks immediately because we're iterating over it skip_records.append(record) record.check_result["result"] = CheckResult.SKIPPED record.check_result["suppress_comment"] = skip["suppress_comment"] report.add_record(record) if record.resource_address and record.resource_address.startswith("module."): module_path = record.resource_address[module_address_len:record.resource_address.index('.', module_address_len + 1)] module_enrichments = enriched_resources.get(module_path, {}) for module_skip in module_enrichments.get("skipped_checks", []): if record.check_id in module_skip["id"]: skip_records.append(record) record.check_result["result"] = CheckResult.SKIPPED record.check_result["suppress_comment"] = module_skip["suppress_comment"] report.add_record(record) for record in skip_records: if record in report.failed_checks: report.failed_checks.remove(record) return report def get_plan_resource_raw_id(resource_id: str) -> str: """ return the resource raw id without the modules and the indexes example: from resource_id='module.module_name.type.name[1]' return 'type.name' """ resource_raw_id = ".".join(resource_id.split(".")[-2:]) if '[' in resource_raw_id: resource_raw_id = resource_raw_id[:resource_raw_id.index('[')] return resource_raw_id def from_reduced_json(cls, json_report: dict[str, Any], check_type: str) -> Report: report = Report(check_type) report.image_cached_results = json_report['image_cached_results'] all_json_records = json_report["checks"]["passed_checks"] + \ json_report["checks"]["failed_checks"] + \ json_report["checks"]["skipped_checks"] for json_record in all_json_records: report.add_record( Record.from_reduced_json(json_record) ) return report parallel_runner = ParallelRunner() _BaseRunner = TypeVar("_BaseRunner", bound="BaseRunner[Any, Any, Any]") LibraryGraph: TypeAlias = "Union[DiGraph, _RustworkxGraph]" log_stream = StringIO() def erase_log_stream() -> None: log_stream.seek(0) log_stream.truncate(0) class RunnerFilter(object): # NOTE: This needs to be static because different filters may be used at load time versus runtime # (see note in BaseCheckRegistery.register). The concept of which checks are external is # logically a "static" concept anyway, so this makes logical sense. __EXTERNAL_CHECK_IDS: Set[str] = set() def __init__( self, framework: Optional[List[str]] = None, checks: Union[str, List[str], None] = None, skip_checks: Union[str, List[str], None] = None, include_all_checkov_policies: bool = True, download_external_modules: bool = False, external_modules_download_path: str = DEFAULT_EXTERNAL_MODULES_DIR, evaluate_variables: bool = True, runners: Optional[List[str]] = None, skip_framework: Optional[List[str]] = None, excluded_paths: Optional[List[str]] = None, all_external: bool = False, var_files: Optional[List[str]] = None, skip_cve_package: Optional[List[str]] = None, use_enforcement_rules: bool = False, filtered_policy_ids: Optional[List[str]] = None, show_progress_bar: Optional[bool] = True, run_image_referencer: bool = False, enable_secret_scan_all_files: bool = False, block_list_secret_scan: Optional[List[str]] = None, deep_analysis: bool = False, repo_root_for_plan_enrichment: Optional[List[str]] = None, resource_attr_to_omit: Optional[Dict[str, Set[str]]] = None, enable_git_history_secret_scan: bool = False, git_history_timeout: str = '12h', git_history_last_commit_scanned: Optional[str] = None, # currently not exposed by a CLI flag report_sast_imports: bool = False, remove_default_sast_policies: bool = False, report_sast_reachability: bool = False ) -> None: checks = convert_csv_string_arg_to_list(checks) skip_checks = convert_csv_string_arg_to_list(skip_checks) self.skip_invalid_secrets = skip_checks and any(skip_check.capitalize() == ValidationStatus.INVALID.value for skip_check in skip_checks) self.use_enforcement_rules = use_enforcement_rules self.enforcement_rule_configs: Dict[str, Severity | Dict[CodeCategoryType, Severity]] = {} # we will store the lowest value severity we find in checks, and the highest value we find in skip-checks # so the logic is "run all checks >= severity" and/or "skip all checks <= severity" self.check_threshold = None self.skip_check_threshold = None self.checks = [] self.bc_cloned_checks: dict[str, list[dict[str, Any]]] = defaultdict(list) self.skip_checks = [] self.skip_checks_regex_patterns = defaultdict(list) self.show_progress_bar = show_progress_bar # split out check/skip thresholds so we can access them easily later for val in (checks or []): if val.upper() in Severities: val = val.upper() if not self.check_threshold or self.check_threshold.level > Severities[val].level: self.check_threshold = Severities[val] else: self.checks.append(val) # Get regex patterns to split checks and remove it from skip checks: updated_skip_checks = set(skip_checks) for val in (skip_checks or []): splitted_check = val.split(":") # In case it's not expected pattern if len(splitted_check) != 2: continue self.skip_checks_regex_patterns[splitted_check[0]].append(splitted_check[1]) updated_skip_checks -= {val} skip_checks = list(updated_skip_checks) for val in (skip_checks or []): if val.upper() in Severities: val = val.upper() if not self.skip_check_threshold or self.skip_check_threshold.level < Severities[val].level: self.skip_check_threshold = Severities[val] else: self.skip_checks.append(val) self.include_all_checkov_policies = include_all_checkov_policies if not framework or "all" in framework: self.framework_flag_values = [] else: self.framework_flag_values = framework self.framework: "Iterable[str]" = framework if framework else ["all"] if skip_framework: if "all" in self.framework: if runners is None: runners = [] self.framework = set(runners) - set(skip_framework) else: self.framework = set(self.framework) - set(skip_framework) logging.debug(f"Resultant set of frameworks (removing skipped frameworks): {','.join(self.framework)}") self.download_external_modules = download_external_modules self.external_modules_download_path = external_modules_download_path self.evaluate_variables = evaluate_variables self.excluded_paths = excluded_paths or [] self.all_external = all_external self.var_files = var_files self.skip_cve_package = skip_cve_package self.filtered_policy_ids = filtered_policy_ids or [] self.run_image_referencer = run_image_referencer self.enable_secret_scan_all_files = enable_secret_scan_all_files self.block_list_secret_scan = block_list_secret_scan self.suppressed_policies: List[str] = [] self.deep_analysis = deep_analysis self.repo_root_for_plan_enrichment = repo_root_for_plan_enrichment self.resource_attr_to_omit: DefaultDict[str, Set[str]] = RunnerFilter._load_resource_attr_to_omit( resource_attr_to_omit ) self.sast_languages: Set[SastLanguages] = RunnerFilter.get_sast_languages(framework, skip_framework) if self.sast_languages and any(item for item in self.framework if item.startswith(CheckType.SAST) or item == 'all'): self.framework = [item for item in self.framework if not item.startswith(CheckType.SAST)] self.framework.append(CheckType.SAST) elif not self.sast_languages: # remove all SAST and CDK frameworks self.framework = [ item for item in self.framework if not item.startswith(CheckType.SAST) and item != CheckType.CDK ] self.enable_git_history_secret_scan: bool = enable_git_history_secret_scan if self.enable_git_history_secret_scan: self.git_history_timeout = convert_to_seconds(git_history_timeout) self.framework = [CheckType.SECRETS] logging.debug("Scan secrets history was enabled ignoring other frameworks") self.git_history_last_commit_scanned = git_history_last_commit_scanned self.report_sast_imports = report_sast_imports self.remove_default_sast_policies = remove_default_sast_policies self.report_sast_reachability = report_sast_reachability def _load_resource_attr_to_omit(resource_attr_to_omit_input: Optional[Dict[str, Set[str]]]) -> DefaultDict[str, Set[str]]: resource_attributes_to_omit: DefaultDict[str, Set[str]] = defaultdict(set) # In order to create new object (and not a reference to the given one) if resource_attr_to_omit_input: resource_attributes_to_omit.update(resource_attr_to_omit_input) return resource_attributes_to_omit def apply_enforcement_rules(self, enforcement_rule_configs: Dict[str, CodeCategoryConfiguration]) -> None: self.enforcement_rule_configs = {} for report_type, code_category in CodeCategoryMapping.items(): if isinstance(code_category, list): self.enforcement_rule_configs[report_type] = {c: enforcement_rule_configs.get(c).soft_fail_threshold for c in code_category} # type:ignore[union-attr] # will not be None else: config = enforcement_rule_configs.get(code_category) if not config: raise Exception(f'Could not find an enforcement rule config for category {code_category} (runner: {report_type})') self.enforcement_rule_configs[report_type] = config.soft_fail_threshold def extract_enforcement_rule_threshold(self, check_id: str, report_type: str) -> Severity: if 'sca_' in report_type and '_LIC_' in check_id: return cast("dict[CodeCategoryType, Severity]", self.enforcement_rule_configs[report_type])[CodeCategoryType.LICENSES] elif 'sca_' in report_type: # vulnerability return cast("dict[CodeCategoryType, Severity]", self.enforcement_rule_configs[report_type])[CodeCategoryType.VULNERABILITIES] else: return cast(Severity, self.enforcement_rule_configs[report_type]) def should_run_check( self, check: BaseCheck | BaseGraphCheck | BaseSastCheck | None = None, check_id: str | None = None, bc_check_id: str | None = None, severity: Severity | None = None, report_type: str | None = None, file_origin_paths: List[str] | None = None, root_folder: str | None = None ) -> bool: if check: check_id = check.id bc_check_id = check.bc_id severity = check.severity assert check_id is not None # nosec (for mypy (and then for bandit)) check_threshold: Optional[Severity] skip_check_threshold: Optional[Severity] # apply enforcement rules if specified, but let --check/--skip-check with a severity take priority if self.use_enforcement_rules and report_type: if not self.check_threshold and not self.skip_check_threshold: check_threshold = self.extract_enforcement_rule_threshold(check_id, report_type) skip_check_threshold = None else: check_threshold = self.check_threshold skip_check_threshold = self.skip_check_threshold else: if self.use_enforcement_rules: # this is a warning for us (but there is nothing the user can do about it) logging.debug(f'Use enforcement rules is true, but check {check_id} was not passed to the runner filter with a report type') check_threshold = self.check_threshold skip_check_threshold = self.skip_check_threshold run_severity = severity and check_threshold and severity.level >= check_threshold.level explicit_run = self.checks and self.check_matches(check_id, bc_check_id, self.checks) implicit_run = not self.checks and not check_threshold is_external = RunnerFilter.is_external_check(check_id) is_policy_filtered = self.is_policy_filtered(check_id) # True if this check is present in the allow list, or if there is no allow list # this is not necessarily the return value (need to apply other filters) should_run_check = ( run_severity or explicit_run or implicit_run or (is_external and self.all_external) ) if not should_run_check: logging.debug(f'Should run check {check_id}: False') return False # If a policy is not present in the list of filtered policies, it should not be run - implicitly or explicitly. # It can, however, be skipped. if not is_policy_filtered: logging.debug(f'not is_policy_filtered {check_id}: should_run_check = False') should_run_check = False skip_severity = severity and skip_check_threshold and severity.level <= skip_check_threshold.level explicit_skip = self.skip_checks and self.check_matches(check_id, bc_check_id, self.skip_checks) regex_match = self._match_regex_pattern(check_id, file_origin_paths, root_folder) should_skip_check = ( skip_severity or explicit_skip or regex_match or (not bc_check_id and not self.include_all_checkov_policies and not is_external and not explicit_run) or (bc_check_id in self.suppressed_policies and bc_check_id not in self.bc_cloned_checks) ) logging.debug(f'skip_severity = {skip_severity}, explicit_skip = {explicit_skip}, regex_match = {regex_match}, suppressed_policies: {self.suppressed_policies}') logging.debug( f'bc_check_id = {bc_check_id}, include_all_checkov_policies = {self.include_all_checkov_policies}, is_external = {is_external}, explicit_run: {explicit_run}') if should_skip_check: result = False logging.debug(f'should_skip_check {check_id}: {should_skip_check}') elif should_run_check: result = True logging.debug(f'should_run_check {check_id}: {result}') else: result = False logging.debug(f'default {check_id}: {result}') return result def _match_regex_pattern(self, check_id: str, file_origin_paths: List[str] | None, root_folder: str | None) -> bool: """ Check if skip check_id for a certain file_types, according to given path pattern """ if not file_origin_paths: return False regex_patterns = self.skip_checks_regex_patterns.get(check_id, []) # In case skip is generic, for example, CKV_AZURE_*. generic_check_id = f"{'_'.join(i for i in check_id.split('_')[:-1])}_*" generic_check_regex_patterns = self.skip_checks_regex_patterns.get(generic_check_id, []) regex_patterns.extend(generic_check_regex_patterns) if not regex_patterns: return False for pattern in regex_patterns: if not pattern: continue full_regex_pattern = fr"^{root_folder}/{pattern}" if root_folder else pattern try: if any(re.search(full_regex_pattern, path) for path in file_origin_paths): return True except Exception as exc: logging.error( "Invalid regex pattern has been supplied", extra={"regex_pattern": pattern, "exc": str(exc)} ) return False def check_matches(check_id: str, bc_check_id: Optional[str], pattern_list: List[str]) -> bool: return any( (fnmatch.fnmatch(check_id, pattern) or (bc_check_id and fnmatch.fnmatch(bc_check_id, pattern))) for pattern in pattern_list) def within_threshold(self, severity: Severity) -> bool: above_min = (not self.check_threshold) or self.check_threshold.level <= severity.level below_max = self.skip_check_threshold and self.skip_check_threshold.level >= severity.level return above_min and not below_max def secret_validation_status_matches(secret_validation_status: str, statuses_list: list[str]) -> bool: return secret_validation_status in statuses_list def notify_external_check(check_id: str) -> None: RunnerFilter.__EXTERNAL_CHECK_IDS.add(check_id) def is_external_check(check_id: str) -> bool: return check_id in RunnerFilter.__EXTERNAL_CHECK_IDS def is_policy_filtered(self, check_id: str) -> bool: if not self.filtered_policy_ids: return True return check_id in self.filtered_policy_ids def to_dict(self) -> Dict[str, Any]: result: Dict[str, Any] = {} for key, value in self.__dict__.items(): result[key] = value return result def from_dict(obj: Dict[str, Any]) -> RunnerFilter: framework = obj.get('framework') checks = obj.get('checks') skip_checks = obj.get('skip_checks') include_all_checkov_policies = obj.get('include_all_checkov_policies') if include_all_checkov_policies is None: include_all_checkov_policies = True download_external_modules = obj.get('download_external_modules') if download_external_modules is None: download_external_modules = False external_modules_download_path = obj.get('external_modules_download_path') if external_modules_download_path is None: external_modules_download_path = DEFAULT_EXTERNAL_MODULES_DIR evaluate_variables = obj.get('evaluate_variables') if evaluate_variables is None: evaluate_variables = True runners = obj.get('runners') skip_framework = obj.get('skip_framework') excluded_paths = obj.get('excluded_paths') all_external = obj.get('all_external') if all_external is None: all_external = False var_files = obj.get('var_files') skip_cve_package = obj.get('skip_cve_package') use_enforcement_rules = obj.get('use_enforcement_rules') if use_enforcement_rules is None: use_enforcement_rules = False filtered_policy_ids = obj.get('filtered_policy_ids') show_progress_bar = obj.get('show_progress_bar') if show_progress_bar is None: show_progress_bar = True run_image_referencer = obj.get('run_image_referencer') if run_image_referencer is None: run_image_referencer = False enable_secret_scan_all_files = bool(obj.get('enable_secret_scan_all_files')) block_list_secret_scan = obj.get('block_list_secret_scan') runner_filter = RunnerFilter(framework, checks, skip_checks, include_all_checkov_policies, download_external_modules, external_modules_download_path, evaluate_variables, runners, skip_framework, excluded_paths, all_external, var_files, skip_cve_package, use_enforcement_rules, filtered_policy_ids, show_progress_bar, run_image_referencer, enable_secret_scan_all_files, block_list_secret_scan) return runner_filter def set_suppressed_policies(self, policy_level_suppressions: List[str]) -> None: logging.debug(f"Received the following policy-level suppressions, that will be skipped from running: {policy_level_suppressions}") self.suppressed_policies = policy_level_suppressions def get_sast_languages(frameworks: Optional[List[str]], skip_framework: Optional[List[str]]) -> Set[SastLanguages]: langs: Set[SastLanguages] = set() if not frameworks or (skip_framework and "sast" in skip_framework): return langs if 'all' in frameworks: sast_languages = SastLanguages.set() skip_framework = [] if not skip_framework else [f.split("sast_")[-1] for f in skip_framework] return set([lang for lang in sast_languages if lang.value not in skip_framework]) for framework in frameworks: if framework in [CheckType.SAST, CheckType.CDK]: for sast_lang in SastLanguages: langs.add(sast_lang) return langs if not framework.startswith(CheckType.SAST): continue lang = '_'.join(framework.split('_')[1:]) langs.add(SastLanguages[lang.upper()]) return langs def _parallel_run( runner: _BaseRunner, root_folder: str | None = None, external_checks_dir: list[str] | None = None, files: list[str] | None = None, runner_filter: RunnerFilter | None = None, collect_skip_comments: bool = True, platform_integration_data: dict[str, Any] | None = None, ) -> tuple[Report | list[Report], str | None, list[tuple[LibraryGraph, str | None]] | None, dict[str, str] | None, StringIO | None]: # only sub processes need to erase their logs, to start clean if parallel_runner.running_as_process(): erase_log_stream() if platform_integration_data: # only happens for 'ParallelizationType.SPAWN' bc_integration.init_instance(platform_integration_data=platform_integration_data) report = runner.run( root_folder=root_folder, external_checks_dir=external_checks_dir, files=files, runner_filter=runner_filter, collect_skip_comments=collect_skip_comments, ) if report is None: # this only happens, when an uncaught exception inside the runner occurs logging.error(f"Failed to create report for {runner.check_type} framework") report = Report(check_type=runner.check_type) if runner.graph_manager: return report, runner.check_type, RunnerRegistry.extract_graphs_from_runner(runner), runner.resource_subgraph_map, log_stream return report, runner.check_type, None, None, log_stream
null
2,310
from __future__ import annotations import itertools import logging import os import re from abc import ABC, abstractmethod from collections.abc import Iterable from typing import List, Any, TYPE_CHECKING, TypeVar, Generic, Dict, Optional from checkov.common.graph.db_connectors.networkx.networkx_db_connector import NetworkxConnector from checkov.common.graph.graph_builder import CustomAttributes from checkov.common.util.tqdm_utils import ProgressBar from checkov.common.graph.checks_infra.base_check import BaseGraphCheck from checkov.common.output.report import Report from checkov.runner_filter import RunnerFilter from checkov.common.graph.graph_manager import GraphManager The provided code snippet includes necessary dependencies for implementing the `strtobool` function. Write a Python function `def strtobool(val: str) -> int` to solve the following problem: Convert a string representation of truth to true (1) or false (0). True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if 'val' is anything else. Here is the function: def strtobool(val: str) -> int: """Convert a string representation of truth to true (1) or false (0). True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if 'val' is anything else. """ val = val.lower() if val in ('y', 'yes', 't', 'true', 'on', '1'): return 1 elif val in ('n', 'no', 'f', 'false', 'off', '0'): return 0 else: raise ValueError("invalid boolean value %r for environment variable CKV_IGNORE_HIDDEN_DIRECTORIES" % (val,))
Convert a string representation of truth to true (1) or false (0). True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if 'val' is anything else.
2,311
from __future__ import annotations import itertools import logging import os from datetime import datetime from hashlib import sha1 from importlib.metadata import version as meta_version from pathlib import Path from typing import TYPE_CHECKING, cast, Any from cyclonedx.model import ( XsUri, ExternalReference, ExternalReferenceType, HashAlgorithm, HashType, Property, Tool, ) from cyclonedx.model.bom import Bom from cyclonedx.model.component import Component, ComponentType from cyclonedx.model.license import DisjunctiveLicense from cyclonedx.model.vulnerability import ( Vulnerability, VulnerabilityAdvisory, BomTarget, VulnerabilitySource, VulnerabilityRating, VulnerabilityScoreSource, VulnerabilitySeverity, ) from cyclonedx.schema import OutputFormat from cyclonedx.output import make_outputter from packageurl import PackageURL from checkov.common.output.common import ImageDetails, format_string_to_licenses, validate_lines from checkov.common.output.report import CheckType from checkov.common.output.cyclonedx_consts import ( SCA_CHECKTYPES, PURL_TYPE_MAVEN, DEFAULT_CYCLONE_SCHEMA_VERSION, CYCLONE_SCHEMA_VERSION, FILE_NAME_TO_PURL_TYPE, IMAGE_DISTRO_TO_PURL_TYPE, TWISTCLI_PACKAGE_TYPE_TO_PURL_TYPE, BC_SEVERITY_TO_CYCLONEDX_LEVEL, ) from checkov.common.output.record import SCA_PACKAGE_SCAN_CHECK_NAME from checkov.common.sca.commons import UNFIXABLE_VERSION, get_fix_version The provided code snippet includes necessary dependencies for implementing the `file_sha1sum` function. Write a Python function `def file_sha1sum(filename: str) -> str` to solve the following problem: Generate a SHA1 hash of the provided file. Args: filename: Absolute path to file to hash as `str` Returns: SHA-1 hash Here is the function: def file_sha1sum(filename: str) -> str: """ Generate a SHA1 hash of the provided file. Args: filename: Absolute path to file to hash as `str` Returns: SHA-1 hash """ h = sha1() # nosec B303, B324 with open(filename, 'rb') as f: for byte_block in iter(lambda: f.read(4096), b''): h.update(byte_block) return h.hexdigest()
Generate a SHA1 hash of the provided file. Args: filename: Absolute path to file to hash as `str` Returns: SHA-1 hash
2,312
from __future__ import annotations import argparse import json import logging import os from collections.abc import Iterable from typing import List, Dict, Union, Any, Optional, TYPE_CHECKING, cast from colorama import init from junit_xml import TestCase, TestSuite, to_xml_report_string from tabulate import tabulate from termcolor import colored from checkov.common.bridgecrew.code_categories import CodeCategoryType from checkov.common.bridgecrew.severities import BcSeverities, Severity from checkov.common.bridgecrew.check_type import CheckType from checkov.common.models.enums import CheckResult, ErrorStatus from checkov.common.output.ai import OpenAi from checkov.common.typing import _ExitCodeThresholds, _ScaExitCodeThresholds from checkov.common.output.record import Record, SCA_PACKAGE_SCAN_CHECK_NAME from checkov.common.sast.consts import POLICIES_ERRORS, POLICIES_ERRORS_COUNT, SOURCE_FILES_COUNT, POLICY_COUNT from checkov.common.util.consts import PARSE_ERROR_FAIL_FLAG, S3_UPLOAD_DETAILS_MESSAGE from checkov.common.util.json_utils import CustomJSONEncoder from checkov.runner_filter import RunnerFilter from checkov.sca_package_2.output import create_cli_output as create_sca_package_cli_output_v2 from checkov.policies_3d.output import create_cli_output as create_3d_policy_cli_output from checkov.version import version class Report: def __init__(self, check_type: str): self.check_type = check_type self.passed_checks: list[Record] = [] self.failed_checks: list[Record] = [] self.skipped_checks: list[Record] = [] self.parsing_errors: list[str] = [] self.resources: set[str] = set() self.extra_resources: set[ExtraResource] = set() self.image_cached_results: List[dict[str, Any]] = [] self.error_status: ErrorStatus = ErrorStatus.SUCCESS def errors(self) -> Dict[str, List[str]]: return dict() def set_error_status(self, error_status: ErrorStatus) -> None: self.error_status = error_status def add_parsing_errors(self, errors: "Iterable[str]") -> None: for file in errors: self.add_parsing_error(file) def add_parsing_error(self, file: str) -> None: if file: self.parsing_errors.append(file) def add_resource(self, resource: str) -> None: self.resources.add(resource) def add_record(self, record: Record) -> None: if record.check_result["result"] == CheckResult.PASSED: self.passed_checks.append(record) if record.check_result["result"] == CheckResult.FAILED: self.failed_checks.append(record) if record.check_result["result"] == CheckResult.SKIPPED: self.skipped_checks.append(record) def get_summary(self) -> Dict[str, Union[int, str]]: return { "passed": len(self.passed_checks), "failed": len(self.failed_checks), "skipped": len(self.skipped_checks), "parsing_errors": len(self.parsing_errors), "resource_count": len(self.resources), "checkov_version": version, } def get_json(self) -> str: return json.dumps(self.get_dict(), indent=4, cls=CustomJSONEncoder) def get_all_records(self) -> List[Record]: return self.failed_checks + self.passed_checks + self.skipped_checks def get_dict(self, is_quiet: bool = False, url: str | None = None, full_report: bool = False, s3_setup_failed: bool = False, support_path: str | None = None) -> dict[str, Any]: if not url and not s3_setup_failed: url = "Add an api key '--bc-api-key <api-key>' to see more detailed insights via https://bridgecrew.cloud" elif s3_setup_failed: url = S3_UPLOAD_DETAILS_MESSAGE if is_quiet: return { "check_type": self.check_type, "results": { "failed_checks": [check.__dict__ for check in self.failed_checks] }, "summary": self.get_summary(), } if full_report: return { "check_type": self.check_type, "checks": { "passed_checks": [check.__dict__ for check in self.passed_checks], "failed_checks": [check.__dict__ for check in self.failed_checks], "skipped_checks": [check.__dict__ for check in self.skipped_checks] }, "image_cached_results": [res.__dict__ for res in self.image_cached_results] } else: result = { "check_type": self.check_type, "results": { "passed_checks": [check.__dict__ for check in self.passed_checks], "failed_checks": [check.__dict__ for check in self.failed_checks], "skipped_checks": [check.__dict__ for check in self.skipped_checks], "parsing_errors": list(self.parsing_errors), }, "summary": self.get_summary(), "url": url, } if support_path: result["support_path"] = support_path return result def get_exit_code(self, exit_code_thresholds: Union[_ExitCodeThresholds, _ScaExitCodeThresholds]) -> int: """ Returns the appropriate exit code depending on the flags that are passed in. :return: Exit code 0 or 1. """ hard_fail_on_parsing_errors = os.getenv(PARSE_ERROR_FAIL_FLAG, "false").lower() == 'true' logging.debug(f'In get_exit_code; exit code thresholds: {exit_code_thresholds}, hard_fail_on_parsing_errors: {hard_fail_on_parsing_errors}') if self.parsing_errors and hard_fail_on_parsing_errors: logging.debug('hard_fail_on_parsing_errors is True and there were parsing errors - returning 1') return 1 if not self.failed_checks: logging.debug('No failed checks in this report - returning 0') return 0 # we will have two different sets of logic in this method, determined by this variable. # if we are using enforcement rules, then there are two different sets of thresholds that apply for licenses and vulnerabilities # and we have to handle that throughout while processing the report # if we are not using enforcement rules, then we can combine licenses and vulnerabilities like normal and same as all other report types # this determination is made in runner_registry.get_fail_thresholds has_split_enforcement = CodeCategoryType.LICENSES in exit_code_thresholds hard_fail_threshold: Optional[Severity | Dict[str, Severity]] soft_fail: Optional[bool | Dict[str, bool]] if has_split_enforcement: sca_thresholds = cast(_ScaExitCodeThresholds, exit_code_thresholds) # these three are the same even in split enforcement rules generic_thresholds = cast(_ExitCodeThresholds, next(iter(sca_thresholds.values()))) soft_fail_on_checks = generic_thresholds['soft_fail_checks'] soft_fail_threshold = generic_thresholds['soft_fail_threshold'] hard_fail_on_checks = generic_thresholds['hard_fail_checks'] # these two can be different for licenses / vulnerabilities hard_fail_threshold = {category: thresholds['hard_fail_threshold'] for category, thresholds in sca_thresholds.items()} # type:ignore[index] # thinks it's an object, can't possibly be more clear soft_fail = {category: thresholds['soft_fail'] for category, thresholds in sca_thresholds.items()} # type:ignore[index] # thinks it's an object failed_checks_by_category = { CodeCategoryType.LICENSES: [fc for fc in self.failed_checks if '_LIC_' in fc.check_id], CodeCategoryType.VULNERABILITIES: [fc for fc in self.failed_checks if '_VUL_' in fc.check_id] } has_soft_fail_values = soft_fail_on_checks or soft_fail_threshold if all( not failed_checks_by_category[cast(CodeCategoryType, c)] or ( not has_soft_fail_values and not (hard_fail_threshold[c] or hard_fail_on_checks) and soft_fail[c] ) for c in sca_thresholds.keys() ): logging.debug( 'No failed checks, or soft_fail is True and soft_fail_on and hard_fail_on are empty for all SCA types - returning 0') return 0 if any( not has_soft_fail_values and not (hard_fail_threshold[c] or hard_fail_on_checks) and failed_checks_by_category[cast(CodeCategoryType, c)] for c in sca_thresholds.keys() ): logging.debug('There are failed checks and all soft/hard fail args are empty for one or more SCA reports - returning 1') return 1 else: non_sca_thresholds = cast(_ExitCodeThresholds, exit_code_thresholds) soft_fail_on_checks = non_sca_thresholds['soft_fail_checks'] soft_fail_threshold = non_sca_thresholds['soft_fail_threshold'] hard_fail_on_checks = non_sca_thresholds['hard_fail_checks'] hard_fail_threshold = non_sca_thresholds['hard_fail_threshold'] soft_fail = non_sca_thresholds['soft_fail'] has_soft_fail_values = soft_fail_on_checks or soft_fail_threshold has_hard_fail_values = hard_fail_threshold or hard_fail_on_checks if not has_soft_fail_values and not has_hard_fail_values and soft_fail: logging.debug('Soft_fail is True and soft_fail_on and hard_fail_on are empty - returning 0') return 0 elif not has_soft_fail_values and not has_hard_fail_values: logging.debug('There are failed checks and all soft/hard fail args are empty - returning 1') return 1 for failed_check in self.failed_checks: check_id = failed_check.check_id bc_check_id = failed_check.bc_check_id severity = failed_check.severity secret_validation_status = failed_check.validation_status if hasattr(failed_check, 'validation_status') else '' hf_threshold: Severity sf: bool if has_split_enforcement: category = CodeCategoryType.LICENSES if '_LIC_' in check_id else CodeCategoryType.VULNERABILITIES hard_fail_threshold = cast(Dict[str, Severity], hard_fail_threshold) hf_threshold = hard_fail_threshold[category] soft_fail = cast(Dict[str, bool], soft_fail) sf = soft_fail[category] else: hard_fail_threshold = cast(Severity, hard_fail_threshold) hf_threshold = hard_fail_threshold soft_fail = cast(bool, soft_fail) sf = soft_fail soft_fail_severity = severity and soft_fail_threshold and severity.level <= soft_fail_threshold.level hard_fail_severity = severity and hf_threshold and severity.level >= hf_threshold.level explicit_soft_fail = RunnerFilter.check_matches(check_id, bc_check_id, soft_fail_on_checks) explicit_hard_fail = RunnerFilter.check_matches(check_id, bc_check_id, hard_fail_on_checks) explicit_secrets_soft_fail = RunnerFilter.secret_validation_status_matches(secret_validation_status, soft_fail_on_checks) explicit_secrets_hard_fail = RunnerFilter.secret_validation_status_matches(secret_validation_status, hard_fail_on_checks) implicit_soft_fail = not explicit_hard_fail and not explicit_secrets_hard_fail and not soft_fail_on_checks and not soft_fail_threshold implicit_hard_fail = not explicit_soft_fail and not soft_fail_severity and not explicit_secrets_soft_fail if explicit_hard_fail or \ (hard_fail_severity and not explicit_soft_fail) or \ (implicit_hard_fail and not implicit_soft_fail and not sf): logging.debug(f'Check {check_id} (BC ID: {bc_check_id}, severity: {severity.level if severity else None} triggered hard fail - returning 1') return 1 logging.debug('No failed check triggered hard fail - returning 0') return 0 def is_empty(self, full: bool = False) -> bool: checks_count = ( len(self.passed_checks) + len(self.failed_checks) + len(self.skipped_checks) + len(self.parsing_errors) ) if full: checks_count += len(self.resources) + len(self.extra_resources) + len(self.image_cached_results) return checks_count == 0 def add_errors_to_output(self) -> str: ret_value = '' for error_title, errors_messages in self.errors.items(): ret_value += colored(f"Encountered {error_title} error - {len(errors_messages)} times\n\n", "red") return ret_value def print_console( self, is_quiet: bool = False, is_compact: bool = False, created_baseline_path: str | None = None, baseline: Baseline | None = None, use_bc_ids: bool = False, summary_position: str = 'top', openai_api_key: str | None = None, ) -> str: summary = self.get_summary() output_data = colored(f"{self.check_type} scan results:\n", "blue") if self.parsing_errors: message = "\nPassed checks: {}, Failed checks: {}, Skipped checks: {}, Parsing errors: {}\n\n".format( summary["passed"], summary["failed"], summary["skipped"], summary["parsing_errors"], ) else: if self.check_type == CheckType.SCA_PACKAGE or self.check_type.lower().startswith(CheckType.SAST): message = f"\nFailed checks: {summary['failed']}, Skipped checks: {summary['skipped']}\n\n" else: message = f"\nPassed checks: {summary['passed']}, Failed checks: {summary['failed']}, Skipped checks: {summary['skipped']}\n\n" if summary_position == 'top': output_data += colored(message, "cyan") # output for vulnerabilities is different if self.check_type in (CheckType.SCA_PACKAGE, CheckType.SCA_IMAGE): if self.failed_checks or self.skipped_checks: create_cli_output = create_sca_package_cli_output_v2 output_data += create_cli_output(self.check_type == CheckType.SCA_PACKAGE, self.failed_checks, self.skipped_checks) elif self.check_type == CheckType.POLICY_3D: if self.failed_checks or self.skipped_checks: output_data += create_3d_policy_cli_output(self.failed_checks, self.skipped_checks) # type:ignore[arg-type] else: if self.check_type.lower().startswith(CheckType.SAST): output_data += colored(f"Source code files scanned: {summary.get(SOURCE_FILES_COUNT, -1)}, " f"Policies found: {summary.get(POLICY_COUNT, -1)}\n\n", "cyan") policies_errors: str = str(summary.get(POLICIES_ERRORS, "")) if policies_errors: output_data += colored(f"Policy parsing failures ({summary.get(POLICIES_ERRORS_COUNT)}):\n{policies_errors}\n\n", "red") if not is_quiet: for record in self.passed_checks: output_data += record.to_string(compact=is_compact, use_bc_ids=use_bc_ids) if self.failed_checks: OpenAi(api_key=openai_api_key).enhance_records(runner_type=self.check_type, records=self.failed_checks) for record in self.failed_checks: output_data += record.to_string(compact=is_compact, use_bc_ids=use_bc_ids) if not is_quiet: for record in self.skipped_checks: output_data += record.to_string(compact=is_compact, use_bc_ids=use_bc_ids) if not is_quiet: for file in self.parsing_errors: output_data += colored(f"Error parsing file {file}ֿ\n", "red") if created_baseline_path: output_data += colored( f"Created a checkov baseline file at {created_baseline_path}", "blue", ) if baseline: output_data += colored( f"Baseline analysis report using {baseline.path} - only new failed checks with respect to the baseline are reported", "blue", ) if summary_position == 'bottom': output_data += colored(message, "cyan") return output_data def _print_parsing_error_console(file: str) -> None: print(colored(f"Error parsing file {file}", "red")) def get_junit_xml_string(ts: list[TestSuite]) -> str: return to_xml_report_string(ts) def print_failed_github_md(self, use_bc_ids: bool = False) -> str: result = [] for record in self.failed_checks: result.append( [ record.get_output_id(use_bc_ids), record.file_path, record.resource, record.check_name, record.guideline, ] ) if result: table = tabulate( result, headers=["check_id", "file", "resource", "check_name", "guideline"], tablefmt="github", showindex=True, ) output_data = f"### {self.check_type} scan results:\n\n{table}\n\n---\n" return output_data else: return "\n\n---\n\n" def get_test_suite(self, properties: Optional[Dict[str, Any]] = None, use_bc_ids: bool = False) -> TestSuite: """Creates a test suite for the JUnit XML report""" test_cases = [] records = self.passed_checks + self.failed_checks + self.skipped_checks for record in records: severity = BcSeverities.NONE if record.severity: severity = record.severity.name if self.check_type == CheckType.SCA_PACKAGE: if record.check_name != SCA_PACKAGE_SCAN_CHECK_NAME: continue if not record.vulnerability_details: # this shouldn't normally happen logging.warning(f"Vulnerability check without details {record.file_path}") continue check_id = record.vulnerability_details["id"] test_name_detail = f"{record.vulnerability_details['package_name']}: {record.vulnerability_details['package_version']}" class_name = f"{record.file_path}.{record.vulnerability_details['package_name']}" else: check_id = record.bc_check_id if use_bc_ids else record.check_id test_name_detail = record.check_name class_name = f"{record.file_path}.{record.resource}" test_name = f"[{severity}][{check_id}] {test_name_detail}" test_case = TestCase(name=test_name, file=record.file_path, classname=class_name) if record.check_result["result"] == CheckResult.FAILED: test_case.add_failure_info( message=record.check_name, output=self._create_test_case_failure_output(record) ) if record.check_result["result"] == CheckResult.SKIPPED: if self.check_type == CheckType.SCA_PACKAGE: test_case.add_skipped_info(f"{check_id} skipped for {test_name_detail}") else: test_case.add_skipped_info(record.check_result.get("suppress_comment", "")) test_cases.append(test_case) test_suite = TestSuite(name=f"{self.check_type} scan", test_cases=test_cases, properties=properties) return test_suite def create_test_suite_properties_block(config: argparse.Namespace) -> Dict[str, Any]: """Creates a dictionary without 'None' values for the JUnit XML properties block""" properties = {k: v for k, v in config.__dict__.items() if v is not None} return properties def _create_test_case_failure_output(self, record: Record) -> str: """Creates the failure output for a JUnit XML test case IaC example: Resource: azurerm_network_security_rule.fail_rdp File: /main.tf: 71-83 Guideline: https://docs.bridgecrew.io/docs/bc_azr_networking_2 71 | resource "azurerm_network_security_rule" "fail_rdp" { 72 | resource_group_name = azurerm_resource_group.example.name 73 | network_security_group_name=azurerm_network_security_group.example_rdp.name 74 | name = "fail_security_rule" 75 | direction = "Inbound" 76 | access = "Allow" 77 | protocol = "TCP" 78 | source_port_range = "*" 79 | destination_port_range = "3389" 80 | source_address_prefix = "*" 81 | destination_address_prefix = "*" 82 | priority = 120 83 | } SCA example: Description: Django before 1.11.27, 2.x before 2.2.9, and 3.x before 3.0.1 allows account takeover. Link: https://nvd.nist.gov/vuln/detail/CVE-2019-19844 Published Date: 2019-12-18T20:15:00+01:00 Base Score: 9.8 Vector: CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H Risk Factors: ['Attack complexity: low', 'Attack vector: network', 'Critical severity', 'Has fix'] Resource: requirements.txt.django File: /requirements.txt: 0-0 0 | django: 1.2 """ failure_output = [] if self.check_type == CheckType.SCA_PACKAGE: if record.vulnerability_details: lowest_fixed_version = record.vulnerability_details.get('lowest_fixed_version') if lowest_fixed_version is not None: fix = lowest_fixed_version else: fixlist = record.vulnerability_details.get('fixed_versions') if fixlist is not None: fix = fixlist failure_output.extend( [ "", f"Description: {record.description}", f"Link: {record.vulnerability_details.get('link')}", f"Published Date: {record.vulnerability_details.get('published_date')}", f"Base Score: {record.vulnerability_details.get('cvss')}", f"Vector: {record.vulnerability_details.get('vector')}", f"Risk Factors: {record.vulnerability_details.get('risk_factors')}", "Fix Details:", f" Status: {record.vulnerability_details.get('status')}", f" Fixed Version: {fix}", ] ) else: # this shouldn't normally happen logging.warning(f"Vulnerability check without details {record.file_path}") failure_output.extend( [ "", f"Resource: {record.resource}", ] ) if record.file_path: file_line = f"File: {record.file_path}" if record.file_line_range: file_line += f": {record.file_line_range[0]}-{record.file_line_range[1]}" failure_output.append(file_line) if self.check_type != CheckType.SCA_PACKAGE: failure_output.append(f"Guideline: {record.guideline}") if record.code_block: failure_output.append("") failure_output.append(record._code_line_string(code_block=record.code_block, colorized=False)) return "\n".join(failure_output) def print_json(self) -> None: print(self.get_json()) def enrich_plan_report( report: "Report", enriched_resources: Dict[str, Dict[str, Any]] ) -> "Report": # This enriches reports with the appropriate filepath, line numbers, and codeblock for record in report.failed_checks: resource_raw_id = Report.get_plan_resource_raw_id(record.resource) enriched_resource = enriched_resources.get(resource_raw_id) if enriched_resource: record.file_path = enriched_resource["scanned_file"] record.file_line_range = enriched_resource["entity_lines_range"] record.code_block = enriched_resource["entity_code_lines"] return report def handle_skipped_checks( report: "Report", enriched_resources: Dict[str, Dict[str, Any]] ) -> "Report": module_address_len = len("module.") skip_records = [] for record in report.failed_checks: resource_raw_id = Report.get_plan_resource_raw_id(record.resource) resource_skips = enriched_resources.get(resource_raw_id, {}).get( "skipped_checks", [] ) for skip in resource_skips: if record.check_id in skip["id"]: # Mark for removal and add it as a skipped record. It is not safe to remove # the record from failed_checks immediately because we're iterating over it skip_records.append(record) record.check_result["result"] = CheckResult.SKIPPED record.check_result["suppress_comment"] = skip["suppress_comment"] report.add_record(record) if record.resource_address and record.resource_address.startswith("module."): module_path = record.resource_address[module_address_len:record.resource_address.index('.', module_address_len + 1)] module_enrichments = enriched_resources.get(module_path, {}) for module_skip in module_enrichments.get("skipped_checks", []): if record.check_id in module_skip["id"]: skip_records.append(record) record.check_result["result"] = CheckResult.SKIPPED record.check_result["suppress_comment"] = module_skip["suppress_comment"] report.add_record(record) for record in skip_records: if record in report.failed_checks: report.failed_checks.remove(record) return report def get_plan_resource_raw_id(resource_id: str) -> str: """ return the resource raw id without the modules and the indexes example: from resource_id='module.module_name.type.name[1]' return 'type.name' """ resource_raw_id = ".".join(resource_id.split(".")[-2:]) if '[' in resource_raw_id: resource_raw_id = resource_raw_id[:resource_raw_id.index('[')] return resource_raw_id def from_reduced_json(cls, json_report: dict[str, Any], check_type: str) -> Report: report = Report(check_type) report.image_cached_results = json_report['image_cached_results'] all_json_records = json_report["checks"]["passed_checks"] + \ json_report["checks"]["failed_checks"] + \ json_report["checks"]["skipped_checks"] for json_record in all_json_records: report.add_record( Record.from_reduced_json(json_record) ) return report def merge_reports(base_report: Report, report_to_merge: Report) -> None: base_report.passed_checks.extend(report_to_merge.passed_checks) base_report.failed_checks.extend(report_to_merge.failed_checks) base_report.skipped_checks.extend(report_to_merge.skipped_checks) base_report.parsing_errors.extend(report_to_merge.parsing_errors) base_report.image_cached_results.extend(report_to_merge.image_cached_results) base_report.resources.update(report_to_merge.resources) base_report.extra_resources.update(report_to_merge.extra_resources)
null
2,313
from __future__ import annotations import argparse import json import logging import os from collections.abc import Iterable from typing import List, Dict, Union, Any, Optional, TYPE_CHECKING, cast from colorama import init from junit_xml import TestCase, TestSuite, to_xml_report_string from tabulate import tabulate from termcolor import colored from checkov.common.bridgecrew.code_categories import CodeCategoryType from checkov.common.bridgecrew.severities import BcSeverities, Severity from checkov.common.bridgecrew.check_type import CheckType from checkov.common.models.enums import CheckResult, ErrorStatus from checkov.common.output.ai import OpenAi from checkov.common.typing import _ExitCodeThresholds, _ScaExitCodeThresholds from checkov.common.output.record import Record, SCA_PACKAGE_SCAN_CHECK_NAME from checkov.common.sast.consts import POLICIES_ERRORS, POLICIES_ERRORS_COUNT, SOURCE_FILES_COUNT, POLICY_COUNT from checkov.common.util.consts import PARSE_ERROR_FAIL_FLAG, S3_UPLOAD_DETAILS_MESSAGE from checkov.common.util.json_utils import CustomJSONEncoder from checkov.runner_filter import RunnerFilter from checkov.sca_package_2.output import create_cli_output as create_sca_package_cli_output_v2 from checkov.policies_3d.output import create_cli_output as create_3d_policy_cli_output from checkov.version import version class Report: def __init__(self, check_type: str): self.check_type = check_type self.passed_checks: list[Record] = [] self.failed_checks: list[Record] = [] self.skipped_checks: list[Record] = [] self.parsing_errors: list[str] = [] self.resources: set[str] = set() self.extra_resources: set[ExtraResource] = set() self.image_cached_results: List[dict[str, Any]] = [] self.error_status: ErrorStatus = ErrorStatus.SUCCESS def errors(self) -> Dict[str, List[str]]: return dict() def set_error_status(self, error_status: ErrorStatus) -> None: self.error_status = error_status def add_parsing_errors(self, errors: "Iterable[str]") -> None: for file in errors: self.add_parsing_error(file) def add_parsing_error(self, file: str) -> None: if file: self.parsing_errors.append(file) def add_resource(self, resource: str) -> None: self.resources.add(resource) def add_record(self, record: Record) -> None: if record.check_result["result"] == CheckResult.PASSED: self.passed_checks.append(record) if record.check_result["result"] == CheckResult.FAILED: self.failed_checks.append(record) if record.check_result["result"] == CheckResult.SKIPPED: self.skipped_checks.append(record) def get_summary(self) -> Dict[str, Union[int, str]]: return { "passed": len(self.passed_checks), "failed": len(self.failed_checks), "skipped": len(self.skipped_checks), "parsing_errors": len(self.parsing_errors), "resource_count": len(self.resources), "checkov_version": version, } def get_json(self) -> str: return json.dumps(self.get_dict(), indent=4, cls=CustomJSONEncoder) def get_all_records(self) -> List[Record]: return self.failed_checks + self.passed_checks + self.skipped_checks def get_dict(self, is_quiet: bool = False, url: str | None = None, full_report: bool = False, s3_setup_failed: bool = False, support_path: str | None = None) -> dict[str, Any]: if not url and not s3_setup_failed: url = "Add an api key '--bc-api-key <api-key>' to see more detailed insights via https://bridgecrew.cloud" elif s3_setup_failed: url = S3_UPLOAD_DETAILS_MESSAGE if is_quiet: return { "check_type": self.check_type, "results": { "failed_checks": [check.__dict__ for check in self.failed_checks] }, "summary": self.get_summary(), } if full_report: return { "check_type": self.check_type, "checks": { "passed_checks": [check.__dict__ for check in self.passed_checks], "failed_checks": [check.__dict__ for check in self.failed_checks], "skipped_checks": [check.__dict__ for check in self.skipped_checks] }, "image_cached_results": [res.__dict__ for res in self.image_cached_results] } else: result = { "check_type": self.check_type, "results": { "passed_checks": [check.__dict__ for check in self.passed_checks], "failed_checks": [check.__dict__ for check in self.failed_checks], "skipped_checks": [check.__dict__ for check in self.skipped_checks], "parsing_errors": list(self.parsing_errors), }, "summary": self.get_summary(), "url": url, } if support_path: result["support_path"] = support_path return result def get_exit_code(self, exit_code_thresholds: Union[_ExitCodeThresholds, _ScaExitCodeThresholds]) -> int: """ Returns the appropriate exit code depending on the flags that are passed in. :return: Exit code 0 or 1. """ hard_fail_on_parsing_errors = os.getenv(PARSE_ERROR_FAIL_FLAG, "false").lower() == 'true' logging.debug(f'In get_exit_code; exit code thresholds: {exit_code_thresholds}, hard_fail_on_parsing_errors: {hard_fail_on_parsing_errors}') if self.parsing_errors and hard_fail_on_parsing_errors: logging.debug('hard_fail_on_parsing_errors is True and there were parsing errors - returning 1') return 1 if not self.failed_checks: logging.debug('No failed checks in this report - returning 0') return 0 # we will have two different sets of logic in this method, determined by this variable. # if we are using enforcement rules, then there are two different sets of thresholds that apply for licenses and vulnerabilities # and we have to handle that throughout while processing the report # if we are not using enforcement rules, then we can combine licenses and vulnerabilities like normal and same as all other report types # this determination is made in runner_registry.get_fail_thresholds has_split_enforcement = CodeCategoryType.LICENSES in exit_code_thresholds hard_fail_threshold: Optional[Severity | Dict[str, Severity]] soft_fail: Optional[bool | Dict[str, bool]] if has_split_enforcement: sca_thresholds = cast(_ScaExitCodeThresholds, exit_code_thresholds) # these three are the same even in split enforcement rules generic_thresholds = cast(_ExitCodeThresholds, next(iter(sca_thresholds.values()))) soft_fail_on_checks = generic_thresholds['soft_fail_checks'] soft_fail_threshold = generic_thresholds['soft_fail_threshold'] hard_fail_on_checks = generic_thresholds['hard_fail_checks'] # these two can be different for licenses / vulnerabilities hard_fail_threshold = {category: thresholds['hard_fail_threshold'] for category, thresholds in sca_thresholds.items()} # type:ignore[index] # thinks it's an object, can't possibly be more clear soft_fail = {category: thresholds['soft_fail'] for category, thresholds in sca_thresholds.items()} # type:ignore[index] # thinks it's an object failed_checks_by_category = { CodeCategoryType.LICENSES: [fc for fc in self.failed_checks if '_LIC_' in fc.check_id], CodeCategoryType.VULNERABILITIES: [fc for fc in self.failed_checks if '_VUL_' in fc.check_id] } has_soft_fail_values = soft_fail_on_checks or soft_fail_threshold if all( not failed_checks_by_category[cast(CodeCategoryType, c)] or ( not has_soft_fail_values and not (hard_fail_threshold[c] or hard_fail_on_checks) and soft_fail[c] ) for c in sca_thresholds.keys() ): logging.debug( 'No failed checks, or soft_fail is True and soft_fail_on and hard_fail_on are empty for all SCA types - returning 0') return 0 if any( not has_soft_fail_values and not (hard_fail_threshold[c] or hard_fail_on_checks) and failed_checks_by_category[cast(CodeCategoryType, c)] for c in sca_thresholds.keys() ): logging.debug('There are failed checks and all soft/hard fail args are empty for one or more SCA reports - returning 1') return 1 else: non_sca_thresholds = cast(_ExitCodeThresholds, exit_code_thresholds) soft_fail_on_checks = non_sca_thresholds['soft_fail_checks'] soft_fail_threshold = non_sca_thresholds['soft_fail_threshold'] hard_fail_on_checks = non_sca_thresholds['hard_fail_checks'] hard_fail_threshold = non_sca_thresholds['hard_fail_threshold'] soft_fail = non_sca_thresholds['soft_fail'] has_soft_fail_values = soft_fail_on_checks or soft_fail_threshold has_hard_fail_values = hard_fail_threshold or hard_fail_on_checks if not has_soft_fail_values and not has_hard_fail_values and soft_fail: logging.debug('Soft_fail is True and soft_fail_on and hard_fail_on are empty - returning 0') return 0 elif not has_soft_fail_values and not has_hard_fail_values: logging.debug('There are failed checks and all soft/hard fail args are empty - returning 1') return 1 for failed_check in self.failed_checks: check_id = failed_check.check_id bc_check_id = failed_check.bc_check_id severity = failed_check.severity secret_validation_status = failed_check.validation_status if hasattr(failed_check, 'validation_status') else '' hf_threshold: Severity sf: bool if has_split_enforcement: category = CodeCategoryType.LICENSES if '_LIC_' in check_id else CodeCategoryType.VULNERABILITIES hard_fail_threshold = cast(Dict[str, Severity], hard_fail_threshold) hf_threshold = hard_fail_threshold[category] soft_fail = cast(Dict[str, bool], soft_fail) sf = soft_fail[category] else: hard_fail_threshold = cast(Severity, hard_fail_threshold) hf_threshold = hard_fail_threshold soft_fail = cast(bool, soft_fail) sf = soft_fail soft_fail_severity = severity and soft_fail_threshold and severity.level <= soft_fail_threshold.level hard_fail_severity = severity and hf_threshold and severity.level >= hf_threshold.level explicit_soft_fail = RunnerFilter.check_matches(check_id, bc_check_id, soft_fail_on_checks) explicit_hard_fail = RunnerFilter.check_matches(check_id, bc_check_id, hard_fail_on_checks) explicit_secrets_soft_fail = RunnerFilter.secret_validation_status_matches(secret_validation_status, soft_fail_on_checks) explicit_secrets_hard_fail = RunnerFilter.secret_validation_status_matches(secret_validation_status, hard_fail_on_checks) implicit_soft_fail = not explicit_hard_fail and not explicit_secrets_hard_fail and not soft_fail_on_checks and not soft_fail_threshold implicit_hard_fail = not explicit_soft_fail and not soft_fail_severity and not explicit_secrets_soft_fail if explicit_hard_fail or \ (hard_fail_severity and not explicit_soft_fail) or \ (implicit_hard_fail and not implicit_soft_fail and not sf): logging.debug(f'Check {check_id} (BC ID: {bc_check_id}, severity: {severity.level if severity else None} triggered hard fail - returning 1') return 1 logging.debug('No failed check triggered hard fail - returning 0') return 0 def is_empty(self, full: bool = False) -> bool: checks_count = ( len(self.passed_checks) + len(self.failed_checks) + len(self.skipped_checks) + len(self.parsing_errors) ) if full: checks_count += len(self.resources) + len(self.extra_resources) + len(self.image_cached_results) return checks_count == 0 def add_errors_to_output(self) -> str: ret_value = '' for error_title, errors_messages in self.errors.items(): ret_value += colored(f"Encountered {error_title} error - {len(errors_messages)} times\n\n", "red") return ret_value def print_console( self, is_quiet: bool = False, is_compact: bool = False, created_baseline_path: str | None = None, baseline: Baseline | None = None, use_bc_ids: bool = False, summary_position: str = 'top', openai_api_key: str | None = None, ) -> str: summary = self.get_summary() output_data = colored(f"{self.check_type} scan results:\n", "blue") if self.parsing_errors: message = "\nPassed checks: {}, Failed checks: {}, Skipped checks: {}, Parsing errors: {}\n\n".format( summary["passed"], summary["failed"], summary["skipped"], summary["parsing_errors"], ) else: if self.check_type == CheckType.SCA_PACKAGE or self.check_type.lower().startswith(CheckType.SAST): message = f"\nFailed checks: {summary['failed']}, Skipped checks: {summary['skipped']}\n\n" else: message = f"\nPassed checks: {summary['passed']}, Failed checks: {summary['failed']}, Skipped checks: {summary['skipped']}\n\n" if summary_position == 'top': output_data += colored(message, "cyan") # output for vulnerabilities is different if self.check_type in (CheckType.SCA_PACKAGE, CheckType.SCA_IMAGE): if self.failed_checks or self.skipped_checks: create_cli_output = create_sca_package_cli_output_v2 output_data += create_cli_output(self.check_type == CheckType.SCA_PACKAGE, self.failed_checks, self.skipped_checks) elif self.check_type == CheckType.POLICY_3D: if self.failed_checks or self.skipped_checks: output_data += create_3d_policy_cli_output(self.failed_checks, self.skipped_checks) # type:ignore[arg-type] else: if self.check_type.lower().startswith(CheckType.SAST): output_data += colored(f"Source code files scanned: {summary.get(SOURCE_FILES_COUNT, -1)}, " f"Policies found: {summary.get(POLICY_COUNT, -1)}\n\n", "cyan") policies_errors: str = str(summary.get(POLICIES_ERRORS, "")) if policies_errors: output_data += colored(f"Policy parsing failures ({summary.get(POLICIES_ERRORS_COUNT)}):\n{policies_errors}\n\n", "red") if not is_quiet: for record in self.passed_checks: output_data += record.to_string(compact=is_compact, use_bc_ids=use_bc_ids) if self.failed_checks: OpenAi(api_key=openai_api_key).enhance_records(runner_type=self.check_type, records=self.failed_checks) for record in self.failed_checks: output_data += record.to_string(compact=is_compact, use_bc_ids=use_bc_ids) if not is_quiet: for record in self.skipped_checks: output_data += record.to_string(compact=is_compact, use_bc_ids=use_bc_ids) if not is_quiet: for file in self.parsing_errors: output_data += colored(f"Error parsing file {file}ֿ\n", "red") if created_baseline_path: output_data += colored( f"Created a checkov baseline file at {created_baseline_path}", "blue", ) if baseline: output_data += colored( f"Baseline analysis report using {baseline.path} - only new failed checks with respect to the baseline are reported", "blue", ) if summary_position == 'bottom': output_data += colored(message, "cyan") return output_data def _print_parsing_error_console(file: str) -> None: print(colored(f"Error parsing file {file}", "red")) def get_junit_xml_string(ts: list[TestSuite]) -> str: return to_xml_report_string(ts) def print_failed_github_md(self, use_bc_ids: bool = False) -> str: result = [] for record in self.failed_checks: result.append( [ record.get_output_id(use_bc_ids), record.file_path, record.resource, record.check_name, record.guideline, ] ) if result: table = tabulate( result, headers=["check_id", "file", "resource", "check_name", "guideline"], tablefmt="github", showindex=True, ) output_data = f"### {self.check_type} scan results:\n\n{table}\n\n---\n" return output_data else: return "\n\n---\n\n" def get_test_suite(self, properties: Optional[Dict[str, Any]] = None, use_bc_ids: bool = False) -> TestSuite: """Creates a test suite for the JUnit XML report""" test_cases = [] records = self.passed_checks + self.failed_checks + self.skipped_checks for record in records: severity = BcSeverities.NONE if record.severity: severity = record.severity.name if self.check_type == CheckType.SCA_PACKAGE: if record.check_name != SCA_PACKAGE_SCAN_CHECK_NAME: continue if not record.vulnerability_details: # this shouldn't normally happen logging.warning(f"Vulnerability check without details {record.file_path}") continue check_id = record.vulnerability_details["id"] test_name_detail = f"{record.vulnerability_details['package_name']}: {record.vulnerability_details['package_version']}" class_name = f"{record.file_path}.{record.vulnerability_details['package_name']}" else: check_id = record.bc_check_id if use_bc_ids else record.check_id test_name_detail = record.check_name class_name = f"{record.file_path}.{record.resource}" test_name = f"[{severity}][{check_id}] {test_name_detail}" test_case = TestCase(name=test_name, file=record.file_path, classname=class_name) if record.check_result["result"] == CheckResult.FAILED: test_case.add_failure_info( message=record.check_name, output=self._create_test_case_failure_output(record) ) if record.check_result["result"] == CheckResult.SKIPPED: if self.check_type == CheckType.SCA_PACKAGE: test_case.add_skipped_info(f"{check_id} skipped for {test_name_detail}") else: test_case.add_skipped_info(record.check_result.get("suppress_comment", "")) test_cases.append(test_case) test_suite = TestSuite(name=f"{self.check_type} scan", test_cases=test_cases, properties=properties) return test_suite def create_test_suite_properties_block(config: argparse.Namespace) -> Dict[str, Any]: """Creates a dictionary without 'None' values for the JUnit XML properties block""" properties = {k: v for k, v in config.__dict__.items() if v is not None} return properties def _create_test_case_failure_output(self, record: Record) -> str: """Creates the failure output for a JUnit XML test case IaC example: Resource: azurerm_network_security_rule.fail_rdp File: /main.tf: 71-83 Guideline: https://docs.bridgecrew.io/docs/bc_azr_networking_2 71 | resource "azurerm_network_security_rule" "fail_rdp" { 72 | resource_group_name = azurerm_resource_group.example.name 73 | network_security_group_name=azurerm_network_security_group.example_rdp.name 74 | name = "fail_security_rule" 75 | direction = "Inbound" 76 | access = "Allow" 77 | protocol = "TCP" 78 | source_port_range = "*" 79 | destination_port_range = "3389" 80 | source_address_prefix = "*" 81 | destination_address_prefix = "*" 82 | priority = 120 83 | } SCA example: Description: Django before 1.11.27, 2.x before 2.2.9, and 3.x before 3.0.1 allows account takeover. Link: https://nvd.nist.gov/vuln/detail/CVE-2019-19844 Published Date: 2019-12-18T20:15:00+01:00 Base Score: 9.8 Vector: CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H Risk Factors: ['Attack complexity: low', 'Attack vector: network', 'Critical severity', 'Has fix'] Resource: requirements.txt.django File: /requirements.txt: 0-0 0 | django: 1.2 """ failure_output = [] if self.check_type == CheckType.SCA_PACKAGE: if record.vulnerability_details: lowest_fixed_version = record.vulnerability_details.get('lowest_fixed_version') if lowest_fixed_version is not None: fix = lowest_fixed_version else: fixlist = record.vulnerability_details.get('fixed_versions') if fixlist is not None: fix = fixlist failure_output.extend( [ "", f"Description: {record.description}", f"Link: {record.vulnerability_details.get('link')}", f"Published Date: {record.vulnerability_details.get('published_date')}", f"Base Score: {record.vulnerability_details.get('cvss')}", f"Vector: {record.vulnerability_details.get('vector')}", f"Risk Factors: {record.vulnerability_details.get('risk_factors')}", "Fix Details:", f" Status: {record.vulnerability_details.get('status')}", f" Fixed Version: {fix}", ] ) else: # this shouldn't normally happen logging.warning(f"Vulnerability check without details {record.file_path}") failure_output.extend( [ "", f"Resource: {record.resource}", ] ) if record.file_path: file_line = f"File: {record.file_path}" if record.file_line_range: file_line += f": {record.file_line_range[0]}-{record.file_line_range[1]}" failure_output.append(file_line) if self.check_type != CheckType.SCA_PACKAGE: failure_output.append(f"Guideline: {record.guideline}") if record.code_block: failure_output.append("") failure_output.append(record._code_line_string(code_block=record.code_block, colorized=False)) return "\n".join(failure_output) def print_json(self) -> None: print(self.get_json()) def enrich_plan_report( report: "Report", enriched_resources: Dict[str, Dict[str, Any]] ) -> "Report": # This enriches reports with the appropriate filepath, line numbers, and codeblock for record in report.failed_checks: resource_raw_id = Report.get_plan_resource_raw_id(record.resource) enriched_resource = enriched_resources.get(resource_raw_id) if enriched_resource: record.file_path = enriched_resource["scanned_file"] record.file_line_range = enriched_resource["entity_lines_range"] record.code_block = enriched_resource["entity_code_lines"] return report def handle_skipped_checks( report: "Report", enriched_resources: Dict[str, Dict[str, Any]] ) -> "Report": module_address_len = len("module.") skip_records = [] for record in report.failed_checks: resource_raw_id = Report.get_plan_resource_raw_id(record.resource) resource_skips = enriched_resources.get(resource_raw_id, {}).get( "skipped_checks", [] ) for skip in resource_skips: if record.check_id in skip["id"]: # Mark for removal and add it as a skipped record. It is not safe to remove # the record from failed_checks immediately because we're iterating over it skip_records.append(record) record.check_result["result"] = CheckResult.SKIPPED record.check_result["suppress_comment"] = skip["suppress_comment"] report.add_record(record) if record.resource_address and record.resource_address.startswith("module."): module_path = record.resource_address[module_address_len:record.resource_address.index('.', module_address_len + 1)] module_enrichments = enriched_resources.get(module_path, {}) for module_skip in module_enrichments.get("skipped_checks", []): if record.check_id in module_skip["id"]: skip_records.append(record) record.check_result["result"] = CheckResult.SKIPPED record.check_result["suppress_comment"] = module_skip["suppress_comment"] report.add_record(record) for record in skip_records: if record in report.failed_checks: report.failed_checks.remove(record) return report def get_plan_resource_raw_id(resource_id: str) -> str: """ return the resource raw id without the modules and the indexes example: from resource_id='module.module_name.type.name[1]' return 'type.name' """ resource_raw_id = ".".join(resource_id.split(".")[-2:]) if '[' in resource_raw_id: resource_raw_id = resource_raw_id[:resource_raw_id.index('[')] return resource_raw_id def from_reduced_json(cls, json_report: dict[str, Any], check_type: str) -> Report: report = Report(check_type) report.image_cached_results = json_report['image_cached_results'] all_json_records = json_report["checks"]["passed_checks"] + \ json_report["checks"]["failed_checks"] + \ json_report["checks"]["skipped_checks"] for json_record in all_json_records: report.add_record( Record.from_reduced_json(json_record) ) return report class Record: def __init__( self, check_id: str, check_name: str, check_result: _CheckResult, code_block: List[Tuple[int, str]], file_path: str, file_line_range: List[int], resource: str, evaluations: Optional[Dict[str, Any]], check_class: str, file_abs_path: str, entity_tags: Optional[Dict[str, str]] = None, caller_file_path: Optional[str] = None, caller_file_line_range: tuple[int, int] | None = None, bc_check_id: Optional[str] = None, resource_address: Optional[str] = None, severity: Optional[Severity] = None, bc_category: Optional[str] = None, benchmarks: dict[str, list[str]] | None = None, description: Optional[str] = None, short_description: Optional[str] = None, vulnerability_details: Optional[Dict[str, Any]] = None, connected_node: Optional[Dict[str, Any]] = None, details: Optional[List[str]] = None, check_len: int | None = None, definition_context_file_path: Optional[str] = None ) -> None: """ :param evaluations: A dict with the key being the variable name, value being a dict containing: - 'var_file' - 'value' - 'definitions', a list of dicts which contain 'definition_expression' """ self.check_id = check_id self.bc_check_id = bc_check_id self.check_name = check_name self.check_result = check_result self.code_block = code_block self.file_path = file_path self.file_abs_path = file_abs_path self.repo_file_path = self._determine_repo_file_path(file_abs_path) self.file_line_range = file_line_range self.resource = resource self.evaluations = evaluations self.check_class = check_class self.fixed_definition = None self.entity_tags = entity_tags self.caller_file_path = caller_file_path # When created from a module self.caller_file_line_range = caller_file_line_range # When created from a module self.resource_address = resource_address self.severity = severity self.bc_category = bc_category self.benchmarks = benchmarks self.description = description # used by SARIF output self.short_description = short_description # used by SARIF and GitLab SAST output self.vulnerability_details = vulnerability_details # Stores package vulnerability details self.connected_node = connected_node self.guideline: str | None = None self.details: List[str] = details or [] self.check_len = check_len self.definition_context_file_path = definition_context_file_path def _determine_repo_file_path(file_path: Union[str, "os.PathLike[str]"]) -> str: # matches file paths given in the BC platform and should always be a unix path repo_file_path = Path(file_path) if CURRENT_LOCAL_DRIVE == repo_file_path.drive: return convert_to_unix_path(f"/{os.path.relpath(repo_file_path)}").replace("/..", "") return f"/{'/'.join(repo_file_path.parts[1:])}" def set_guideline(self, guideline: Optional[str]) -> None: self.guideline = guideline def _trim_special_chars(expression: str) -> str: return "".join(re.findall(re.compile(r"[^ ${\}]+"), expression)) def _is_expression_in_code_lines(expression: str, code_block: List[Tuple[int, str]]) -> bool: stripped_expression = Record._trim_special_chars(expression) return any(stripped_expression in Record._trim_special_chars(line) for (_, line) in code_block) def _code_line_string(code_block: List[Tuple[int, str]], colorized: bool = True) -> str: code_output = [] color_codes = (Fore.WHITE if colorized else "", Fore.YELLOW if colorized else "") last_line_number_len = len(str(code_block[-1][0])) if len(code_block) >= OUTPUT_CODE_LINE_LIMIT: return f'\t\t{color_codes[1]}Code lines for this resource are too many. ' \ f'Please use IDE of your choice to review the file.' for line_num, line in code_block: spaces = " " * (last_line_number_len - len(str(line_num))) if line.lstrip().startswith("#"): code_output.append(f"\t\t{color_codes[0]}{line_num}{spaces} | {line}") elif line.lstrip() == PLACEHOLDER_LINE: code_output.append(f"\t\t{line}") else: code_output.append(f"\t\t{color_codes[0]}{line_num}{spaces} | {color_codes[1]}{line}") return "".join(code_output) def get_guideline_string(guideline: Optional[str]) -> str: if guideline: return ( "\tGuide: " + Style.BRIGHT + colored(f"{guideline}\n", "blue", attrs=["underline"]) + Style.RESET_ALL ) return '' def get_code_lines_string(code_block: List[Tuple[int, str]]) -> str: if code_block: return "\n{}\n".format("".join([Record._code_line_string(code_block, not (ANSI_COLORS_DISABLED))])) return '' def get_details_string(details: List[str]) -> str: if details: detail_buffer = [colored(f"\tDetails: {details[0]}\n", "blue")] for t in details[1:]: detail_buffer.append(colored(f"\t {t}\n", "blue")) return "".join(detail_buffer) return '' def get_caller_file_details_string(caller_file_path: Optional[str], caller_file_line_range: Optional[Tuple[int, int]]) -> str: if caller_file_path and caller_file_line_range: return colored( "\tCalling File: {}:{}\n".format( caller_file_path, "-".join([str(x) for x in caller_file_line_range]) ), "magenta", ) return '' def get_evaluation_string(evaluations: Optional[Dict[str, Any]], code_block: List[Tuple[int, str]]) -> str: if evaluations: for (var_name, var_evaluations) in evaluations.items(): var_file = var_evaluations["var_file"] var_definitions = var_evaluations["definitions"] for definition_obj in var_definitions: definition_expression = definition_obj["definition_expression"] if Record._is_expression_in_code_lines(definition_expression, code_block): return colored( f'\tVariable {colored(var_name, "yellow")} (of {var_file}) evaluated to value "{colored(var_evaluations["value"], "yellow")}" ' f'in expression: {colored(definition_obj["definition_name"] + " = ", "yellow")}{colored(definition_obj["definition_expression"], "yellow")}\n', "white", ) return '' def to_string(self, compact: bool = False, use_bc_ids: bool = False) -> str: status = "" status_color = "white" suppress_comment = "" if self.check_result["result"] == CheckResult.PASSED: status = CheckResult.PASSED.name status_color = "green" elif self.check_result["result"] == CheckResult.FAILED: status = CheckResult.FAILED.name status_color = "red" elif self.check_result["result"] == CheckResult.SKIPPED: status = CheckResult.SKIPPED.name status_color = "blue" suppress_comment = "\tSuppress comment: {}\n".format(self.check_result.get("suppress_comment", "")) check_message = colored('Check: {}: "{}"\n'.format(self.get_output_id(use_bc_ids), self.check_name), "white") guideline_message = self.get_guideline_string(self.guideline) severity_message = f'\tSeverity: {self.severity.name}\n' if self.severity else '' file_details = colored( "\tFile: {}:{}\n".format(self.file_path, "-".join([str(x) for x in self.file_line_range])), "magenta" ) code_lines = self.get_code_lines_string(self.code_block) detail = self.get_details_string(self.details) caller_file_details = self.get_caller_file_details_string(self.caller_file_path, self.caller_file_line_range) evaluation_message = self.get_evaluation_string(self.evaluations, self.code_block) status_message = colored("\t{} for resource: {}\n".format(status, self.resource), status_color) if self.check_result["result"] == CheckResult.FAILED and code_lines and not compact: return f"{check_message}{status_message}{severity_message}{detail}{file_details}{caller_file_details}{guideline_message}{code_lines}{evaluation_message}" if self.check_result["result"] == CheckResult.SKIPPED: return f"{check_message}{status_message}{severity_message}{suppress_comment}{detail}{file_details}{caller_file_details}{guideline_message}" else: return f"{check_message}{status_message}{severity_message}{detail}{file_details}{caller_file_details}{evaluation_message}{guideline_message}" def __str__(self) -> str: return self.to_string() def get_output_id(self, use_bc_ids: bool) -> str: return self.bc_check_id if self.bc_check_id and use_bc_ids else self.check_id def get_unique_string(self) -> str: return f"{self.check_id}.{self.file_abs_path}.{self.file_line_range}.{self.resource}" def from_reduced_json(cls, record_json: dict[str, Any]) -> Record: return Record( check_id=record_json['check_id'], bc_check_id=record_json['bc_check_id'], check_name=record_json['check_name'], check_result=record_json['check_result'], code_block=record_json['code_block'], file_path=record_json['file_path'], file_line_range=record_json['file_line_range'], resource=record_json['resource'], evaluations=record_json.get('evaluations'), check_class='', file_abs_path=record_json['file_abs_path'], severity=record_json.get('severity') ) def remove_duplicate_results(report: Report) -> Report: def dedupe_records(origin_records: list[Record]) -> list[Record]: unique_records: Dict[str, Record] = {} for record in origin_records: record_hash = record.get_unique_string() unique_records[record_hash] = record return list(unique_records.values()) report.passed_checks = dedupe_records(report.passed_checks) report.failed_checks = dedupe_records(report.failed_checks) return report
null
2,314
from __future__ import annotations from dataclasses import dataclass, field from checkov.common.bridgecrew.severities import Severities from checkov.common.output.record import DEFAULT_SEVERITY def is_raw_formatted(licenses: str) -> bool: return '","' in licenses
null
2,315
from __future__ import annotations from dataclasses import dataclass, field from checkov.common.bridgecrew.severities import Severities from checkov.common.output.record import DEFAULT_SEVERITY UNKNOWN_LICENSE = 'Unknown' def format_string_to_licenses(licenses_str: str) -> list[str]: if licenses_str == UNKNOWN_LICENSE: return [licenses_str] elif licenses_str: # remove first and last quotes licenses_str = licenses_str[1:-1] if licenses_str.startswith('"') and licenses_str.endswith( '"') else licenses_str license_lst = licenses_str.split('","') return license_lst else: return []
null
2,316
from __future__ import annotations import concurrent import hashlib from typing import Any, Callable import concurrent.futures def calculate_hash(data: Any) -> str: sha256 = hashlib.sha256(str(data).encode("utf-8")) return sha256.hexdigest()
null
2,317
from __future__ import annotations import concurrent import hashlib from typing import Any, Callable import concurrent.futures def join_trimmed_strings(char_to_join: str, str_lst: list[str], num_to_trim: int) -> str: return char_to_join.join(str_lst[: len(str_lst) - num_to_trim])
null
2,318
from __future__ import annotations import concurrent import hashlib from typing import Any, Callable import concurrent.futures def run_function_multithreaded( func: Callable[..., Any], data: list[list[Any]], max_group_size: int, num_of_workers: int | None = None ) -> None: groups_of_data = [data[i : i + max_group_size] for i in range(0, len(data), max_group_size)] if not num_of_workers: num_of_workers = len(groups_of_data) if num_of_workers > 0: with concurrent.futures.ThreadPoolExecutor(max_workers=num_of_workers) as executor: futures = {executor.submit(func, data_group): data_group for data_group in groups_of_data} wait_result = concurrent.futures.wait(futures) if wait_result.not_done: raise Exception(f"failed to perform {func.__name__}") for future in futures: try: future.result() except Exception: raise
null
2,319
from __future__ import annotations import concurrent import hashlib from typing import Any, Callable import concurrent.futures def is_include_dup_dynamic(key: str, list_keys: list[str]) -> bool: return f"dynamic.{key.split('.')[0]}" not in list_keys def filter_sub_keys(key_list: list[str]) -> list[str]: filtered_key_list = [] for key in key_list: if not any(other_key != key and other_key.startswith(key) for other_key in key_list) and is_include_dup_dynamic(key, key_list): filtered_key_list.append(key) return filtered_key_list
null
2,320
from dataclasses import dataclass from enum import Enum from typing import List, Any def props(cls: Any) -> List[str]: return [i for i in cls.__dict__.keys() if i[:1] != "_"]
null
2,321
from __future__ import annotations import json import logging from collections.abc import Iterable from typing import Any, TYPE_CHECKING import yaml from termcolor import colored from checkov.common.graph.graph_builder import CustomAttributes from checkov.common.resource_code_logger_filter import add_resource_code_filter_to_logger from checkov.common.util.env_vars_config import env_vars_config env_vars_config = EnvVarsConfig() def graph_check(check_id: str, check_name: str) -> None: if not env_vars_config.EXPERIMENTAL_GRAPH_DEBUG: return print(f'\nEvaluating graph policy: "{check_id}" - "{check_name}"')
null
2,322
from __future__ import annotations import json import logging from collections.abc import Iterable from typing import Any, TYPE_CHECKING import yaml from termcolor import colored from checkov.common.graph.graph_builder import CustomAttributes from checkov.common.resource_code_logger_filter import add_resource_code_filter_to_logger from checkov.common.util.env_vars_config import env_vars_config def _create_attribute_block( resource_types: Iterable[str], attribute: str | None, operator: str, value: str | list[str] | None ) -> dict[str, Any]: env_vars_config = EnvVarsConfig() def attribute_block( resource_types: Iterable[str], attribute: str | None, operator: str, value: str | list[str] | None, resource: dict[str, Any], status: str, ) -> None: if not env_vars_config.EXPERIMENTAL_GRAPH_DEBUG: return attribute_block_conf = _create_attribute_block( resource_types=resource_types, attribute=attribute, operator=operator, value=value ) color = "green" if status == "passed" else "red" print("\nEvaluated block:\n") print(colored(yaml.dump([attribute_block_conf], sort_keys=False), "blue")) print("and got:") print(colored(f'\nResource "{resource[CustomAttributes.ID]}" {status}:', color)) print(colored(json.dumps(resource[CustomAttributes.CONFIG], indent=2), "yellow"))
null
2,323
from __future__ import annotations import json import logging from collections.abc import Iterable from typing import Any, TYPE_CHECKING import yaml from termcolor import colored from checkov.common.graph.graph_builder import CustomAttributes from checkov.common.resource_code_logger_filter import add_resource_code_filter_to_logger from checkov.common.util.env_vars_config import env_vars_config def _create_connection_block( resource_types: Iterable[str], connected_resource_types: Iterable[str], operator: str ) -> dict[str, Any]: env_vars_config = EnvVarsConfig() def connection_block( resource_types: Iterable[str], connected_resource_types: Iterable[str], operator: str, passed_resources: list[dict[str, Any]], failed_resources: list[dict[str, Any]], ) -> None: if not env_vars_config.EXPERIMENTAL_GRAPH_DEBUG: return connection_block_conf = _create_connection_block( resource_types=resource_types, connected_resource_types=connected_resource_types, operator=operator, ) passed_resources_str = '", "'.join(resource[CustomAttributes.ID] for resource in passed_resources) failed_resources_str = '", "'.join(resource[CustomAttributes.ID] for resource in failed_resources) print("\nEvaluated blocks:\n") print(colored(yaml.dump([connection_block_conf], sort_keys=False), "blue")) print("and got:\n") print(colored(f'Passed resources: "{passed_resources_str}"', "green")) print(colored(f'Failed resources: "{failed_resources_str}"', "red"))
null
2,324
from __future__ import annotations import json import logging from collections.abc import Iterable from typing import Any, TYPE_CHECKING import yaml from termcolor import colored from checkov.common.graph.graph_builder import CustomAttributes from checkov.common.resource_code_logger_filter import add_resource_code_filter_to_logger from checkov.common.util.env_vars_config import env_vars_config logger = logging.getLogger(__name__) def resource_types(resource_types: Iterable[str], resource_count: int, operator: str) -> None: def _create_attribute_block( resource_types: Iterable[str], attribute: str | None, operator: str, value: str | list[str] | None ) -> dict[str, Any]: def _create_connection_block( resource_types: Iterable[str], connected_resource_types: Iterable[str], operator: str ) -> dict[str, Any]: def _create_filter_block(attribute: str | None, operator: str, value: str | list[str]) -> dict[str, Any]: env_vars_config = EnvVarsConfig() class BaseSolver: def __init__(self, solver_type: SolverType) -> None: def get_operation(self, *args: Any, **kwargs: Any) -> Any: def _get_operation(self, *args: Any, **kwargs: Any) -> Any: def run(self, graph_connector: DiGraph) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]], List[Dict[str, Any]]]: def resource_type_pred(v: Dict[str, Any], resource_types: List[str]) -> bool: class BaseAttributeSolver(BaseSolver): def __init__( self, resource_types: List[str], attribute: Optional[str], value: Any, is_jsonpath_check: bool = False ) -> None: def run(self, graph_connector: LibraryGraph) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]], List[Dict[str, Any]]]: def get_operation(self, vertex: Dict[str, Any]) -> Optional[bool]: def _get_operation(self, vertex: Dict[str, Any], attribute: Optional[str]) -> bool: def _process_node( self, data: Dict[str, Any], passed_vartices: List[Dict[str, Any]], failed_vertices: List[Dict[str, Any]], unknown_vertices: List[Dict[str, Any]] ) -> None: def _evaluate_attribute_matches( self, vertex: dict[str, Any], attribute_matches: list[str], filtered_attribute_matches: list[str] ) -> bool | None: def get_attribute_matches(self, vertex: Dict[str, Any]) -> List[str]: def get_attribute_patterns(attribute: str) -> Tuple[Pattern[str], Pattern[str]]: def _is_variable_dependant(value: Any, source: str) -> bool: def _render_json_str(value_to_check: Any, attr: str, vertex: Dict[str, Any]) -> Any: def _get_cached_jsonpath_statement(self, statement: str) -> JSONPath: class BaseComplexSolver(BaseSolver): def __init__(self, solvers: List[BaseSolver], resource_types: List[str]) -> None: def _get_operation(self, *args: Any, **kwargs: Any) -> Any: def _get_negative_op(self, *args: Any) -> Any: def get_operation(self, vertex: Dict[str, Any]) -> Optional[bool]: def run(self, graph_connector: LibraryGraph) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]], List[Dict[str, Any]]]: class BaseConnectionSolver(BaseSolver): def __init__( self, resource_types: List[str], connected_resources_types: List[str], vertices_under_resource_types: Optional[List[Dict[str, Any]]] = None, vertices_under_connected_resources_types: Optional[List[Dict[str, Any]]] = None, ) -> None: def run(self, graph_connector: LibraryGraph) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]], List[Dict[str, Any]]]: def is_associated_edge(self, origin_type: str | None, destination_type: str | None) -> bool: def is_associated_vertex(self, vertex_type: str) -> bool: def set_vertices(self, graph_connector: LibraryGraph, exclude_vertices: List[Dict[str, Any]], unknown_vertices: List[Dict[str, Any]]) -> None: def reduce_graph_by_target_types(self, graph_connector: LibraryGraph) -> LibraryGraph: def populate_checks_results(self, origin_attributes: Dict[str, Any], destination_attributes: Dict[str, Any], passed: List[Dict[str, Any]], failed: List[Dict[str, Any]], unknown: List[Dict[str, Any]]) -> None: def get_operation(self, graph_connector: LibraryGraph) -> \ Tuple[List[Dict[str, Any]], List[Dict[str, Any]], List[Dict[str, Any]]]: def _get_operation(self, *args: Any, **kwargs: Any) -> Any: class ComplexConnectionSolver(BaseConnectionSolver): def __init__(self, solvers: Optional[List[BaseSolver]], operator: str) -> None: def get_check_identifier(check: Dict[str, Any]) -> Tuple[str, str, Optional[Any]]: def filter_duplicates(checks: List[Dict[str, Any]]) -> List[Dict[str, Any]]: def filter_results( self, passed: List[Dict[str, Any]], failed: List[Dict[str, Any]], unknown: List[Dict[str, Any]] ) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]], List[Dict[str, Any]]]: def get_sorted_connection_solvers(self) -> List[BaseConnectionSolver]: def run_attribute_solvers(self, graph_connector: LibraryGraph) -> \ Tuple[List[Dict[str, Any]], List[Dict[str, Any]], List[Dict[str, Any]]]: class BaseFilterSolver(BaseSolver): def __init__(self, resource_types: List[str], attribute: Optional[str], value: Any) -> None: def get_operation(self, *args: Any, **kwargs: Any) -> bool: def _get_operation(self, *args: Any, **kwargs: Any) -> Callable[..., bool]: def run(self, graph_connector: LibraryGraph) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]], List[Dict[str, Any]]]: def complex_connection_block( solvers: list[BaseSolver], operator: str, passed_resources: list[dict[str, Any]], failed_resources: list[dict[str, Any]], ) -> None: if not env_vars_config.EXPERIMENTAL_GRAPH_DEBUG: return # to prevent circular dependencies from checkov.common.checks_infra.solvers.attribute_solvers.base_attribute_solver import BaseAttributeSolver from checkov.common.checks_infra.solvers.complex_solvers.base_complex_solver import BaseComplexSolver from checkov.common.checks_infra.solvers.connections_solvers.base_connection_solver import BaseConnectionSolver from checkov.common.checks_infra.solvers.connections_solvers.complex_connection_solver import ( ComplexConnectionSolver, ) from checkov.common.checks_infra.solvers.filter_solvers.base_filter_solver import BaseFilterSolver complex_connection_block = [] for solver in solvers: if isinstance(solver, BaseAttributeSolver): block = _create_attribute_block( resource_types=solver.resource_types, attribute=solver.attribute, operator=solver.operator, value=solver.value, ) elif isinstance(solver, BaseFilterSolver): block = _create_filter_block(attribute=solver.attribute, operator=solver.operator, value=solver.value) elif isinstance(solver, (ComplexConnectionSolver, BaseComplexSolver)): # ComplexConnectionSolver check needs to be before BaseConnectionSolver, because it is a subclass block = {solver.operator: ["..." for _ in solver.solvers]} elif isinstance(solver, BaseConnectionSolver): block = _create_connection_block( resource_types=solver.resource_types, connected_resource_types=solver.connected_resources_types, operator=solver.operator, ) else: logger.info(f"Unsupported solver type {type(solver)} found") continue complex_connection_block.append(block) passed_resources_str = '", "'.join(resource[CustomAttributes.ID] for resource in passed_resources) failed_resources_str = '", "'.join(resource[CustomAttributes.ID] for resource in failed_resources) print("\nEvaluated blocks:\n") print(colored(yaml.dump([{operator: complex_connection_block}], sort_keys=False), "blue")) print("and got:\n") print(colored(f'Passed resources: "{passed_resources_str}"', "green")) print(colored(f'Failed resources: "{failed_resources_str}"', "red"))
null
2,325
from __future__ import annotations import asyncio import logging import os from collections.abc import Sequence, Iterable from pathlib import Path from typing import Any, TYPE_CHECKING from aiomultiprocess import Pool from checkov.common.bridgecrew.vulnerability_scanning.integrations.package_scanning import PackageScanningIntegration async def _report_results_to_bridgecrew_async( scan_results: Iterable[dict[str, Any]], bc_integration: BcPlatformIntegration, bc_api_key: str, ) -> Sequence[int]: package_scanning_int = PackageScanningIntegration() args = [(result, bc_integration, bc_api_key, Path(result["repository"])) for result in scan_results] if os.getenv("PYCHARM_HOSTED") == "1": # PYCHARM_HOSTED env variable equals 1 when running via Pycharm. # it avoids us from crashing, which happens when using multiprocessing via Pycharm's debug-mode logging.warning("reporting the results in sequence for avoiding crashing when running via Pycharm") exit_codes = [] for curr_arg in args: exit_codes.append(await package_scanning_int.report_results_async(*curr_arg)) else: async with Pool() as pool: exit_codes = await pool.starmap(package_scanning_int.report_results_async, args) return exit_codes class BcPlatformIntegration: def __init__(self) -> None: self.clean() def clean(self) -> None: self.bc_api_key = read_key() self.s3_client: S3Client | None = None self.bucket: str | None = None self.credentials: dict[str, str] | None = None self.repo_path: str | None = None self.support_bucket: str | None = None self.support_repo_path: str | None = None self.repo_id: str | None = None self.repo_branch: str | None = None self.skip_fixes = False # even though we removed the CLI flag, this gets set so we know whether this is a fix run (IDE) or not (normal CLI) self.skip_download = False self.source_id: str | None = None self.bc_source: SourceType | None = None self.bc_source_version: str | None = None self.timestamp: str | None = None self.scan_reports: list[Report] = [] self.bc_api_url = normalize_bc_url(os.getenv('BC_API_URL')) self.prisma_api_url = normalize_prisma_url(os.getenv('PRISMA_API_URL') or 'https://api0.prismacloud.io') self.prisma_policies_url: str | None = None self.prisma_policy_filters_url: str | None = None self.custom_auth_headers: dict[str, str] = {} self.setup_api_urls() self.customer_run_config_response = None self.runtime_run_config_response = None self.prisma_policies_response = None self.public_metadata_response = None self.use_s3_integration = False self.s3_setup_failed = False self.platform_integration_configured = False self.http: urllib3.PoolManager | urllib3.ProxyManager | None = None self.http_timeout = urllib3.Timeout(connect=REQUEST_CONNECT_TIMEOUT, read=REQUEST_READ_TIMEOUT) self.http_retry = urllib3.Retry( REQUEST_RETRIES, redirect=3, status_forcelist=REQUEST_STATUS_CODES_RETRY, allowed_methods=REQUEST_METHODS_TO_RETRY ) self.bc_skip_mapping = False self.cicd_details: _CicdDetails = {} self.support_flag_enabled = False self.enable_persist_graphs = convert_str_to_bool(os.getenv('BC_ENABLE_PERSIST_GRAPHS', 'True')) self.persist_graphs_timeout = int(os.getenv('BC_PERSIST_GRAPHS_TIMEOUT', 60)) self.ca_certificate: str | None = None self.no_cert_verify: bool = False self.on_prem: bool = False self.daemon_process = False # set to 'True' when running in multiprocessing 'spawn' mode self.scan_dir: List[str] = [] self.scan_file: List[str] = [] self.sast_custom_policies: str = '' def init_instance(self, platform_integration_data: dict[str, Any]) -> None: """This is mainly used for recreating the instance without interacting with the platform again""" self.daemon_process = True self.bc_api_url = platform_integration_data["bc_api_url"] self.bc_api_key = platform_integration_data["bc_api_key"] self.bc_source = platform_integration_data["bc_source"] self.bc_source_version = platform_integration_data["bc_source_version"] self.bucket = platform_integration_data["bucket"] self.cicd_details = platform_integration_data["cicd_details"] self.credentials = platform_integration_data["credentials"] self.platform_integration_configured = platform_integration_data["platform_integration_configured"] self.prisma_api_url = platform_integration_data.get("prisma_api_url", 'https://api0.prismacloud.io') self.custom_auth_headers = platform_integration_data["custom_auth_headers"] self.repo_branch = platform_integration_data["repo_branch"] self.repo_id = platform_integration_data["repo_id"] self.repo_path = platform_integration_data["repo_path"] self.skip_fixes = platform_integration_data["skip_fixes"] self.timestamp = platform_integration_data["timestamp"] self.use_s3_integration = platform_integration_data["use_s3_integration"] self.setup_api_urls() # 'mypy' doesn't like, when you try to override an instance method self.get_auth_token = MethodType(lambda _=None: platform_integration_data["get_auth_token"], self) # type:ignore[method-assign] def generate_instance_data(self) -> dict[str, Any]: """This output is used to re-initialize the instance and should be kept in sync with 'init_instance()'""" return { # 'api_url' will be set by invoking 'setup_api_urls()' "bc_api_url": self.bc_api_url, "bc_api_key": self.bc_api_key, "bc_source": self.bc_source, "bc_source_version": self.bc_source_version, "bucket": self.bucket, "cicd_details": self.cicd_details, "credentials": self.credentials, "platform_integration_configured": self.platform_integration_configured, "prisma_api_url": self.prisma_api_url, "custom_auth_headers": self.custom_auth_headers, "repo_branch": self.repo_branch, "repo_id": self.repo_id, "repo_path": self.repo_path, "skip_fixes": self.skip_fixes, "timestamp": self.timestamp, "use_s3_integration": self.use_s3_integration, # will be overriden with a simple lambda expression "get_auth_token": self.get_auth_token() if self.bc_api_key else "" } def set_bc_api_url(self, new_url: str) -> None: self.bc_api_url = normalize_bc_url(new_url) self.setup_api_urls() def setup_api_urls(self) -> None: """ API URLs vary depending upon whether the platform is Bridgecrew or Prisma Cloud. Bridgecrew has one default that can be used when initializing the class, but Prisma Cloud requires resetting them in setup_bridgecrew_credentials, which is where command-line parameters are first made available. """ if self.bc_api_url: self.api_url = self.bc_api_url else: self.api_url = f"{self.prisma_api_url}/bridgecrew" self.prisma_policies_url = f"{self.prisma_api_url}/v2/policy" self.prisma_policy_filters_url = f"{self.prisma_api_url}/filter/policy/suggest" self.guidelines_api_url = f"{self.api_url}/api/v2/guidelines" self.guidelines_api_url_backoff = f"{self.api_url}/api/v1/guidelines" self.integrations_api_url = f"{self.api_url}/api/v1/integrations/types/checkov" self.platform_run_config_url = f"{self.api_url}/api/v2/checkov/runConfiguration" self.reachability_run_config_url = f"{self.api_url}/api/v2/checkov/reachabilityRunConfiguration" self.runtime_run_config_url = f"{self.api_url}/api/v1/runtime-images/repositories" def is_prisma_integration(self) -> bool: if self.bc_api_key and not self.is_bc_token(self.bc_api_key): return True return False def is_token_valid(token: str) -> bool: parts = token.split('::') parts_len = len(parts) if parts_len == 1: valid = BcPlatformIntegration.is_bc_token(token) # TODO: add it back at a later time # if valid: # print( # "We're glad you're using Checkov with Bridgecrew!\n" # "Bridgecrew has been fully integrated into Prisma Cloud with a powerful code to cloud experience.\n" # "As a part of the transition, we will be shutting down Bridgecrew standalone edition at the end of 2023 (https://www.paloaltonetworks.com/services/support/end-of-life-announcements).\n" # "Please upgrade to Prisma Cloud Enterprise Edition before the end of the year.\n" # ) return valid elif parts_len == 2: # A Prisma access key is a UUID, same as a BC API key if BcPlatformIntegration.is_bc_token(parts[0]) and parts[1] and BASE64_PATTERN.match(parts[1]) is not None: return True return False else: return False def is_bc_token(token: str | None) -> TypeGuard[str]: if not token: return False return re.match(UUID_V4_PATTERN, token) is not None def get_auth_token(self) -> str: if self.is_bc_token(self.bc_api_key): return self.bc_api_key # A Prisma Cloud Access Key was specified as the Bridgecrew token. if not self.prisma_api_url: raise ValueError("A Prisma Cloud token was set, but no Prisma Cloud API URL was set") if not self.bc_api_key: # should usually not happen raise ValueError("A Prisma Cloud or Birdgecrew token was not set") if '::' not in self.bc_api_key: raise ValueError( "A Prisma Cloud token was set, but the token is not in the correct format: <access_key_id>::<secret_key>") if not self.http: raise AttributeError("HTTP manager was not correctly created") username, password = self.bc_api_key.split('::') request = self.http.request("POST", f"{self.prisma_api_url}/login", # type:ignore[no-untyped-call] body=json.dumps({"username": username, "password": password}), headers=merge_dicts({"Content-Type": "application/json"}, get_user_agent_header())) if request.status == 401: logging.error(f'Received 401 response from Prisma /login endpoint: {request.data.decode("utf8")}') raise BridgecrewAuthError() elif request.status == 403: logging.error('Received 403 (Forbidden) response from Prisma /login endpoint') raise BridgecrewAuthError() token: str = json.loads(request.data.decode("utf8"))['token'] return token def setup_http_manager(self, ca_certificate: str | None = None, no_cert_verify: bool = False) -> None: """ bridgecrew uses both the urllib3 and requests libraries, while checkov uses the requests library. :param ca_certificate: an optional CA bundle to be used by both libraries. :param no_cert_verify: whether to skip SSL cert verification """ self.ca_certificate = ca_certificate self.no_cert_verify = no_cert_verify ca_certificate = ca_certificate or os.getenv('BC_CA_BUNDLE') cert_reqs: str | None if self.http: return if ca_certificate: os.environ['REQUESTS_CA_BUNDLE'] = ca_certificate cert_reqs = 'CERT_NONE' if no_cert_verify else 'REQUIRED' logging.debug(f'Using CA cert {ca_certificate} and cert_reqs {cert_reqs}') try: parsed_url = urllib3.util.parse_url(os.environ['https_proxy']) self.http = urllib3.ProxyManager( os.environ['https_proxy'], cert_reqs=cert_reqs, ca_certs=ca_certificate, proxy_headers=urllib3.make_headers(proxy_basic_auth=parsed_url.auth), # type:ignore[no-untyped-call] timeout=self.http_timeout, retries=self.http_retry, ) except KeyError: self.http = urllib3.PoolManager( cert_reqs=cert_reqs, ca_certs=ca_certificate, timeout=self.http_timeout, retries=self.http_retry, ) else: cert_reqs = 'CERT_NONE' if no_cert_verify else None logging.debug(f'Using cert_reqs {cert_reqs}') try: parsed_url = urllib3.util.parse_url(os.environ['https_proxy']) self.http = urllib3.ProxyManager( os.environ['https_proxy'], cert_reqs=cert_reqs, proxy_headers=urllib3.make_headers(proxy_basic_auth=parsed_url.auth), # type:ignore[no-untyped-call] timeout=self.http_timeout, retries=self.http_retry, ) except KeyError: self.http = urllib3.PoolManager( cert_reqs=cert_reqs, timeout=self.http_timeout, retries=self.http_retry, ) logging.debug('Successfully set up HTTP manager') def setup_bridgecrew_credentials( self, repo_id: str, skip_download: bool = False, source: SourceType | None = None, skip_fixes: bool = False, source_version: str | None = None, repo_branch: str | None = None, prisma_api_url: str | None = None, bc_api_url: str | None = None ) -> None: """ Setup credentials against Bridgecrew's platform. :param repo_id: Identity string of the scanned repository, of the form <repo_owner>/<repo_name> :param skip_download: whether to skip downloading data (guidelines, custom policies, etc) from the platform :param source: :param prisma_api_url: optional URL for the Prisma Cloud platform, requires a Prisma Cloud Access Key as bc_api_key """ self.repo_id = repo_id self.repo_branch = repo_branch self.skip_fixes = skip_fixes self.skip_download = skip_download self.bc_source = source self.bc_source_version = source_version if bc_api_url: self.prisma_api_url = None self.bc_api_url = normalize_bc_url(bc_api_url) self.setup_api_urls() logging.info(f'Using BC API URL: {self.bc_api_url}') if prisma_api_url: self.prisma_api_url = normalize_prisma_url(prisma_api_url) self.setup_api_urls() logging.info(f'Using Prisma API URL: {self.prisma_api_url}') if self.bc_source and self.bc_source.upload_results: self.set_s3_integration() self.platform_integration_configured = True def set_s3_integration(self) -> None: try: self.skip_fixes = True # no need to run fixes on CI integration repo_full_path, support_path, response = self.get_s3_role(self.repo_id) # type: ignore if not repo_full_path: # happens if the setup fails with something other than an auth error - we continue locally return self.bucket, self.repo_path = repo_full_path.split("/", 1) self.timestamp = self.repo_path.split("/")[-2] self.credentials = cast("dict[str, str]", response["creds"]) self.set_s3_client() if self.support_flag_enabled: self.support_bucket, self.support_repo_path = cast(str, support_path).split("/", 1) self.use_s3_integration = True self.platform_integration_configured = True except MaxRetryError: logging.error("An SSL error occurred connecting to the platform. If you are on a VPN, please try " "disabling it and re-running the command.", exc_info=True) raise except HTTPError: logging.error("Failed to get customer assumed role", exc_info=True) raise except JSONDecodeError: logging.error(f"Response of {self.integrations_api_url} is not a valid JSON", exc_info=True) raise except BridgecrewAuthError: logging.error("Received an error response during authentication") raise def set_s3_client(self) -> None: if not self.credentials: raise ValueError("Credentials for client are not set") region = DEFAULT_REGION use_accelerate_endpoint = True if self.prisma_api_url == PRISMA_GOV_API_URL: region = GOV_CLOUD_REGION use_accelerate_endpoint = False try: config = Config( s3={ "use_accelerate_endpoint": use_accelerate_endpoint, } ) self.s3_client = boto3.client( "s3", aws_access_key_id=self.credentials["AccessKeyId"], aws_secret_access_key=self.credentials["SecretAccessKey"], aws_session_token=self.credentials["SessionToken"], region_name=region, config=config, ) except ClientError: logging.error(f"Failed to initiate client with credentials {self.credentials}", exc_info=True) raise def get_s3_role(self, repo_id: str) -> tuple[str, str, dict[str, Any]] | tuple[None, None, dict[str, Any]]: token = self.get_auth_token() if not self.http: raise AttributeError("HTTP manager was not correctly created") tries = 0 response = self._get_s3_creds(repo_id, token) while ('Message' in response or 'message' in response): if response.get('Message') and response['Message'] == UNAUTHORIZED_MESSAGE: raise BridgecrewAuthError() elif response.get('message') and ASSUME_ROLE_UNUATHORIZED_MESSAGE in response['message']: raise BridgecrewAuthError( "Checkov got an unexpected authorization error that may not be due to your credentials. Please contact support.") elif response.get('message') and "cannot be found" in response['message']: self.loading_output("creating role") response = self._get_s3_creds(repo_id, token) else: if tries < 3: tries += 1 response = self._get_s3_creds(repo_id, token) else: logging.error('Checkov got an unexpected error that may be due to backend issues. The scan will continue, ' 'but results will not be sent to the platform. Please contact support for assistance.') logging.error(f'Error from platform: {response.get("message") or response.get("Message")}') self.s3_setup_failed = True return None, None, response repo_full_path = response["path"] support_path = response.get("supportPath") return repo_full_path, support_path, response def _get_s3_creds(self, repo_id: str, token: str) -> dict[str, Any]: logging.debug(f'Getting S3 upload credentials from {self.integrations_api_url}') request = self.http.request("POST", self.integrations_api_url, # type:ignore[union-attr] body=json.dumps({"repoId": repo_id, "support": self.support_flag_enabled}), headers=merge_dicts({"Authorization": token, "Content-Type": "application/json"}, get_user_agent_header(), self.custom_auth_headers)) logging.debug(f'Request ID: {request.headers.get("x-amzn-requestid")}') logging.debug(f'Trace ID: {request.headers.get("x-amzn-trace-id")}') if request.status == 403: error_message = get_auth_error_message(request.status, self.is_prisma_integration(), True) raise BridgecrewAuthError(error_message) response: dict[str, Any] = json.loads(request.data.decode("utf8")) return response def is_integration_configured(self) -> bool: """ Checks if Bridgecrew integration is fully configured based in input params. :return: True if the integration is configured, False otherwise """ return self.platform_integration_configured def persist_repository( self, root_dir: str | Path, files: list[str] | None = None, excluded_paths: list[str] | None = None, included_paths: list[str] | None = None, sast_languages: Set[SastLanguages] | None = None ) -> None: """ Persist the repository found on root_dir path to Bridgecrew's platform. If --file flag is used, only files that are specified will be persisted. :param files: Absolute path of the files passed in the --file flag. :param root_dir: Absolute path of the directory containing the repository root level. :param excluded_paths: Paths to exclude from persist process :param included_paths: Paths to exclude from persist process """ excluded_paths = excluded_paths if excluded_paths is not None else [] if not self.use_s3_integration or self.s3_setup_failed: return files_to_persist: List[FileToPersist] = [] if files: for f in files: f_name = os.path.basename(f) _, file_extension = os.path.splitext(f) if file_extension in SCANNABLE_PACKAGE_FILES: continue if file_extension in SUPPORTED_FILE_EXTENSIONS or f_name in SUPPORTED_FILES: files_to_persist.append(FileToPersist(f, os.path.relpath(f, root_dir))) if sast_languages: for framwork in sast_languages: if file_extension in SAST_SUPPORTED_FILE_EXTENSIONS[framwork]: files_to_persist.append(FileToPersist(f, os.path.relpath(f, root_dir))) break else: for root_path, d_names, f_names in os.walk(root_dir): # self.excluded_paths only contains the config fetched from the platform. # but here we expect the list from runner_registry as well (which includes self.excluded_paths). filter_ignored_paths(root_path, d_names, excluded_paths, included_paths=included_paths) filter_ignored_paths(root_path, f_names, excluded_paths) for file_path in f_names: _, file_extension = os.path.splitext(file_path) if file_extension in SCANNABLE_PACKAGE_FILES: continue full_file_path = os.path.join(root_path, file_path) relative_file_path = os.path.relpath(full_file_path, root_dir) if file_extension in SUPPORTED_FILE_EXTENSIONS or file_path in SUPPORTED_FILES or is_dockerfile(file_path): files_to_persist.append(FileToPersist(full_file_path, relative_file_path)) if sast_languages: for framwork in sast_languages: if file_extension in SAST_SUPPORTED_FILE_EXTENSIONS[framwork]: files_to_persist.append(FileToPersist(full_file_path, relative_file_path)) break self.persist_files(files_to_persist) def persist_git_configuration(self, root_dir: str | Path, git_config_folders: list[str]) -> None: if not self.use_s3_integration or self.s3_setup_failed: return files_to_persist: list[FileToPersist] = [] for git_config_folder in git_config_folders: if not os.path.isdir(git_config_folder): continue if not len(os.listdir(git_config_folder)): continue for root_path, _, f_names in os.walk(git_config_folder): for file_path in f_names: _, file_extension = os.path.splitext(file_path) if file_extension in SUPPORTED_FILE_EXTENSIONS: full_file_path = os.path.join(root_path, file_path) relative_file_path = os.path.relpath(full_file_path, root_dir) files_to_persist.append(FileToPersist(full_file_path, relative_file_path)) self.persist_files(files_to_persist) def adjust_sast_match_location_path(self, match: Match) -> None: for dir in self.scan_dir: if match.location.path.startswith(os.path.abspath(dir)): match.location.path = match.location.path.replace(os.path.abspath(dir), self.repo_path) # type: ignore if match.metadata.code_locations: for code_location in match.metadata.code_locations: code_location.path = code_location.path.replace(os.path.abspath(dir), self.repo_path) # type: ignore if match.metadata.taint_mode and match.metadata.taint_mode.data_flow: for df in match.metadata.taint_mode.data_flow: df.path = df.path.replace(os.path.abspath(dir), self.repo_path) # type: ignore return for file in self.scan_file: if match.location.path == os.path.abspath(file): file_dir = '/'.join(match.location.path.split('/')[0:-1]) match.location.path = match.location.path.replace(os.path.abspath(file_dir), self.repo_path) # type: ignore if match.metadata.code_locations: for code_location in match.metadata.code_locations: code_location.path = code_location.path.replace(os.path.abspath(file_dir), self.repo_path) # type: ignore if match.metadata.taint_mode and match.metadata.taint_mode.data_flow: for df in match.metadata.taint_mode.data_flow: df.path = df.path.replace(os.path.abspath(file_dir), self.repo_path) # type: ignore return def _delete_code_block_from_sast_report(report: Dict[str, Any]) -> None: if isinstance(report, dict): for key, value in report.items(): if key == 'code_block': report[key] = '' BcPlatformIntegration._delete_code_block_from_sast_report(value) if isinstance(report, list): for item in report: BcPlatformIntegration._delete_code_block_from_sast_report(item) def save_sast_report_locally(sast_scan_reports: Dict[str, Dict[str, Any]]) -> None: for lang, report in sast_scan_reports.items(): filename = f'{lang}_report.json' with open(f"/tmp/{filename}", 'w') as f: # nosec f.write(json.dumps(report)) def persist_sast_scan_results(self, reports: List[Report]) -> None: sast_scan_reports = {} for report in reports: if not report.check_type.lower().startswith(CheckType.SAST): continue if not hasattr(report, 'sast_report') or not report.sast_report: continue for _, match_by_check in report.sast_report.rule_match.items(): for _, match in match_by_check.items(): for m in match.matches: self.adjust_sast_match_location_path(m) sast_scan_reports[report.check_type] = report.sast_report.model_dump(mode='json') if self.on_prem: BcPlatformIntegration._delete_code_block_from_sast_report(sast_scan_reports) if os.getenv('SAVE_SAST_REPORT_LOCALLY'): self.save_sast_report_locally(sast_scan_reports) persist_checks_results(sast_scan_reports, self.s3_client, self.bucket, self.repo_path) # type: ignore def persist_cdk_scan_results(self, reports: List[Report]) -> None: cdk_scan_reports = {} for report in reports: if not report.check_type.startswith(CDK_FRAMEWORK_PREFIX): continue if not report.cdk_report: # type: ignore continue for match_by_check in report.cdk_report.rule_match.values(): # type: ignore for _, match in match_by_check.items(): for m in match.matches: self.adjust_sast_match_location_path(m) cdk_scan_reports[report.check_type] = report.cdk_report.model_dump(mode='json') # type: ignore if self.on_prem: BcPlatformIntegration._delete_code_block_from_sast_report(cdk_scan_reports) # In case we dont have sast report - create empty one sast_reports = {} for check_type, report in cdk_scan_reports.items(): lang = check_type.split('_')[1] found_sast_report = False for report in reports: if report.check_type == f'sast_{lang}': found_sast_report = True if not found_sast_report: sast_reports[f'sast_{lang}'] = report.empty_sast_report.model_dump(mode='json') # type: ignore persist_checks_results(sast_reports, self.s3_client, self.bucket, self.repo_path) # type: ignore persist_checks_results(cdk_scan_reports, self.s3_client, self.bucket, self.repo_path) # type: ignore def persist_scan_results(self, scan_reports: list[Report]) -> None: """ Persist checkov's scan result into bridgecrew's platform. :param scan_reports: List of checkov scan reports """ if not self.use_s3_integration or not self.s3_client or self.s3_setup_failed: return if not self.bucket or not self.repo_path: logging.error(f"Something went wrong: bucket {self.bucket}, repo path {self.repo_path}") return # just process reports with actual results in it self.scan_reports = [scan_report for scan_report in scan_reports if not scan_report.is_empty(full=True)] reduced_scan_reports = reduce_scan_reports(self.scan_reports, self.on_prem) checks_metadata_paths = enrich_and_persist_checks_metadata(self.scan_reports, self.s3_client, self.bucket, self.repo_path, self.on_prem) dpath.merge(reduced_scan_reports, checks_metadata_paths) persist_checks_results(reduced_scan_reports, self.s3_client, self.bucket, self.repo_path) async def persist_reachability_alias_mapping(self, alias_mapping: Dict[str, Any]) -> None: if not self.use_s3_integration or not self.s3_client or self.s3_setup_failed: return if not self.bucket or not self.repo_path: logging.error(f"Something went wrong: bucket {self.bucket}, repo path {self.repo_path}") return s3_path = f'{self.repo_path}/alias_mapping.json' _put_json_object(self.s3_client, alias_mapping, self.bucket, s3_path) def persist_assets_scan_results(self, assets_report: Optional[Dict[str, Any]]) -> None: if not assets_report: return for lang, assets in assets_report['imports'].items(): new_report = {'imports': {lang.value: assets}} persist_assets_results(f'sast_{lang.value}', new_report, self.s3_client, self.bucket, self.repo_path) def persist_reachability_scan_results(self, reachability_report: Optional[Dict[str, Any]]) -> None: if not reachability_report: return for lang, report in reachability_report.items(): persist_reachability_results(f'sast_{lang}', {lang: report}, self.s3_client, self.bucket, self.repo_path) def persist_image_scan_results(self, report: dict[str, Any] | None, file_path: str, image_name: str, branch: str) -> None: if not self.s3_client: logging.error("S3 upload was not correctly initialized") return if not self.bucket or not self.repo_path: logging.error("Bucket or repo_path was not set") return repo_path_without_src = os.path.dirname(self.repo_path) target_report_path = f'{repo_path_without_src}/{checkov_results_prefix}/{CheckType.SCA_IMAGE}/raw_results.json' to_upload = {"report": report, "file_path": file_path, "image_name": image_name, "branch": branch} _put_json_object(self.s3_client, to_upload, self.bucket, target_report_path) def persist_enriched_secrets(self, enriched_secrets: list[EnrichedSecret]) -> str | None: if not enriched_secrets or not self.repo_path or not self.bucket: logging.debug(f'One of enriched secrets, repo path, or bucket are empty, aborting. values:' f'enriched_secrets={"Valid" if enriched_secrets else "Empty"},' f' repo_path={self.repo_path}, bucket={self.bucket}') return None if not bc_integration.bc_api_key or not os.getenv("CKV_VALIDATE_SECRETS"): logging.debug('Skipping persistence of enriched secrets object as secrets verification is off,' ' enabled it via env var CKV_VALIDATE_SECRETS and provide an api key') return None if not self.s3_client: logging.error("S3 upload was not correctly initialized") return None base_path = re.sub(REPO_PATH_PATTERN, r'original_secrets/\1', self.repo_path) s3_path = f'{base_path}/{uuid.uuid4()}.json' try: _put_json_object(self.s3_client, enriched_secrets, self.bucket, s3_path, log_stack_trace_on_error=False) except ClientError: logging.warning("Got access denied, retrying as s3 role changes should be propagated") sleep(4) try: _put_json_object(self.s3_client, enriched_secrets, self.bucket, s3_path, log_stack_trace_on_error=False) except ClientError: logging.error("Getting access denied consistently, skipping secrets verification, please try again") return None return s3_path def persist_run_metadata(self, run_metadata: dict[str, str | list[str]]) -> None: if not self.use_s3_integration or not self.s3_client or self.s3_setup_failed: return if not self.bucket or not self.repo_path: logging.error(f"Something went wrong: bucket {self.bucket}, repo path {self.repo_path}") return persist_run_metadata(run_metadata, self.s3_client, self.bucket, self.repo_path, True) if self.support_bucket and self.support_repo_path: logging.debug(f'Also uploading run_metadata.json to support location: {self.support_bucket}/{self.support_repo_path}') persist_run_metadata(run_metadata, self.s3_client, self.support_bucket, self.support_repo_path, False) def persist_all_logs_streams(self, logs_streams: Dict[str, StringIO]) -> None: if not self.use_s3_integration or not self.s3_client or self.s3_setup_failed: return if not self.support_bucket or not self.support_repo_path: logging.error( f"Something went wrong with the log upload location: bucket {self.support_bucket}, repo path {self.support_repo_path}") return persist_multiple_logs_stream(logs_streams, self.s3_client, self.support_bucket, self.support_repo_path) def persist_graphs(self, graphs: dict[str, list[tuple[LibraryGraph, Optional[str]]]], absolute_root_folder: str = '') -> None: if not self.use_s3_integration or not self.s3_client or self.s3_setup_failed: return if not self.bucket or not self.repo_path: logging.error(f"Something went wrong: bucket {self.bucket}, repo path {self.repo_path}") return persist_graphs(graphs, self.s3_client, self.bucket, self.repo_path, self.persist_graphs_timeout, absolute_root_folder=absolute_root_folder) def persist_resource_subgraph_maps(self, resource_subgraph_maps: dict[str, dict[str, str]]) -> None: if not self.use_s3_integration or not self.s3_client or self.s3_setup_failed: return if not self.bucket or not self.repo_path: logging.error(f"Something went wrong: bucket {self.bucket}, repo path {self.repo_path}") return persist_resource_subgraph_maps(resource_subgraph_maps, self.s3_client, self.bucket, self.repo_path, self.persist_graphs_timeout) def commit_repository(self, branch: str) -> str | None: """ :param branch: branch to be persisted Finalize the repository's scanning in bridgecrew's platform. """ try_num = 0 while try_num < MAX_RETRIES: if not self.use_s3_integration or self.s3_setup_failed: return None request = None response = None try: if not self.http: logging.error("HTTP manager was not correctly created") return None if not self.bc_source: logging.error("Source was not set") return None if not self.bc_source.upload_results: # no need to upload something return None logging.debug(f'Submitting finalize upload request to {self.integrations_api_url}') request = self.http.request("PUT", f"{self.integrations_api_url}?source={self.bc_source.name}", # type:ignore[no-untyped-call] body=json.dumps( {"path": self.repo_path, "branch": branch, "to_branch": CI_METADATA_EXTRACTOR.to_branch, "pr_id": CI_METADATA_EXTRACTOR.pr_id, "pr_url": CI_METADATA_EXTRACTOR.pr_url, "commit_hash": CI_METADATA_EXTRACTOR.commit_hash, "commit_url": CI_METADATA_EXTRACTOR.commit_url, "author": CI_METADATA_EXTRACTOR.author_name, "author_url": CI_METADATA_EXTRACTOR.author_url, "run_id": CI_METADATA_EXTRACTOR.run_id, "run_url": CI_METADATA_EXTRACTOR.run_url, "repository_url": CI_METADATA_EXTRACTOR.repository_url}), headers=merge_dicts({"Authorization": self.get_auth_token(), "Content-Type": "application/json", 'x-api-client': self.bc_source.name, 'x-api-checkov-version': checkov_version}, get_user_agent_header(), self.custom_auth_headers )) response = json.loads(request.data.decode("utf8")) logging.debug(f'Request ID: {request.headers.get("x-amzn-requestid")}') logging.debug(f'Trace ID: {request.headers.get("x-amzn-trace-id")}') url: str = self.get_sso_prismacloud_url(response.get("url", None)) return url except HTTPError: logging.error(f"Failed to commit repository {self.repo_path}", exc_info=True) self.s3_setup_failed = True except JSONDecodeError: if request: logging.warning(f"Response (status: {request.status}) of {self.integrations_api_url}: {request.data.decode('utf8')}") # danger:ignore - we won't be here if the response contains valid data logging.error(f"Response of {self.integrations_api_url} is not a valid JSON", exc_info=True) self.s3_setup_failed = True finally: if request and request.status == 201 and response and response.get("result") == "Success": logging.info(f"Finalize repository {self.repo_id} in the platform") elif ( response and try_num < MAX_RETRIES and re.match("The integration ID .* in progress", response.get("message", "")) ): logging.info( f"Failed to persist for repo {self.repo_id}, sleeping for {SLEEP_SECONDS} seconds before retrying") try_num += 1 sleep(SLEEP_SECONDS) else: logging.error(f"Failed to finalize repository {self.repo_id} in the platform with the following error:\n{response}") self.s3_setup_failed = True return None def persist_files(self, files_to_persist: list[FileToPersist]) -> None: logging.info(f"Persisting {len(files_to_persist)} files") with futures.ThreadPoolExecutor() as executor: futures.wait( [executor.submit(self._persist_file, file_to_persist.full_file_path, file_to_persist.s3_file_key) for file_to_persist in files_to_persist], return_when=futures.FIRST_EXCEPTION, ) logging.info(f"Done persisting {len(files_to_persist)} files") def _persist_file(self, full_file_path: str, s3_file_key: str) -> None: tries = MAX_RETRIES curr_try = 0 if not self.s3_client or not self.bucket or not self.repo_path: logging.error( f"Something went wrong: S3 client {self.s3_client} bucket {self.bucket}, repo path {self.repo_path}" ) return file_object_key = os.path.join(self.repo_path, s3_file_key).replace("\\", "/") while curr_try < tries: try: self.s3_client.upload_file(full_file_path, self.bucket, file_object_key) return except ClientError as e: if e.response.get('Error', {}).get('Code') == 'AccessDenied': sleep(SLEEP_SECONDS) curr_try += 1 else: logging.error(f"failed to persist file {full_file_path} into S3 bucket {self.bucket}", exc_info=True) logging.debug(f"file size of {full_file_path} is {os.stat(full_file_path).st_size} bytes") raise except Exception: logging.error(f"failed to persist file {full_file_path} into S3 bucket {self.bucket}", exc_info=True) logging.debug(f"file size of {full_file_path} is {os.stat(full_file_path).st_size} bytes") raise if curr_try == tries: logging.error( f"failed to persist file {full_file_path} into S3 bucket {self.bucket} - gut AccessDenied {tries} times") def get_platform_run_config(self) -> None: if self.skip_download is True: logging.debug("Skipping downloading configs from platform") return if self.is_integration_configured(): self.get_customer_run_config() else: self.get_public_run_config() def _get_run_config_query_params(self) -> str: return f'module={"bc" if self.is_bc_token(self.bc_api_key) else "pc"}&enforcementv2=true' def get_run_config_url(self) -> str: return f'{self.platform_run_config_url}?{self._get_run_config_query_params()}' def get_customer_run_config(self) -> None: if self.skip_download is True: logging.debug("Skipping customer run config API call") return if not self.bc_api_key or not self.is_integration_configured(): raise Exception( "Tried to get customer run config, but the API key was missing or the integration was not set up") if not self.bc_source: logging.error("Source was not set") return try: token = self.get_auth_token() headers = merge_dicts(get_auth_header(token), get_default_get_headers(self.bc_source, self.bc_source_version), self.custom_auth_headers) self.setup_http_manager() if not self.http: logging.error("HTTP manager was not correctly created") return platform_type = PRISMA_PLATFORM if self.is_prisma_integration() else BRIDGECREW_PLATFORM url = self.get_run_config_url() logging.debug(f'Platform run config URL: {url}') request = self.http.request("GET", url, headers=headers) # type:ignore[no-untyped-call] request_id = request.headers.get("x-amzn-requestid") trace_id = request.headers.get("x-amzn-trace-id") logging.debug(f'Request ID: {request_id}') logging.debug(f'Trace ID: {trace_id}') if request.status == 500: error_message = 'An unexpected backend error occurred getting the run configuration from the platform (status code 500). ' \ 'please contact support and provide debug logs and the values below. You may be able to use the --skip-download option ' \ 'to bypass this error, but this will prevent platform configurations (e.g., custom policies, suppressions) from ' \ f'being used in the scan.\nRequest ID: {request_id}\nTrace ID: {trace_id}' logging.error(error_message) raise Exception(error_message) elif request.status != 200: error_message = get_auth_error_message(request.status, self.is_prisma_integration(), False) logging.error(error_message) raise BridgecrewAuthError(error_message) self.customer_run_config_response = json.loads(request.data.decode("utf8")) logging.debug(f"Got customer run config from {platform_type} platform") except Exception: logging.warning(f"Failed to get the customer run config from {self.platform_run_config_url}", exc_info=True) raise def get_reachability_run_config(self) -> Union[Dict[str, Any], None]: if self.skip_download is True: logging.debug("Skipping customer run config API call") return None if not self.bc_api_key or not self.is_integration_configured(): raise Exception( "Tried to get customer run config, but the API key was missing or the integration was not set up") if not self.bc_source: logging.error("Source was not set") return None try: token = self.get_auth_token() headers = merge_dicts(get_auth_header(token), get_default_get_headers(self.bc_source, self.bc_source_version), self.custom_auth_headers) self.setup_http_manager() if not self.http: logging.error("HTTP manager was not correctly created") return None platform_type = PRISMA_PLATFORM if self.is_prisma_integration() else BRIDGECREW_PLATFORM request = self.http.request("GET", self.reachability_run_config_url, headers=headers) # type:ignore[no-untyped-call] if request.status != 200: error_message = get_auth_error_message(request.status, self.is_prisma_integration(), False) logging.error(error_message) raise BridgecrewAuthError(error_message) logging.debug(f"Got reachability run config from {platform_type} platform") res: Dict[str, Any] = json.loads(request.data.decode("utf8")) return res except Exception: logging.warning(f"Failed to get the reachability run config from {self.reachability_run_config_url}", exc_info=True) raise def get_runtime_run_config(self) -> None: try: if self.skip_download is True: logging.debug("Skipping customer run config API call") raise if not self.bc_api_key or not self.is_integration_configured(): raise Exception( "Tried to get customer run config, but the API key was missing or the integration was not set up") if not self.bc_source: logging.error("Source was not set") raise token = self.get_auth_token() headers = merge_dicts(get_auth_header(token), get_default_get_headers(self.bc_source, self.bc_source_version), self.custom_auth_headers) self.setup_http_manager() if not self.http: logging.error("HTTP manager was not correctly created") raise platform_type = PRISMA_PLATFORM if self.is_prisma_integration() else BRIDGECREW_PLATFORM url = f"{self.runtime_run_config_url}?repoId={self.repo_id}" request = self.http.request("GET", url, headers=headers) # type:ignore[no-untyped-call] if request.status != 200: error_message = get_auth_error_message(request.status, self.is_prisma_integration(), False) logging.error(error_message) raise BridgecrewAuthError(error_message) logging.debug(f"Got run config from {platform_type} platform") self.runtime_run_config_response = json.loads(request.data.decode("utf8")) except Exception: logging.debug('could not get runtime info for this repo') def get_prisma_build_policies(self, policy_filter: str) -> None: """ Get Prisma policy for enriching runConfig with metadata Filters: https://prisma.pan.dev/api/cloud/cspm/policy#operation/get-policy-filters-and-options :param policy_filter: comma separated filter string. Example, policy.label=A,cloud.type=aws :return: """ if self.skip_download is True: logging.debug("Skipping prisma policy API call") return if not policy_filter: return if not self.is_prisma_integration(): return if not self.bc_api_key or not self.is_integration_configured(): raise Exception( "Tried to get prisma build policy metadata, " "but the API key was missing or the integration was not set up") request = None try: token = self.get_auth_token() headers = merge_dicts(get_prisma_auth_header(token), get_prisma_get_headers(), self.custom_auth_headers) self.setup_http_manager() if not self.http: logging.error("HTTP manager was not correctly created") return logging.debug(f'Prisma policy URL: {self.prisma_policies_url}') query_params = convert_prisma_policy_filter_to_dict(policy_filter) if self.is_valid_policy_filter(query_params, valid_filters=self.get_prisma_policy_filters()): # If enabled and subtype are not explicitly set, use the only acceptable values. query_params['policy.enabled'] = True query_params['policy.subtype'] = 'build' request = self.http.request( # type:ignore[no-untyped-call] "GET", self.prisma_policies_url, headers=headers, fields=query_params, ) self.prisma_policies_response = json.loads(request.data.decode("utf8")) logging.debug("Got Prisma build policy metadata") else: logging.warning("Skipping get prisma build policies. --policy-metadata-filter will not be applied.") except Exception: response_message = f': {request.status} - {request.reason}' if request else '' logging.warning( f"Failed to get prisma build policy metadata from {self.prisma_policies_url}{response_message}", exc_info=True) def get_prisma_policy_filters(self) -> Dict[str, Dict[str, Any]]: request = None try: token = self.get_auth_token() headers = merge_dicts(get_prisma_auth_header(token), get_prisma_get_headers(), self.custom_auth_headers) self.setup_http_manager() if not self.http: logging.error("HTTP manager was not correctly created") return {} logging.debug(f'Prisma filter URL: {self.prisma_policy_filters_url}') request = self.http.request( # type:ignore[no-untyped-call] "GET", self.prisma_policy_filters_url, headers=headers, ) policy_filters: dict[str, dict[str, Any]] = json.loads(request.data.decode("utf8")) logging.debug(f'Prisma filter suggestion response: {policy_filters}') return policy_filters except Exception: response_message = f': {request.status} - {request.reason}' if request else '' logging.warning( f"Failed to get prisma build policy metadata from {self.prisma_policy_filters_url}{response_message}", exc_info=True) return {} def is_valid_policy_filter(policy_filter: dict[str, str], valid_filters: dict[str, dict[str, Any]] | None = None) -> bool: """ Validates only the filter names """ valid_filters = valid_filters or {} if not policy_filter: return False if not valid_filters: return False for filter_name, filter_value in policy_filter.items(): if filter_name not in valid_filters.keys(): logging.warning(f"Invalid filter name: {filter_name}") logging.warning(f"Available filter names: {', '.join(valid_filters.keys())}") return False elif filter_name == 'policy.subtype' and filter_value != 'build': logging.warning(f"Filter value not allowed: {filter_value}") logging.warning("Available options: build") return False elif filter_name == 'policy.enabled' and not convert_str_to_bool(filter_value): logging.warning(f"Filter value not allowed: {filter_value}") logging.warning("Available options: True") return False logging.debug("--policy-metadata-filter is valid") return True def get_public_run_config(self) -> None: if self.skip_download is True: logging.debug("Skipping checkov mapping and guidelines API call") return try: headers: dict[str, Any] = {} self.setup_http_manager() if not self.http: logging.error("HTTP manager was not correctly created") return request = self.http.request("GET", self.guidelines_api_url, headers=headers) # type:ignore[no-untyped-call] if request.status >= 300: request = self.http.request( # type:ignore[no-untyped-call] "GET", self.guidelines_api_url_backoff, headers=headers, ) self.public_metadata_response = json.loads(request.data.decode("utf8")) platform_type = PRISMA_PLATFORM if self.is_prisma_integration() else BRIDGECREW_PLATFORM logging.debug(f"Got checkov mappings and guidelines from {platform_type} platform") except Exception: logging.warning(f"Failed to get the checkov mappings and guidelines from {self.guidelines_api_url}. Skips using BC_* IDs will not work.", exc_info=True) def get_report_to_platform(self, args: argparse.Namespace, scan_reports: list[Report]) -> None: if self.bc_api_key: if args.directory: repo_id = self.get_repository(args) self.setup_bridgecrew_credentials(repo_id=repo_id) if self.is_integration_configured(): self._upload_run(args, scan_reports) # Added this to generate a default repo_id for cli scans for upload to the platform # whilst also persisting a cli repo_id into the object def persist_bc_api_key(self, args: argparse.Namespace) -> str | None: if args.bc_api_key: self.bc_api_key = args.bc_api_key else: # get the key from file self.bc_api_key = read_key() return self.bc_api_key # Added this to generate a default repo_id for cli scans for upload to the platform # whilst also persisting a cli repo_id into the object def persist_repo_id(self, args: argparse.Namespace) -> str: if args.repo_id is None: if CI_METADATA_EXTRACTOR.from_branch: self.repo_id = CI_METADATA_EXTRACTOR.from_branch if args.directory: basename = path.basename(os.path.abspath(args.directory[0])) self.repo_id = f"cli_repo/{basename}" if args.file: # Get the base path of the file based on it's absolute path basename = os.path.basename(os.path.dirname(os.path.abspath(args.file[0]))) self.repo_id = f"cli_repo/{basename}" else: self.repo_id = args.repo_id if not self.repo_id: # this should not happen self.repo_id = "cli_repo/unknown" return self.repo_id def get_repository(self, args: argparse.Namespace) -> str: if CI_METADATA_EXTRACTOR.from_branch: return CI_METADATA_EXTRACTOR.from_branch arg_dir = args.directory[0] arg_dir.rstrip(os.path.sep) # If directory ends with /, remove it. Does not remove any other character!! basename = 'unnamed_repo' if path.basename(arg_dir) == '.' else path.basename(arg_dir) repo_id = f"cli_repo/{basename}" return repo_id def _upload_run(self, args: argparse.Namespace, scan_reports: list[Report]) -> None: print(Style.BRIGHT + colored("Connecting to Prisma Cloud...", 'green', attrs=['bold']) + Style.RESET_ALL) self.persist_repository(args.directory[0]) print(Style.BRIGHT + colored("Metadata upload complete", 'green', attrs=['bold']) + Style.RESET_ALL) self.persist_scan_results(scan_reports) self.persist_sast_scan_results(scan_reports) self.persist_cdk_scan_results(scan_reports) print(Style.BRIGHT + colored("Report upload complete", 'green', attrs=['bold']) + Style.RESET_ALL) self.commit_repository(args.branch) print(Style.BRIGHT + colored( "COMPLETE! \nYour results are in your Prisma Cloud account \n", 'green', attrs=['bold']) + Style.RESET_ALL) def _input_orgname(self) -> str: while True: result = str(input('Organization name: ')).lower().strip() # nosec # remove spaces and special characters result = ''.join(e for e in result if e.isalnum()) if result: break return result def _input_visualize_results(self) -> str: while True: result = str(input('Visualize results? (y/n): ')).lower().strip() # nosec if result[:1] in ["y", "n"]: break return result def _input_levelup_results(self) -> str: while True: result = str(input('Level up? (y/n): ')).lower().strip() # nosec if result[:1] in ["y", "n"]: break return result def _input_email(self) -> str: while True: email = str(input('E-Mail: ')).lower().strip() # nosec if re.search(EMAIL_PATTERN, email): break else: print("email should match the following pattern: {}".format(EMAIL_PATTERN)) return email def loading_output(msg: str) -> None: with trange(ACCOUNT_CREATION_TIME) as t: for _ in t: t.set_description(msg) t.set_postfix(refresh=False) sleep(SLEEP_SECONDS) def repo_matches(self, repo_name: str) -> bool: # matches xyz_org/repo or org/repo (where xyz is the BC org name and the CLI repo prefix from the platform) return re.match(re.compile(f'^(\\w+_)?{self.repo_id}$'), repo_name) is not None def get_default_headers(self, request_type: str) -> dict[str, Any]: if not self.bc_source: logging.warning("Source was not set") return {} if request_type.upper() == "GET": return merge_dicts(get_default_get_headers(self.bc_source, self.bc_source_version), {"Authorization": self.get_auth_token()}, self.custom_auth_headers) elif request_type.upper() == "POST": return merge_dicts(get_default_post_headers(self.bc_source, self.bc_source_version), {"Authorization": self.get_auth_token()}, self.custom_auth_headers) logging.info(f"Unsupported request {request_type}") return {} # Define the function that will get the relay state from the Prisma Cloud Platform. def get_sso_prismacloud_url(self, report_url: str) -> str: if not bc_integration.prisma_api_url or not self.http or not self.bc_source or report_url is None: return report_url or '' url_saml_config = f"{bc_integration.prisma_api_url}/saml/config" token = self.get_auth_token() headers = merge_dicts(get_auth_header(token), get_default_get_headers(self.bc_source, self.bc_source_version), bc_integration.custom_auth_headers) request = self.http.request("GET", url_saml_config, headers=headers, timeout=10) # type:ignore[no-untyped-call] if request.status >= 300: return report_url data = json.loads(request.data.decode("utf8")) relay_state_param_name = data.get("relayStateParamName") access_saml_url = data.get("redLockAccessSamlUrl") if relay_state_param_name and access_saml_url: parsed_url = urlparse(report_url) uri = parsed_url.path # If there are any query parameters, append them to the URI if parsed_url.query: uri = f"{uri}?{parsed_url.query}" # Check if the URL already contains GET parameters. if "?" in access_saml_url: report_url = f"{access_saml_url}&{relay_state_param_name}={uri}" else: report_url = f"{access_saml_url}?{relay_state_param_name}={uri}" return report_url def setup_on_prem(self) -> None: if self.customer_run_config_response: self.on_prem = self.customer_run_config_response.get('tenantConfig', {}).get('preventCodeUploads', False) if self.on_prem: logging.debug('On prem mode is enabled') def report_results_to_bridgecrew( scan_results: Iterable[dict[str, Any]], bc_integration: BcPlatformIntegration, bc_api_key: str, ) -> Sequence[int]: return asyncio.run(_report_results_to_bridgecrew_async(scan_results, bc_integration, bc_api_key))
null
2,326
from __future__ import annotations import logging import subprocess from pathlib import Path from typing import Union, Dict, Any, TYPE_CHECKING import asyncio from urllib.parse import quote_plus import docker import json import os import time from yarl import URL from checkov.common.bridgecrew.vulnerability_scanning.integrations.docker_image_scanning import \ docker_image_scanning_integration from checkov.common.bridgecrew.platform_integration import bc_integration from checkov.common.util.file_utils import decompress_file_gzip_base64 from checkov.common.util.http_utils import request_wrapper from checkov.common.bridgecrew.platform_key import bridgecrew_dir def generate_image_name() -> str: return f'repository/image{str(time.time() * 1000)}' def _get_docker_image_name(docker_image_id: str) -> str: try: docker_client = docker.from_env() image_name: str = docker_client.images.get(docker_image_id).attrs['RepoDigests'][0].split('@')[0] return image_name except Exception: logging.info("Failed to fetch image name.", exc_info=True) return generate_image_name()
null
2,327
from __future__ import annotations import logging import subprocess from pathlib import Path from typing import Union, Dict, Any, TYPE_CHECKING import asyncio from urllib.parse import quote_plus import docker import json import os import time from yarl import URL from checkov.common.bridgecrew.vulnerability_scanning.integrations.docker_image_scanning import \ docker_image_scanning_integration from checkov.common.bridgecrew.platform_integration import bc_integration from checkov.common.util.file_utils import decompress_file_gzip_base64 from checkov.common.util.http_utils import request_wrapper from checkov.common.bridgecrew.platform_key import bridgecrew_dir def _get_dockerfile_content(dockerfile_path: Union[str, "os.PathLike[str]"]) -> str: try: with open(dockerfile_path) as f: return f.read() except FileNotFoundError: logging.error("Path to Dockerfile is invalid", exc_info=True) raise except Exception: logging.error("Failed to read Dockerfile content", exc_info=True) raise
null
2,328
from __future__ import annotations import os from pathlib import Path bridgecrew_dir = f"{home}/.bridgecrew" bridgecrew_file = f"{bridgecrew_dir}/credentials" def persist_key(key: str) -> None: if not os.path.exists(bridgecrew_dir): os.makedirs(bridgecrew_dir) with open(bridgecrew_file, "w") as f: f.write(key)
null
2,329
from __future__ import annotations import os from pathlib import Path bridgecrew_file = f"{bridgecrew_dir}/credentials" def read_key() -> str | None: key = None if os.path.exists(bridgecrew_file): with open(bridgecrew_file, "r") as f: key = f.readline() or None # in Mac, if the credentials file is empty, f.readline() == '' and it causes bugs return key
null
2,330
from dataclasses import dataclass class SourceType: def __init__(self, name: str, upload_results: bool): class BCSourceType: SourceTypes = { BCSourceType.VSCODE: SourceType(BCSourceType.VSCODE, False), BCSourceType.JETBRAINS: SourceType(BCSourceType.JETBRAINS, False), BCSourceType.CLI: SourceType(BCSourceType.CLI, True), BCSourceType.KUBERNETES_WORKLOADS: SourceType(BCSourceType.KUBERNETES_WORKLOADS, True), BCSourceType.DISABLED: SourceType(BCSourceType.VSCODE, False), BCSourceType.GITHUB_ACTIONS: SourceType(BCSourceType.GITHUB_ACTIONS, True), BCSourceType.CODEBUILD: SourceType(BCSourceType.CODEBUILD, True), BCSourceType.JENKINS: SourceType(BCSourceType.JENKINS, True), BCSourceType.CIRCLECI: SourceType(BCSourceType.CIRCLECI, True), BCSourceType.ADMISSION_CONTROLLER: SourceType(BCSourceType.ADMISSION_CONTROLLER, False) } def get_source_type(source: str) -> SourceType: # helper method to get the source type with a default - using dict.get is ugly; you have to do: # SourceTypes.get(xyz, SourceTypes[BCSourceType.Disabled]) if source in SourceTypes: return SourceTypes[source] else: return SourceTypes[BCSourceType.CLI]
null
2,331
from __future__ import annotations import logging import os import json import itertools from concurrent import futures from io import StringIO from typing import Any, TYPE_CHECKING, Optional, Dict from collections import defaultdict import dpath from rustworkx import PyDiGraph, digraph_node_link_json from checkov.common.sast.consts import CDK_FRAMEWORK_PREFIX, SAST_FRAMEWORK_PREFIX from checkov.common.bridgecrew.check_type import CheckType from checkov.common.models.consts import SUPPORTED_FILE_EXTENSIONS from checkov.common.typing import _ReducedScanReport, LibraryGraph from checkov.common.util.file_utils import compress_multiple_strings_ios_tar from checkov.common.util.json_utils import CustomJSONEncoder SUPPORTED_FILE_EXTENSIONS = [".tf", ".yml", ".yaml", ".json", ".template", ".bicep", ".hcl"] def _is_scanned_file(file: str) -> bool: file_ending = os.path.splitext(file)[1] return file_ending in SUPPORTED_FILE_EXTENSIONS
null
2,332
from __future__ import annotations import logging import os import json import itertools from concurrent import futures from io import StringIO from typing import Any, TYPE_CHECKING, Optional, Dict from collections import defaultdict import dpath from rustworkx import PyDiGraph, digraph_node_link_json from checkov.common.sast.consts import CDK_FRAMEWORK_PREFIX, SAST_FRAMEWORK_PREFIX from checkov.common.bridgecrew.check_type import CheckType from checkov.common.models.consts import SUPPORTED_FILE_EXTENSIONS from checkov.common.typing import _ReducedScanReport, LibraryGraph from checkov.common.util.file_utils import compress_multiple_strings_ios_tar from checkov.common.util.json_utils import CustomJSONEncoder check_reduced_keys = ( 'check_id', 'check_result', 'resource', 'file_path', 'file_line_range', 'code_block', 'caller_file_path', 'caller_file_line_range') secrets_check_reduced_keys = check_reduced_keys + ('validation_status',) SAST_FRAMEWORK_PREFIX = 'sast' CDK_FRAMEWORK_PREFIX = 'cdk' class CheckType: ANSIBLE = "ansible" ARGO_WORKFLOWS = "argo_workflows" ARM = "arm" AZURE_PIPELINES = "azure_pipelines" BICEP = "bicep" BITBUCKET_PIPELINES = "bitbucket_pipelines" CDK = "cdk" CIRCLECI_PIPELINES = "circleci_pipelines" CLOUDFORMATION = "cloudformation" DOCKERFILE = "dockerfile" GITHUB_CONFIGURATION = "github_configuration" GITHUB_ACTIONS = "github_actions" GITLAB_CONFIGURATION = "gitlab_configuration" GITLAB_CI = "gitlab_ci" BITBUCKET_CONFIGURATION = "bitbucket_configuration" HELM = "helm" JSON = "json" YAML = "yaml" KUBERNETES = "kubernetes" KUSTOMIZE = "kustomize" OPENAPI = "openapi" SCA_PACKAGE = "sca_package" SCA_IMAGE = "sca_image" SECRETS = "secrets" SERVERLESS = "serverless" TERRAFORM = "terraform" TERRAFORM_JSON = "terraform_json" TERRAFORM_PLAN = "terraform_plan" SAST = 'sast' SAST_PYTHON = 'sast_python' SAST_JAVA = 'sast_java' SAST_JAVASCRIPT = 'sast_javascript' POLICY_3D = "3d_policy" class _ReducedScanReport(TypedDict): checks: _ReducedScanReportCheck image_cached_results: list[dict[str, Any]] class Report: def __init__(self, check_type: str): self.check_type = check_type self.passed_checks: list[Record] = [] self.failed_checks: list[Record] = [] self.skipped_checks: list[Record] = [] self.parsing_errors: list[str] = [] self.resources: set[str] = set() self.extra_resources: set[ExtraResource] = set() self.image_cached_results: List[dict[str, Any]] = [] self.error_status: ErrorStatus = ErrorStatus.SUCCESS def errors(self) -> Dict[str, List[str]]: return dict() def set_error_status(self, error_status: ErrorStatus) -> None: self.error_status = error_status def add_parsing_errors(self, errors: "Iterable[str]") -> None: for file in errors: self.add_parsing_error(file) def add_parsing_error(self, file: str) -> None: if file: self.parsing_errors.append(file) def add_resource(self, resource: str) -> None: self.resources.add(resource) def add_record(self, record: Record) -> None: if record.check_result["result"] == CheckResult.PASSED: self.passed_checks.append(record) if record.check_result["result"] == CheckResult.FAILED: self.failed_checks.append(record) if record.check_result["result"] == CheckResult.SKIPPED: self.skipped_checks.append(record) def get_summary(self) -> Dict[str, Union[int, str]]: return { "passed": len(self.passed_checks), "failed": len(self.failed_checks), "skipped": len(self.skipped_checks), "parsing_errors": len(self.parsing_errors), "resource_count": len(self.resources), "checkov_version": version, } def get_json(self) -> str: return json.dumps(self.get_dict(), indent=4, cls=CustomJSONEncoder) def get_all_records(self) -> List[Record]: return self.failed_checks + self.passed_checks + self.skipped_checks def get_dict(self, is_quiet: bool = False, url: str | None = None, full_report: bool = False, s3_setup_failed: bool = False, support_path: str | None = None) -> dict[str, Any]: if not url and not s3_setup_failed: url = "Add an api key '--bc-api-key <api-key>' to see more detailed insights via https://bridgecrew.cloud" elif s3_setup_failed: url = S3_UPLOAD_DETAILS_MESSAGE if is_quiet: return { "check_type": self.check_type, "results": { "failed_checks": [check.__dict__ for check in self.failed_checks] }, "summary": self.get_summary(), } if full_report: return { "check_type": self.check_type, "checks": { "passed_checks": [check.__dict__ for check in self.passed_checks], "failed_checks": [check.__dict__ for check in self.failed_checks], "skipped_checks": [check.__dict__ for check in self.skipped_checks] }, "image_cached_results": [res.__dict__ for res in self.image_cached_results] } else: result = { "check_type": self.check_type, "results": { "passed_checks": [check.__dict__ for check in self.passed_checks], "failed_checks": [check.__dict__ for check in self.failed_checks], "skipped_checks": [check.__dict__ for check in self.skipped_checks], "parsing_errors": list(self.parsing_errors), }, "summary": self.get_summary(), "url": url, } if support_path: result["support_path"] = support_path return result def get_exit_code(self, exit_code_thresholds: Union[_ExitCodeThresholds, _ScaExitCodeThresholds]) -> int: """ Returns the appropriate exit code depending on the flags that are passed in. :return: Exit code 0 or 1. """ hard_fail_on_parsing_errors = os.getenv(PARSE_ERROR_FAIL_FLAG, "false").lower() == 'true' logging.debug(f'In get_exit_code; exit code thresholds: {exit_code_thresholds}, hard_fail_on_parsing_errors: {hard_fail_on_parsing_errors}') if self.parsing_errors and hard_fail_on_parsing_errors: logging.debug('hard_fail_on_parsing_errors is True and there were parsing errors - returning 1') return 1 if not self.failed_checks: logging.debug('No failed checks in this report - returning 0') return 0 # we will have two different sets of logic in this method, determined by this variable. # if we are using enforcement rules, then there are two different sets of thresholds that apply for licenses and vulnerabilities # and we have to handle that throughout while processing the report # if we are not using enforcement rules, then we can combine licenses and vulnerabilities like normal and same as all other report types # this determination is made in runner_registry.get_fail_thresholds has_split_enforcement = CodeCategoryType.LICENSES in exit_code_thresholds hard_fail_threshold: Optional[Severity | Dict[str, Severity]] soft_fail: Optional[bool | Dict[str, bool]] if has_split_enforcement: sca_thresholds = cast(_ScaExitCodeThresholds, exit_code_thresholds) # these three are the same even in split enforcement rules generic_thresholds = cast(_ExitCodeThresholds, next(iter(sca_thresholds.values()))) soft_fail_on_checks = generic_thresholds['soft_fail_checks'] soft_fail_threshold = generic_thresholds['soft_fail_threshold'] hard_fail_on_checks = generic_thresholds['hard_fail_checks'] # these two can be different for licenses / vulnerabilities hard_fail_threshold = {category: thresholds['hard_fail_threshold'] for category, thresholds in sca_thresholds.items()} # type:ignore[index] # thinks it's an object, can't possibly be more clear soft_fail = {category: thresholds['soft_fail'] for category, thresholds in sca_thresholds.items()} # type:ignore[index] # thinks it's an object failed_checks_by_category = { CodeCategoryType.LICENSES: [fc for fc in self.failed_checks if '_LIC_' in fc.check_id], CodeCategoryType.VULNERABILITIES: [fc for fc in self.failed_checks if '_VUL_' in fc.check_id] } has_soft_fail_values = soft_fail_on_checks or soft_fail_threshold if all( not failed_checks_by_category[cast(CodeCategoryType, c)] or ( not has_soft_fail_values and not (hard_fail_threshold[c] or hard_fail_on_checks) and soft_fail[c] ) for c in sca_thresholds.keys() ): logging.debug( 'No failed checks, or soft_fail is True and soft_fail_on and hard_fail_on are empty for all SCA types - returning 0') return 0 if any( not has_soft_fail_values and not (hard_fail_threshold[c] or hard_fail_on_checks) and failed_checks_by_category[cast(CodeCategoryType, c)] for c in sca_thresholds.keys() ): logging.debug('There are failed checks and all soft/hard fail args are empty for one or more SCA reports - returning 1') return 1 else: non_sca_thresholds = cast(_ExitCodeThresholds, exit_code_thresholds) soft_fail_on_checks = non_sca_thresholds['soft_fail_checks'] soft_fail_threshold = non_sca_thresholds['soft_fail_threshold'] hard_fail_on_checks = non_sca_thresholds['hard_fail_checks'] hard_fail_threshold = non_sca_thresholds['hard_fail_threshold'] soft_fail = non_sca_thresholds['soft_fail'] has_soft_fail_values = soft_fail_on_checks or soft_fail_threshold has_hard_fail_values = hard_fail_threshold or hard_fail_on_checks if not has_soft_fail_values and not has_hard_fail_values and soft_fail: logging.debug('Soft_fail is True and soft_fail_on and hard_fail_on are empty - returning 0') return 0 elif not has_soft_fail_values and not has_hard_fail_values: logging.debug('There are failed checks and all soft/hard fail args are empty - returning 1') return 1 for failed_check in self.failed_checks: check_id = failed_check.check_id bc_check_id = failed_check.bc_check_id severity = failed_check.severity secret_validation_status = failed_check.validation_status if hasattr(failed_check, 'validation_status') else '' hf_threshold: Severity sf: bool if has_split_enforcement: category = CodeCategoryType.LICENSES if '_LIC_' in check_id else CodeCategoryType.VULNERABILITIES hard_fail_threshold = cast(Dict[str, Severity], hard_fail_threshold) hf_threshold = hard_fail_threshold[category] soft_fail = cast(Dict[str, bool], soft_fail) sf = soft_fail[category] else: hard_fail_threshold = cast(Severity, hard_fail_threshold) hf_threshold = hard_fail_threshold soft_fail = cast(bool, soft_fail) sf = soft_fail soft_fail_severity = severity and soft_fail_threshold and severity.level <= soft_fail_threshold.level hard_fail_severity = severity and hf_threshold and severity.level >= hf_threshold.level explicit_soft_fail = RunnerFilter.check_matches(check_id, bc_check_id, soft_fail_on_checks) explicit_hard_fail = RunnerFilter.check_matches(check_id, bc_check_id, hard_fail_on_checks) explicit_secrets_soft_fail = RunnerFilter.secret_validation_status_matches(secret_validation_status, soft_fail_on_checks) explicit_secrets_hard_fail = RunnerFilter.secret_validation_status_matches(secret_validation_status, hard_fail_on_checks) implicit_soft_fail = not explicit_hard_fail and not explicit_secrets_hard_fail and not soft_fail_on_checks and not soft_fail_threshold implicit_hard_fail = not explicit_soft_fail and not soft_fail_severity and not explicit_secrets_soft_fail if explicit_hard_fail or \ (hard_fail_severity and not explicit_soft_fail) or \ (implicit_hard_fail and not implicit_soft_fail and not sf): logging.debug(f'Check {check_id} (BC ID: {bc_check_id}, severity: {severity.level if severity else None} triggered hard fail - returning 1') return 1 logging.debug('No failed check triggered hard fail - returning 0') return 0 def is_empty(self, full: bool = False) -> bool: checks_count = ( len(self.passed_checks) + len(self.failed_checks) + len(self.skipped_checks) + len(self.parsing_errors) ) if full: checks_count += len(self.resources) + len(self.extra_resources) + len(self.image_cached_results) return checks_count == 0 def add_errors_to_output(self) -> str: ret_value = '' for error_title, errors_messages in self.errors.items(): ret_value += colored(f"Encountered {error_title} error - {len(errors_messages)} times\n\n", "red") return ret_value def print_console( self, is_quiet: bool = False, is_compact: bool = False, created_baseline_path: str | None = None, baseline: Baseline | None = None, use_bc_ids: bool = False, summary_position: str = 'top', openai_api_key: str | None = None, ) -> str: summary = self.get_summary() output_data = colored(f"{self.check_type} scan results:\n", "blue") if self.parsing_errors: message = "\nPassed checks: {}, Failed checks: {}, Skipped checks: {}, Parsing errors: {}\n\n".format( summary["passed"], summary["failed"], summary["skipped"], summary["parsing_errors"], ) else: if self.check_type == CheckType.SCA_PACKAGE or self.check_type.lower().startswith(CheckType.SAST): message = f"\nFailed checks: {summary['failed']}, Skipped checks: {summary['skipped']}\n\n" else: message = f"\nPassed checks: {summary['passed']}, Failed checks: {summary['failed']}, Skipped checks: {summary['skipped']}\n\n" if summary_position == 'top': output_data += colored(message, "cyan") # output for vulnerabilities is different if self.check_type in (CheckType.SCA_PACKAGE, CheckType.SCA_IMAGE): if self.failed_checks or self.skipped_checks: create_cli_output = create_sca_package_cli_output_v2 output_data += create_cli_output(self.check_type == CheckType.SCA_PACKAGE, self.failed_checks, self.skipped_checks) elif self.check_type == CheckType.POLICY_3D: if self.failed_checks or self.skipped_checks: output_data += create_3d_policy_cli_output(self.failed_checks, self.skipped_checks) # type:ignore[arg-type] else: if self.check_type.lower().startswith(CheckType.SAST): output_data += colored(f"Source code files scanned: {summary.get(SOURCE_FILES_COUNT, -1)}, " f"Policies found: {summary.get(POLICY_COUNT, -1)}\n\n", "cyan") policies_errors: str = str(summary.get(POLICIES_ERRORS, "")) if policies_errors: output_data += colored(f"Policy parsing failures ({summary.get(POLICIES_ERRORS_COUNT)}):\n{policies_errors}\n\n", "red") if not is_quiet: for record in self.passed_checks: output_data += record.to_string(compact=is_compact, use_bc_ids=use_bc_ids) if self.failed_checks: OpenAi(api_key=openai_api_key).enhance_records(runner_type=self.check_type, records=self.failed_checks) for record in self.failed_checks: output_data += record.to_string(compact=is_compact, use_bc_ids=use_bc_ids) if not is_quiet: for record in self.skipped_checks: output_data += record.to_string(compact=is_compact, use_bc_ids=use_bc_ids) if not is_quiet: for file in self.parsing_errors: output_data += colored(f"Error parsing file {file}ֿ\n", "red") if created_baseline_path: output_data += colored( f"Created a checkov baseline file at {created_baseline_path}", "blue", ) if baseline: output_data += colored( f"Baseline analysis report using {baseline.path} - only new failed checks with respect to the baseline are reported", "blue", ) if summary_position == 'bottom': output_data += colored(message, "cyan") return output_data def _print_parsing_error_console(file: str) -> None: print(colored(f"Error parsing file {file}", "red")) def get_junit_xml_string(ts: list[TestSuite]) -> str: return to_xml_report_string(ts) def print_failed_github_md(self, use_bc_ids: bool = False) -> str: result = [] for record in self.failed_checks: result.append( [ record.get_output_id(use_bc_ids), record.file_path, record.resource, record.check_name, record.guideline, ] ) if result: table = tabulate( result, headers=["check_id", "file", "resource", "check_name", "guideline"], tablefmt="github", showindex=True, ) output_data = f"### {self.check_type} scan results:\n\n{table}\n\n---\n" return output_data else: return "\n\n---\n\n" def get_test_suite(self, properties: Optional[Dict[str, Any]] = None, use_bc_ids: bool = False) -> TestSuite: """Creates a test suite for the JUnit XML report""" test_cases = [] records = self.passed_checks + self.failed_checks + self.skipped_checks for record in records: severity = BcSeverities.NONE if record.severity: severity = record.severity.name if self.check_type == CheckType.SCA_PACKAGE: if record.check_name != SCA_PACKAGE_SCAN_CHECK_NAME: continue if not record.vulnerability_details: # this shouldn't normally happen logging.warning(f"Vulnerability check without details {record.file_path}") continue check_id = record.vulnerability_details["id"] test_name_detail = f"{record.vulnerability_details['package_name']}: {record.vulnerability_details['package_version']}" class_name = f"{record.file_path}.{record.vulnerability_details['package_name']}" else: check_id = record.bc_check_id if use_bc_ids else record.check_id test_name_detail = record.check_name class_name = f"{record.file_path}.{record.resource}" test_name = f"[{severity}][{check_id}] {test_name_detail}" test_case = TestCase(name=test_name, file=record.file_path, classname=class_name) if record.check_result["result"] == CheckResult.FAILED: test_case.add_failure_info( message=record.check_name, output=self._create_test_case_failure_output(record) ) if record.check_result["result"] == CheckResult.SKIPPED: if self.check_type == CheckType.SCA_PACKAGE: test_case.add_skipped_info(f"{check_id} skipped for {test_name_detail}") else: test_case.add_skipped_info(record.check_result.get("suppress_comment", "")) test_cases.append(test_case) test_suite = TestSuite(name=f"{self.check_type} scan", test_cases=test_cases, properties=properties) return test_suite def create_test_suite_properties_block(config: argparse.Namespace) -> Dict[str, Any]: """Creates a dictionary without 'None' values for the JUnit XML properties block""" properties = {k: v for k, v in config.__dict__.items() if v is not None} return properties def _create_test_case_failure_output(self, record: Record) -> str: """Creates the failure output for a JUnit XML test case IaC example: Resource: azurerm_network_security_rule.fail_rdp File: /main.tf: 71-83 Guideline: https://docs.bridgecrew.io/docs/bc_azr_networking_2 71 | resource "azurerm_network_security_rule" "fail_rdp" { 72 | resource_group_name = azurerm_resource_group.example.name 73 | network_security_group_name=azurerm_network_security_group.example_rdp.name 74 | name = "fail_security_rule" 75 | direction = "Inbound" 76 | access = "Allow" 77 | protocol = "TCP" 78 | source_port_range = "*" 79 | destination_port_range = "3389" 80 | source_address_prefix = "*" 81 | destination_address_prefix = "*" 82 | priority = 120 83 | } SCA example: Description: Django before 1.11.27, 2.x before 2.2.9, and 3.x before 3.0.1 allows account takeover. Link: https://nvd.nist.gov/vuln/detail/CVE-2019-19844 Published Date: 2019-12-18T20:15:00+01:00 Base Score: 9.8 Vector: CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H Risk Factors: ['Attack complexity: low', 'Attack vector: network', 'Critical severity', 'Has fix'] Resource: requirements.txt.django File: /requirements.txt: 0-0 0 | django: 1.2 """ failure_output = [] if self.check_type == CheckType.SCA_PACKAGE: if record.vulnerability_details: lowest_fixed_version = record.vulnerability_details.get('lowest_fixed_version') if lowest_fixed_version is not None: fix = lowest_fixed_version else: fixlist = record.vulnerability_details.get('fixed_versions') if fixlist is not None: fix = fixlist failure_output.extend( [ "", f"Description: {record.description}", f"Link: {record.vulnerability_details.get('link')}", f"Published Date: {record.vulnerability_details.get('published_date')}", f"Base Score: {record.vulnerability_details.get('cvss')}", f"Vector: {record.vulnerability_details.get('vector')}", f"Risk Factors: {record.vulnerability_details.get('risk_factors')}", "Fix Details:", f" Status: {record.vulnerability_details.get('status')}", f" Fixed Version: {fix}", ] ) else: # this shouldn't normally happen logging.warning(f"Vulnerability check without details {record.file_path}") failure_output.extend( [ "", f"Resource: {record.resource}", ] ) if record.file_path: file_line = f"File: {record.file_path}" if record.file_line_range: file_line += f": {record.file_line_range[0]}-{record.file_line_range[1]}" failure_output.append(file_line) if self.check_type != CheckType.SCA_PACKAGE: failure_output.append(f"Guideline: {record.guideline}") if record.code_block: failure_output.append("") failure_output.append(record._code_line_string(code_block=record.code_block, colorized=False)) return "\n".join(failure_output) def print_json(self) -> None: print(self.get_json()) def enrich_plan_report( report: "Report", enriched_resources: Dict[str, Dict[str, Any]] ) -> "Report": # This enriches reports with the appropriate filepath, line numbers, and codeblock for record in report.failed_checks: resource_raw_id = Report.get_plan_resource_raw_id(record.resource) enriched_resource = enriched_resources.get(resource_raw_id) if enriched_resource: record.file_path = enriched_resource["scanned_file"] record.file_line_range = enriched_resource["entity_lines_range"] record.code_block = enriched_resource["entity_code_lines"] return report def handle_skipped_checks( report: "Report", enriched_resources: Dict[str, Dict[str, Any]] ) -> "Report": module_address_len = len("module.") skip_records = [] for record in report.failed_checks: resource_raw_id = Report.get_plan_resource_raw_id(record.resource) resource_skips = enriched_resources.get(resource_raw_id, {}).get( "skipped_checks", [] ) for skip in resource_skips: if record.check_id in skip["id"]: # Mark for removal and add it as a skipped record. It is not safe to remove # the record from failed_checks immediately because we're iterating over it skip_records.append(record) record.check_result["result"] = CheckResult.SKIPPED record.check_result["suppress_comment"] = skip["suppress_comment"] report.add_record(record) if record.resource_address and record.resource_address.startswith("module."): module_path = record.resource_address[module_address_len:record.resource_address.index('.', module_address_len + 1)] module_enrichments = enriched_resources.get(module_path, {}) for module_skip in module_enrichments.get("skipped_checks", []): if record.check_id in module_skip["id"]: skip_records.append(record) record.check_result["result"] = CheckResult.SKIPPED record.check_result["suppress_comment"] = module_skip["suppress_comment"] report.add_record(record) for record in skip_records: if record in report.failed_checks: report.failed_checks.remove(record) return report def get_plan_resource_raw_id(resource_id: str) -> str: """ return the resource raw id without the modules and the indexes example: from resource_id='module.module_name.type.name[1]' return 'type.name' """ resource_raw_id = ".".join(resource_id.split(".")[-2:]) if '[' in resource_raw_id: resource_raw_id = resource_raw_id[:resource_raw_id.index('[')] return resource_raw_id def from_reduced_json(cls, json_report: dict[str, Any], check_type: str) -> Report: report = Report(check_type) report.image_cached_results = json_report['image_cached_results'] all_json_records = json_report["checks"]["passed_checks"] + \ json_report["checks"]["failed_checks"] + \ json_report["checks"]["skipped_checks"] for json_record in all_json_records: report.add_record( Record.from_reduced_json(json_record) ) return report The provided code snippet includes necessary dependencies for implementing the `reduce_scan_reports` function. Write a Python function `def reduce_scan_reports(scan_reports: list[Report], on_prem: Optional[bool] = False) -> dict[str, _ReducedScanReport]` to solve the following problem: Transform checkov reports objects into compact dictionaries :param scan_reports: List of checkov output reports :return: dictionary of Here is the function: def reduce_scan_reports(scan_reports: list[Report], on_prem: Optional[bool] = False) -> dict[str, _ReducedScanReport]: """ Transform checkov reports objects into compact dictionaries :param scan_reports: List of checkov output reports :return: dictionary of """ reduced_scan_reports: dict[str, _ReducedScanReport] = {} for report in scan_reports: check_type = report.check_type if check_type.startswith((SAST_FRAMEWORK_PREFIX, CDK_FRAMEWORK_PREFIX)): continue reduced_keys = secrets_check_reduced_keys if check_type == CheckType.SECRETS else check_reduced_keys if on_prem: reduced_keys = tuple(k for k in reduced_keys if k != 'code_block') reduced_scan_reports[check_type] = \ { "checks": { "passed_checks": [ {k: getattr(check, k) for k in reduced_keys} for check in report.passed_checks], "failed_checks": [ {k: getattr(check, k) for k in reduced_keys} for check in report.failed_checks], "skipped_checks": [ {k: getattr(check, k) for k in reduced_keys} for check in report.skipped_checks] }, "image_cached_results": report.image_cached_results } return reduced_scan_reports
Transform checkov reports objects into compact dictionaries :param scan_reports: List of checkov output reports :return: dictionary of
2,333
from __future__ import annotations import logging import os import json import itertools from concurrent import futures from io import StringIO from typing import Any, TYPE_CHECKING, Optional, Dict from collections import defaultdict import dpath from rustworkx import PyDiGraph, digraph_node_link_json from checkov.common.sast.consts import CDK_FRAMEWORK_PREFIX, SAST_FRAMEWORK_PREFIX from checkov.common.bridgecrew.check_type import CheckType from checkov.common.models.consts import SUPPORTED_FILE_EXTENSIONS from checkov.common.typing import _ReducedScanReport, LibraryGraph from checkov.common.util.file_utils import compress_multiple_strings_ios_tar from checkov.common.util.json_utils import CustomJSONEncoder checkov_results_prefix = 'checkov_results' def _put_json_object(s3_client: S3Client, json_obj: Any, bucket: str, object_path: str, log_stack_trace_on_error: bool = True) -> None: try: s3_client.put_object(Bucket=bucket, Key=object_path, Body=json.dumps(json_obj, cls=CustomJSONEncoder)) except Exception: logging.error(f"failed to persist object into S3 bucket {bucket} - {object_path}", exc_info=log_stack_trace_on_error) raise def persist_assets_results(check_type: str, assets_report: Dict[str, Any], s3_client: Optional[S3Client], bucket: Optional[str], full_repo_object_key: Optional[str]) -> str: if not s3_client or not bucket or not full_repo_object_key: return '' check_result_object_path = f'{full_repo_object_key}/{checkov_results_prefix}/{check_type}/assets.json' _put_json_object(s3_client, assets_report, bucket, check_result_object_path) return check_result_object_path
null
2,334
from __future__ import annotations import logging import os import json import itertools from concurrent import futures from io import StringIO from typing import Any, TYPE_CHECKING, Optional, Dict from collections import defaultdict import dpath from rustworkx import PyDiGraph, digraph_node_link_json from checkov.common.sast.consts import CDK_FRAMEWORK_PREFIX, SAST_FRAMEWORK_PREFIX from checkov.common.bridgecrew.check_type import CheckType from checkov.common.models.consts import SUPPORTED_FILE_EXTENSIONS from checkov.common.typing import _ReducedScanReport, LibraryGraph from checkov.common.util.file_utils import compress_multiple_strings_ios_tar from checkov.common.util.json_utils import CustomJSONEncoder checkov_results_prefix = 'checkov_results' def _put_json_object(s3_client: S3Client, json_obj: Any, bucket: str, object_path: str, log_stack_trace_on_error: bool = True) -> None: try: s3_client.put_object(Bucket=bucket, Key=object_path, Body=json.dumps(json_obj, cls=CustomJSONEncoder)) except Exception: logging.error(f"failed to persist object into S3 bucket {bucket} - {object_path}", exc_info=log_stack_trace_on_error) raise def persist_reachability_results(check_type: str, reachability_report: Dict[str, Any], s3_client: Optional[S3Client], bucket: Optional[str], full_repo_object_key: Optional[str]) -> str: if not s3_client or not bucket or not full_repo_object_key: return '' check_result_object_path = f'{full_repo_object_key}/{checkov_results_prefix}/{check_type}/reachability_report.json' _put_json_object(s3_client, reachability_report, bucket, check_result_object_path) return check_result_object_path
null
2,335
from __future__ import annotations import logging import os import json import itertools from concurrent import futures from io import StringIO from typing import Any, TYPE_CHECKING, Optional, Dict from collections import defaultdict import dpath from rustworkx import PyDiGraph, digraph_node_link_json from checkov.common.sast.consts import CDK_FRAMEWORK_PREFIX, SAST_FRAMEWORK_PREFIX from checkov.common.bridgecrew.check_type import CheckType from checkov.common.models.consts import SUPPORTED_FILE_EXTENSIONS from checkov.common.typing import _ReducedScanReport, LibraryGraph from checkov.common.util.file_utils import compress_multiple_strings_ios_tar from checkov.common.util.json_utils import CustomJSONEncoder checkov_results_prefix = 'checkov_results' def _put_json_object(s3_client: S3Client, json_obj: Any, bucket: str, object_path: str, log_stack_trace_on_error: bool = True) -> None: try: s3_client.put_object(Bucket=bucket, Key=object_path, Body=json.dumps(json_obj, cls=CustomJSONEncoder)) except Exception: logging.error(f"failed to persist object into S3 bucket {bucket} - {object_path}", exc_info=log_stack_trace_on_error) raise class _ReducedScanReport(TypedDict): checks: _ReducedScanReportCheck image_cached_results: list[dict[str, Any]] The provided code snippet includes necessary dependencies for implementing the `persist_checks_results` function. Write a Python function `def persist_checks_results( reduced_scan_reports: dict[str, _ReducedScanReport], s3_client: S3Client, bucket: str, full_repo_object_key: str ) -> dict[str, str]` to solve the following problem: Save reduced scan reports into bridgecrew's platform :return: List of checks results path of all runners Here is the function: def persist_checks_results( reduced_scan_reports: dict[str, _ReducedScanReport], s3_client: S3Client, bucket: str, full_repo_object_key: str ) -> dict[str, str]: """ Save reduced scan reports into bridgecrew's platform :return: List of checks results path of all runners """ checks_results_paths = {} for check_type, reduced_report in reduced_scan_reports.items(): check_result_object_path = f'{full_repo_object_key}/{checkov_results_prefix}/{check_type}/checks_results.json' checks_results_paths[check_type] = check_result_object_path _put_json_object(s3_client, reduced_report, bucket, check_result_object_path) return checks_results_paths
Save reduced scan reports into bridgecrew's platform :return: List of checks results path of all runners
2,336
from __future__ import annotations import logging import os import json import itertools from concurrent import futures from io import StringIO from typing import Any, TYPE_CHECKING, Optional, Dict from collections import defaultdict import dpath from rustworkx import PyDiGraph, digraph_node_link_json from checkov.common.sast.consts import CDK_FRAMEWORK_PREFIX, SAST_FRAMEWORK_PREFIX from checkov.common.bridgecrew.check_type import CheckType from checkov.common.models.consts import SUPPORTED_FILE_EXTENSIONS from checkov.common.typing import _ReducedScanReport, LibraryGraph from checkov.common.util.file_utils import compress_multiple_strings_ios_tar from checkov.common.util.json_utils import CustomJSONEncoder checkov_results_prefix = 'checkov_results' def persist_run_metadata( run_metadata: dict[str, str | list[str]], s3_client: S3Client, bucket: str, full_repo_object_key: str, use_checkov_results: bool = True ) -> None: object_path = f'{full_repo_object_key}/{checkov_results_prefix}/run_metadata.json' if use_checkov_results else f'{full_repo_object_key}/run_metadata.json' try: s3_client.put_object(Bucket=bucket, Key=object_path, Body=json.dumps(run_metadata, indent=2)) except Exception: logging.error(f"failed to persist run metadata into S3 bucket {bucket}", exc_info=True) raise
null
2,337
from __future__ import annotations import logging import os import json import itertools from concurrent import futures from io import StringIO from typing import Any, TYPE_CHECKING, Optional, Dict from collections import defaultdict import dpath from rustworkx import PyDiGraph, digraph_node_link_json from checkov.common.sast.consts import CDK_FRAMEWORK_PREFIX, SAST_FRAMEWORK_PREFIX from checkov.common.bridgecrew.check_type import CheckType from checkov.common.models.consts import SUPPORTED_FILE_EXTENSIONS from checkov.common.typing import _ReducedScanReport, LibraryGraph from checkov.common.util.file_utils import compress_multiple_strings_ios_tar from checkov.common.util.json_utils import CustomJSONEncoder def compress_multiple_strings_ios_tar(logs_streams: Dict[str, io.StringIO]) -> io.BytesIO: def persist_multiple_logs_stream(logs_streams: Dict[str, StringIO], s3_client: S3Client, bucket: str, full_repo_object_key: str) -> None: file_io = compress_multiple_strings_ios_tar(logs_streams) object_path = f'{full_repo_object_key}/logs_files.tar.gz' try: s3_client.put_object(Bucket=bucket, Key=object_path, Body=file_io) except Exception: logging.error(f"failed to persist logs stream into S3 bucket {bucket}", exc_info=True) raise
null
2,338
from __future__ import annotations import logging import os import json import itertools from concurrent import futures from io import StringIO from typing import Any, TYPE_CHECKING, Optional, Dict from collections import defaultdict import dpath from rustworkx import PyDiGraph, digraph_node_link_json from checkov.common.sast.consts import CDK_FRAMEWORK_PREFIX, SAST_FRAMEWORK_PREFIX from checkov.common.bridgecrew.check_type import CheckType from checkov.common.models.consts import SUPPORTED_FILE_EXTENSIONS from checkov.common.typing import _ReducedScanReport, LibraryGraph from checkov.common.util.file_utils import compress_multiple_strings_ios_tar from checkov.common.util.json_utils import CustomJSONEncoder checkov_results_prefix = 'checkov_results' def _put_json_object(s3_client: S3Client, json_obj: Any, bucket: str, object_path: str, log_stack_trace_on_error: bool = True) -> None: try: s3_client.put_object(Bucket=bucket, Key=object_path, Body=json.dumps(json_obj, cls=CustomJSONEncoder)) except Exception: logging.error(f"failed to persist object into S3 bucket {bucket} - {object_path}", exc_info=log_stack_trace_on_error) raise def _extract_checks_metadata(report: Report, full_repo_object_key: str, on_prem: bool) -> dict[str, dict[str, Any]]: metadata: dict[str, dict[str, Any]] = defaultdict(dict) for check in itertools.chain(report.passed_checks, report.failed_checks, report.skipped_checks): metadata_key = f'{check.file_path}:{check.resource}' check_meta = {k: getattr(check, k, "") for k in check_metadata_keys} check_meta['file_object_path'] = full_repo_object_key + check.file_path if on_prem: check_meta['code_block'] = [] metadata[metadata_key][check.check_id] = check_meta return metadata SAST_FRAMEWORK_PREFIX = 'sast' CDK_FRAMEWORK_PREFIX = 'cdk' class Report: def __init__(self, check_type: str): self.check_type = check_type self.passed_checks: list[Record] = [] self.failed_checks: list[Record] = [] self.skipped_checks: list[Record] = [] self.parsing_errors: list[str] = [] self.resources: set[str] = set() self.extra_resources: set[ExtraResource] = set() self.image_cached_results: List[dict[str, Any]] = [] self.error_status: ErrorStatus = ErrorStatus.SUCCESS def errors(self) -> Dict[str, List[str]]: return dict() def set_error_status(self, error_status: ErrorStatus) -> None: self.error_status = error_status def add_parsing_errors(self, errors: "Iterable[str]") -> None: for file in errors: self.add_parsing_error(file) def add_parsing_error(self, file: str) -> None: if file: self.parsing_errors.append(file) def add_resource(self, resource: str) -> None: self.resources.add(resource) def add_record(self, record: Record) -> None: if record.check_result["result"] == CheckResult.PASSED: self.passed_checks.append(record) if record.check_result["result"] == CheckResult.FAILED: self.failed_checks.append(record) if record.check_result["result"] == CheckResult.SKIPPED: self.skipped_checks.append(record) def get_summary(self) -> Dict[str, Union[int, str]]: return { "passed": len(self.passed_checks), "failed": len(self.failed_checks), "skipped": len(self.skipped_checks), "parsing_errors": len(self.parsing_errors), "resource_count": len(self.resources), "checkov_version": version, } def get_json(self) -> str: return json.dumps(self.get_dict(), indent=4, cls=CustomJSONEncoder) def get_all_records(self) -> List[Record]: return self.failed_checks + self.passed_checks + self.skipped_checks def get_dict(self, is_quiet: bool = False, url: str | None = None, full_report: bool = False, s3_setup_failed: bool = False, support_path: str | None = None) -> dict[str, Any]: if not url and not s3_setup_failed: url = "Add an api key '--bc-api-key <api-key>' to see more detailed insights via https://bridgecrew.cloud" elif s3_setup_failed: url = S3_UPLOAD_DETAILS_MESSAGE if is_quiet: return { "check_type": self.check_type, "results": { "failed_checks": [check.__dict__ for check in self.failed_checks] }, "summary": self.get_summary(), } if full_report: return { "check_type": self.check_type, "checks": { "passed_checks": [check.__dict__ for check in self.passed_checks], "failed_checks": [check.__dict__ for check in self.failed_checks], "skipped_checks": [check.__dict__ for check in self.skipped_checks] }, "image_cached_results": [res.__dict__ for res in self.image_cached_results] } else: result = { "check_type": self.check_type, "results": { "passed_checks": [check.__dict__ for check in self.passed_checks], "failed_checks": [check.__dict__ for check in self.failed_checks], "skipped_checks": [check.__dict__ for check in self.skipped_checks], "parsing_errors": list(self.parsing_errors), }, "summary": self.get_summary(), "url": url, } if support_path: result["support_path"] = support_path return result def get_exit_code(self, exit_code_thresholds: Union[_ExitCodeThresholds, _ScaExitCodeThresholds]) -> int: """ Returns the appropriate exit code depending on the flags that are passed in. :return: Exit code 0 or 1. """ hard_fail_on_parsing_errors = os.getenv(PARSE_ERROR_FAIL_FLAG, "false").lower() == 'true' logging.debug(f'In get_exit_code; exit code thresholds: {exit_code_thresholds}, hard_fail_on_parsing_errors: {hard_fail_on_parsing_errors}') if self.parsing_errors and hard_fail_on_parsing_errors: logging.debug('hard_fail_on_parsing_errors is True and there were parsing errors - returning 1') return 1 if not self.failed_checks: logging.debug('No failed checks in this report - returning 0') return 0 # we will have two different sets of logic in this method, determined by this variable. # if we are using enforcement rules, then there are two different sets of thresholds that apply for licenses and vulnerabilities # and we have to handle that throughout while processing the report # if we are not using enforcement rules, then we can combine licenses and vulnerabilities like normal and same as all other report types # this determination is made in runner_registry.get_fail_thresholds has_split_enforcement = CodeCategoryType.LICENSES in exit_code_thresholds hard_fail_threshold: Optional[Severity | Dict[str, Severity]] soft_fail: Optional[bool | Dict[str, bool]] if has_split_enforcement: sca_thresholds = cast(_ScaExitCodeThresholds, exit_code_thresholds) # these three are the same even in split enforcement rules generic_thresholds = cast(_ExitCodeThresholds, next(iter(sca_thresholds.values()))) soft_fail_on_checks = generic_thresholds['soft_fail_checks'] soft_fail_threshold = generic_thresholds['soft_fail_threshold'] hard_fail_on_checks = generic_thresholds['hard_fail_checks'] # these two can be different for licenses / vulnerabilities hard_fail_threshold = {category: thresholds['hard_fail_threshold'] for category, thresholds in sca_thresholds.items()} # type:ignore[index] # thinks it's an object, can't possibly be more clear soft_fail = {category: thresholds['soft_fail'] for category, thresholds in sca_thresholds.items()} # type:ignore[index] # thinks it's an object failed_checks_by_category = { CodeCategoryType.LICENSES: [fc for fc in self.failed_checks if '_LIC_' in fc.check_id], CodeCategoryType.VULNERABILITIES: [fc for fc in self.failed_checks if '_VUL_' in fc.check_id] } has_soft_fail_values = soft_fail_on_checks or soft_fail_threshold if all( not failed_checks_by_category[cast(CodeCategoryType, c)] or ( not has_soft_fail_values and not (hard_fail_threshold[c] or hard_fail_on_checks) and soft_fail[c] ) for c in sca_thresholds.keys() ): logging.debug( 'No failed checks, or soft_fail is True and soft_fail_on and hard_fail_on are empty for all SCA types - returning 0') return 0 if any( not has_soft_fail_values and not (hard_fail_threshold[c] or hard_fail_on_checks) and failed_checks_by_category[cast(CodeCategoryType, c)] for c in sca_thresholds.keys() ): logging.debug('There are failed checks and all soft/hard fail args are empty for one or more SCA reports - returning 1') return 1 else: non_sca_thresholds = cast(_ExitCodeThresholds, exit_code_thresholds) soft_fail_on_checks = non_sca_thresholds['soft_fail_checks'] soft_fail_threshold = non_sca_thresholds['soft_fail_threshold'] hard_fail_on_checks = non_sca_thresholds['hard_fail_checks'] hard_fail_threshold = non_sca_thresholds['hard_fail_threshold'] soft_fail = non_sca_thresholds['soft_fail'] has_soft_fail_values = soft_fail_on_checks or soft_fail_threshold has_hard_fail_values = hard_fail_threshold or hard_fail_on_checks if not has_soft_fail_values and not has_hard_fail_values and soft_fail: logging.debug('Soft_fail is True and soft_fail_on and hard_fail_on are empty - returning 0') return 0 elif not has_soft_fail_values and not has_hard_fail_values: logging.debug('There are failed checks and all soft/hard fail args are empty - returning 1') return 1 for failed_check in self.failed_checks: check_id = failed_check.check_id bc_check_id = failed_check.bc_check_id severity = failed_check.severity secret_validation_status = failed_check.validation_status if hasattr(failed_check, 'validation_status') else '' hf_threshold: Severity sf: bool if has_split_enforcement: category = CodeCategoryType.LICENSES if '_LIC_' in check_id else CodeCategoryType.VULNERABILITIES hard_fail_threshold = cast(Dict[str, Severity], hard_fail_threshold) hf_threshold = hard_fail_threshold[category] soft_fail = cast(Dict[str, bool], soft_fail) sf = soft_fail[category] else: hard_fail_threshold = cast(Severity, hard_fail_threshold) hf_threshold = hard_fail_threshold soft_fail = cast(bool, soft_fail) sf = soft_fail soft_fail_severity = severity and soft_fail_threshold and severity.level <= soft_fail_threshold.level hard_fail_severity = severity and hf_threshold and severity.level >= hf_threshold.level explicit_soft_fail = RunnerFilter.check_matches(check_id, bc_check_id, soft_fail_on_checks) explicit_hard_fail = RunnerFilter.check_matches(check_id, bc_check_id, hard_fail_on_checks) explicit_secrets_soft_fail = RunnerFilter.secret_validation_status_matches(secret_validation_status, soft_fail_on_checks) explicit_secrets_hard_fail = RunnerFilter.secret_validation_status_matches(secret_validation_status, hard_fail_on_checks) implicit_soft_fail = not explicit_hard_fail and not explicit_secrets_hard_fail and not soft_fail_on_checks and not soft_fail_threshold implicit_hard_fail = not explicit_soft_fail and not soft_fail_severity and not explicit_secrets_soft_fail if explicit_hard_fail or \ (hard_fail_severity and not explicit_soft_fail) or \ (implicit_hard_fail and not implicit_soft_fail and not sf): logging.debug(f'Check {check_id} (BC ID: {bc_check_id}, severity: {severity.level if severity else None} triggered hard fail - returning 1') return 1 logging.debug('No failed check triggered hard fail - returning 0') return 0 def is_empty(self, full: bool = False) -> bool: checks_count = ( len(self.passed_checks) + len(self.failed_checks) + len(self.skipped_checks) + len(self.parsing_errors) ) if full: checks_count += len(self.resources) + len(self.extra_resources) + len(self.image_cached_results) return checks_count == 0 def add_errors_to_output(self) -> str: ret_value = '' for error_title, errors_messages in self.errors.items(): ret_value += colored(f"Encountered {error_title} error - {len(errors_messages)} times\n\n", "red") return ret_value def print_console( self, is_quiet: bool = False, is_compact: bool = False, created_baseline_path: str | None = None, baseline: Baseline | None = None, use_bc_ids: bool = False, summary_position: str = 'top', openai_api_key: str | None = None, ) -> str: summary = self.get_summary() output_data = colored(f"{self.check_type} scan results:\n", "blue") if self.parsing_errors: message = "\nPassed checks: {}, Failed checks: {}, Skipped checks: {}, Parsing errors: {}\n\n".format( summary["passed"], summary["failed"], summary["skipped"], summary["parsing_errors"], ) else: if self.check_type == CheckType.SCA_PACKAGE or self.check_type.lower().startswith(CheckType.SAST): message = f"\nFailed checks: {summary['failed']}, Skipped checks: {summary['skipped']}\n\n" else: message = f"\nPassed checks: {summary['passed']}, Failed checks: {summary['failed']}, Skipped checks: {summary['skipped']}\n\n" if summary_position == 'top': output_data += colored(message, "cyan") # output for vulnerabilities is different if self.check_type in (CheckType.SCA_PACKAGE, CheckType.SCA_IMAGE): if self.failed_checks or self.skipped_checks: create_cli_output = create_sca_package_cli_output_v2 output_data += create_cli_output(self.check_type == CheckType.SCA_PACKAGE, self.failed_checks, self.skipped_checks) elif self.check_type == CheckType.POLICY_3D: if self.failed_checks or self.skipped_checks: output_data += create_3d_policy_cli_output(self.failed_checks, self.skipped_checks) # type:ignore[arg-type] else: if self.check_type.lower().startswith(CheckType.SAST): output_data += colored(f"Source code files scanned: {summary.get(SOURCE_FILES_COUNT, -1)}, " f"Policies found: {summary.get(POLICY_COUNT, -1)}\n\n", "cyan") policies_errors: str = str(summary.get(POLICIES_ERRORS, "")) if policies_errors: output_data += colored(f"Policy parsing failures ({summary.get(POLICIES_ERRORS_COUNT)}):\n{policies_errors}\n\n", "red") if not is_quiet: for record in self.passed_checks: output_data += record.to_string(compact=is_compact, use_bc_ids=use_bc_ids) if self.failed_checks: OpenAi(api_key=openai_api_key).enhance_records(runner_type=self.check_type, records=self.failed_checks) for record in self.failed_checks: output_data += record.to_string(compact=is_compact, use_bc_ids=use_bc_ids) if not is_quiet: for record in self.skipped_checks: output_data += record.to_string(compact=is_compact, use_bc_ids=use_bc_ids) if not is_quiet: for file in self.parsing_errors: output_data += colored(f"Error parsing file {file}ֿ\n", "red") if created_baseline_path: output_data += colored( f"Created a checkov baseline file at {created_baseline_path}", "blue", ) if baseline: output_data += colored( f"Baseline analysis report using {baseline.path} - only new failed checks with respect to the baseline are reported", "blue", ) if summary_position == 'bottom': output_data += colored(message, "cyan") return output_data def _print_parsing_error_console(file: str) -> None: print(colored(f"Error parsing file {file}", "red")) def get_junit_xml_string(ts: list[TestSuite]) -> str: return to_xml_report_string(ts) def print_failed_github_md(self, use_bc_ids: bool = False) -> str: result = [] for record in self.failed_checks: result.append( [ record.get_output_id(use_bc_ids), record.file_path, record.resource, record.check_name, record.guideline, ] ) if result: table = tabulate( result, headers=["check_id", "file", "resource", "check_name", "guideline"], tablefmt="github", showindex=True, ) output_data = f"### {self.check_type} scan results:\n\n{table}\n\n---\n" return output_data else: return "\n\n---\n\n" def get_test_suite(self, properties: Optional[Dict[str, Any]] = None, use_bc_ids: bool = False) -> TestSuite: """Creates a test suite for the JUnit XML report""" test_cases = [] records = self.passed_checks + self.failed_checks + self.skipped_checks for record in records: severity = BcSeverities.NONE if record.severity: severity = record.severity.name if self.check_type == CheckType.SCA_PACKAGE: if record.check_name != SCA_PACKAGE_SCAN_CHECK_NAME: continue if not record.vulnerability_details: # this shouldn't normally happen logging.warning(f"Vulnerability check without details {record.file_path}") continue check_id = record.vulnerability_details["id"] test_name_detail = f"{record.vulnerability_details['package_name']}: {record.vulnerability_details['package_version']}" class_name = f"{record.file_path}.{record.vulnerability_details['package_name']}" else: check_id = record.bc_check_id if use_bc_ids else record.check_id test_name_detail = record.check_name class_name = f"{record.file_path}.{record.resource}" test_name = f"[{severity}][{check_id}] {test_name_detail}" test_case = TestCase(name=test_name, file=record.file_path, classname=class_name) if record.check_result["result"] == CheckResult.FAILED: test_case.add_failure_info( message=record.check_name, output=self._create_test_case_failure_output(record) ) if record.check_result["result"] == CheckResult.SKIPPED: if self.check_type == CheckType.SCA_PACKAGE: test_case.add_skipped_info(f"{check_id} skipped for {test_name_detail}") else: test_case.add_skipped_info(record.check_result.get("suppress_comment", "")) test_cases.append(test_case) test_suite = TestSuite(name=f"{self.check_type} scan", test_cases=test_cases, properties=properties) return test_suite def create_test_suite_properties_block(config: argparse.Namespace) -> Dict[str, Any]: """Creates a dictionary without 'None' values for the JUnit XML properties block""" properties = {k: v for k, v in config.__dict__.items() if v is not None} return properties def _create_test_case_failure_output(self, record: Record) -> str: """Creates the failure output for a JUnit XML test case IaC example: Resource: azurerm_network_security_rule.fail_rdp File: /main.tf: 71-83 Guideline: https://docs.bridgecrew.io/docs/bc_azr_networking_2 71 | resource "azurerm_network_security_rule" "fail_rdp" { 72 | resource_group_name = azurerm_resource_group.example.name 73 | network_security_group_name=azurerm_network_security_group.example_rdp.name 74 | name = "fail_security_rule" 75 | direction = "Inbound" 76 | access = "Allow" 77 | protocol = "TCP" 78 | source_port_range = "*" 79 | destination_port_range = "3389" 80 | source_address_prefix = "*" 81 | destination_address_prefix = "*" 82 | priority = 120 83 | } SCA example: Description: Django before 1.11.27, 2.x before 2.2.9, and 3.x before 3.0.1 allows account takeover. Link: https://nvd.nist.gov/vuln/detail/CVE-2019-19844 Published Date: 2019-12-18T20:15:00+01:00 Base Score: 9.8 Vector: CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H Risk Factors: ['Attack complexity: low', 'Attack vector: network', 'Critical severity', 'Has fix'] Resource: requirements.txt.django File: /requirements.txt: 0-0 0 | django: 1.2 """ failure_output = [] if self.check_type == CheckType.SCA_PACKAGE: if record.vulnerability_details: lowest_fixed_version = record.vulnerability_details.get('lowest_fixed_version') if lowest_fixed_version is not None: fix = lowest_fixed_version else: fixlist = record.vulnerability_details.get('fixed_versions') if fixlist is not None: fix = fixlist failure_output.extend( [ "", f"Description: {record.description}", f"Link: {record.vulnerability_details.get('link')}", f"Published Date: {record.vulnerability_details.get('published_date')}", f"Base Score: {record.vulnerability_details.get('cvss')}", f"Vector: {record.vulnerability_details.get('vector')}", f"Risk Factors: {record.vulnerability_details.get('risk_factors')}", "Fix Details:", f" Status: {record.vulnerability_details.get('status')}", f" Fixed Version: {fix}", ] ) else: # this shouldn't normally happen logging.warning(f"Vulnerability check without details {record.file_path}") failure_output.extend( [ "", f"Resource: {record.resource}", ] ) if record.file_path: file_line = f"File: {record.file_path}" if record.file_line_range: file_line += f": {record.file_line_range[0]}-{record.file_line_range[1]}" failure_output.append(file_line) if self.check_type != CheckType.SCA_PACKAGE: failure_output.append(f"Guideline: {record.guideline}") if record.code_block: failure_output.append("") failure_output.append(record._code_line_string(code_block=record.code_block, colorized=False)) return "\n".join(failure_output) def print_json(self) -> None: print(self.get_json()) def enrich_plan_report( report: "Report", enriched_resources: Dict[str, Dict[str, Any]] ) -> "Report": # This enriches reports with the appropriate filepath, line numbers, and codeblock for record in report.failed_checks: resource_raw_id = Report.get_plan_resource_raw_id(record.resource) enriched_resource = enriched_resources.get(resource_raw_id) if enriched_resource: record.file_path = enriched_resource["scanned_file"] record.file_line_range = enriched_resource["entity_lines_range"] record.code_block = enriched_resource["entity_code_lines"] return report def handle_skipped_checks( report: "Report", enriched_resources: Dict[str, Dict[str, Any]] ) -> "Report": module_address_len = len("module.") skip_records = [] for record in report.failed_checks: resource_raw_id = Report.get_plan_resource_raw_id(record.resource) resource_skips = enriched_resources.get(resource_raw_id, {}).get( "skipped_checks", [] ) for skip in resource_skips: if record.check_id in skip["id"]: # Mark for removal and add it as a skipped record. It is not safe to remove # the record from failed_checks immediately because we're iterating over it skip_records.append(record) record.check_result["result"] = CheckResult.SKIPPED record.check_result["suppress_comment"] = skip["suppress_comment"] report.add_record(record) if record.resource_address and record.resource_address.startswith("module."): module_path = record.resource_address[module_address_len:record.resource_address.index('.', module_address_len + 1)] module_enrichments = enriched_resources.get(module_path, {}) for module_skip in module_enrichments.get("skipped_checks", []): if record.check_id in module_skip["id"]: skip_records.append(record) record.check_result["result"] = CheckResult.SKIPPED record.check_result["suppress_comment"] = module_skip["suppress_comment"] report.add_record(record) for record in skip_records: if record in report.failed_checks: report.failed_checks.remove(record) return report def get_plan_resource_raw_id(resource_id: str) -> str: """ return the resource raw id without the modules and the indexes example: from resource_id='module.module_name.type.name[1]' return 'type.name' """ resource_raw_id = ".".join(resource_id.split(".")[-2:]) if '[' in resource_raw_id: resource_raw_id = resource_raw_id[:resource_raw_id.index('[')] return resource_raw_id def from_reduced_json(cls, json_report: dict[str, Any], check_type: str) -> Report: report = Report(check_type) report.image_cached_results = json_report['image_cached_results'] all_json_records = json_report["checks"]["passed_checks"] + \ json_report["checks"]["failed_checks"] + \ json_report["checks"]["skipped_checks"] for json_record in all_json_records: report.add_record( Record.from_reduced_json(json_record) ) return report The provided code snippet includes necessary dependencies for implementing the `enrich_and_persist_checks_metadata` function. Write a Python function `def enrich_and_persist_checks_metadata( scan_reports: list[Report], s3_client: S3Client, bucket: str, full_repo_object_key: str, on_prem: bool ) -> dict[str, dict[str, str]]` to solve the following problem: Save checks metadata into bridgecrew's platform :return: Here is the function: def enrich_and_persist_checks_metadata( scan_reports: list[Report], s3_client: S3Client, bucket: str, full_repo_object_key: str, on_prem: bool ) -> dict[str, dict[str, str]]: """ Save checks metadata into bridgecrew's platform :return: """ checks_metadata_paths: dict[str, dict[str, str]] = {} for scan_report in scan_reports: check_type = scan_report.check_type if check_type.startswith((SAST_FRAMEWORK_PREFIX, CDK_FRAMEWORK_PREFIX)): continue checks_metadata_object = _extract_checks_metadata(scan_report, full_repo_object_key, on_prem) checks_metadata_object_path = f'{full_repo_object_key}/{checkov_results_prefix}/{check_type}/checks_metadata.json' dpath.new(checks_metadata_paths, f"{check_type}/checks_metadata_path", checks_metadata_object_path) _put_json_object(s3_client, checks_metadata_object, bucket, checks_metadata_object_path) return checks_metadata_paths
Save checks metadata into bridgecrew's platform :return:
2,339
from __future__ import annotations import logging import os import json import itertools from concurrent import futures from io import StringIO from typing import Any, TYPE_CHECKING, Optional, Dict from collections import defaultdict import dpath from rustworkx import PyDiGraph, digraph_node_link_json from checkov.common.sast.consts import CDK_FRAMEWORK_PREFIX, SAST_FRAMEWORK_PREFIX from checkov.common.bridgecrew.check_type import CheckType from checkov.common.models.consts import SUPPORTED_FILE_EXTENSIONS from checkov.common.typing import _ReducedScanReport, LibraryGraph from checkov.common.util.file_utils import compress_multiple_strings_ios_tar from checkov.common.util.json_utils import CustomJSONEncoder FILE_NAME_NETWORKX = 'graph_networkx.json' FILE_NAME_RUSTWORKX = 'graph_rustworkx.json' def _put_json_object(s3_client: S3Client, json_obj: Any, bucket: str, object_path: str, log_stack_trace_on_error: bool = True) -> None: try: s3_client.put_object(Bucket=bucket, Key=object_path, Body=json.dumps(json_obj, cls=CustomJSONEncoder)) except Exception: logging.error(f"failed to persist object into S3 bucket {bucket} - {object_path}", exc_info=log_stack_trace_on_error) raise LibraryGraph: TypeAlias = "Union[DiGraph, _RustworkxGraph]" def persist_graphs( graphs: dict[str, list[tuple[LibraryGraph, Optional[str]]]], s3_client: S3Client, bucket: str, full_repo_object_key: str, timeout: int, absolute_root_folder: str = '' ) -> None: def _upload_graph(check_type: str, graph: LibraryGraph, _absolute_root_folder: str = '', subgraph_path: Optional[str] = None) -> None: if isinstance(graph, DiGraph): json_obj = node_link_data(graph) graph_file_name = FILE_NAME_NETWORKX elif isinstance(graph, PyDiGraph): json_obj = digraph_node_link_json(graph) graph_file_name = FILE_NAME_RUSTWORKX else: logging.error(f"unsupported graph type '{graph.__class__.__name__}'") return multi_graph_addition = (f"multi-graph/{subgraph_path}" if subgraph_path is not None else '').rstrip("/") s3_key = os.path.join(graphs_repo_object_key, check_type, multi_graph_addition, graph_file_name) try: _put_json_object(s3_client, json_obj, bucket, s3_key) except Exception: logging.error(f'failed to upload graph from framework {check_type} to platform', exc_info=True) graphs_repo_object_key = full_repo_object_key.replace('checkov', 'graphs')[:-4] with futures.ThreadPoolExecutor() as executor: futures.wait( [executor.submit(_upload_graph, check_type, graph, absolute_root_folder, subgraph_path) for check_type, graphs in graphs.items() for graph, subgraph_path in graphs], return_when=futures.FIRST_EXCEPTION, timeout=timeout ) logging.info(f"Done persisting {len(list(itertools.chain(*graphs.values())))} graphs")
null
2,340
from __future__ import annotations import logging import os import json import itertools from concurrent import futures from io import StringIO from typing import Any, TYPE_CHECKING, Optional, Dict from collections import defaultdict import dpath from rustworkx import PyDiGraph, digraph_node_link_json from checkov.common.sast.consts import CDK_FRAMEWORK_PREFIX, SAST_FRAMEWORK_PREFIX from checkov.common.bridgecrew.check_type import CheckType from checkov.common.models.consts import SUPPORTED_FILE_EXTENSIONS from checkov.common.typing import _ReducedScanReport, LibraryGraph from checkov.common.util.file_utils import compress_multiple_strings_ios_tar from checkov.common.util.json_utils import CustomJSONEncoder def _put_json_object(s3_client: S3Client, json_obj: Any, bucket: str, object_path: str, log_stack_trace_on_error: bool = True) -> None: try: s3_client.put_object(Bucket=bucket, Key=object_path, Body=json.dumps(json_obj, cls=CustomJSONEncoder)) except Exception: logging.error(f"failed to persist object into S3 bucket {bucket} - {object_path}", exc_info=log_stack_trace_on_error) raise def persist_resource_subgraph_maps( resource_subgraph_maps: dict[str, dict[str, str]], s3_client: S3Client, bucket: str, full_repo_object_key: str, timeout: int ) -> None: def _upload_resource_subgraph_map(check_type: str, resource_subgraph_map: dict[str, str]) -> None: s3_key = os.path.join(graphs_repo_object_key, check_type, "multi-graph/resource_subgraph_maps/resource_subgraph_map.json") try: _put_json_object(s3_client, resource_subgraph_map, bucket, s3_key) except Exception: logging.error(f'failed to upload resource_subgraph_map from framework {check_type} to platform', exc_info=True) # removing '/src' with [:-4] graphs_repo_object_key = full_repo_object_key.replace('checkov', 'graphs')[:-4] with futures.ThreadPoolExecutor() as executor: futures.wait( [executor.submit(_upload_resource_subgraph_map, check_type, resource_subgraph_map) for check_type, resource_subgraph_map in resource_subgraph_maps.items()], return_when=futures.FIRST_EXCEPTION, timeout=timeout ) if resource_subgraph_maps: logging.info(f"Done persisting resource_subgraph_maps for frameworks - {', '.join(resource_subgraph_maps.keys())}")
null
2,341
from __future__ import annotations import asyncio import logging from abc import abstractmethod from collections.abc import Iterable from pathlib import Path from typing import Any, TYPE_CHECKING, Generic, TypeVar import aiohttp import docker from checkov.common.bridgecrew.vulnerability_scanning.image_scanner import image_scanner from checkov.common.bridgecrew.vulnerability_scanning.integrations.docker_image_scanning import \ docker_image_scanning_integration from checkov.common.output.common import ImageDetails from checkov.common.output.report import Report, CheckType from checkov.common.sca.commons import should_run_scan from checkov.common.sca.output import add_to_report_sca_data, get_license_statuses_async from checkov.common.typing import _LicenseStatus class Report: def __init__(self, check_type: str): self.check_type = check_type self.passed_checks: list[Record] = [] self.failed_checks: list[Record] = [] self.skipped_checks: list[Record] = [] self.parsing_errors: list[str] = [] self.resources: set[str] = set() self.extra_resources: set[ExtraResource] = set() self.image_cached_results: List[dict[str, Any]] = [] self.error_status: ErrorStatus = ErrorStatus.SUCCESS def errors(self) -> Dict[str, List[str]]: return dict() def set_error_status(self, error_status: ErrorStatus) -> None: self.error_status = error_status def add_parsing_errors(self, errors: "Iterable[str]") -> None: for file in errors: self.add_parsing_error(file) def add_parsing_error(self, file: str) -> None: if file: self.parsing_errors.append(file) def add_resource(self, resource: str) -> None: self.resources.add(resource) def add_record(self, record: Record) -> None: if record.check_result["result"] == CheckResult.PASSED: self.passed_checks.append(record) if record.check_result["result"] == CheckResult.FAILED: self.failed_checks.append(record) if record.check_result["result"] == CheckResult.SKIPPED: self.skipped_checks.append(record) def get_summary(self) -> Dict[str, Union[int, str]]: return { "passed": len(self.passed_checks), "failed": len(self.failed_checks), "skipped": len(self.skipped_checks), "parsing_errors": len(self.parsing_errors), "resource_count": len(self.resources), "checkov_version": version, } def get_json(self) -> str: return json.dumps(self.get_dict(), indent=4, cls=CustomJSONEncoder) def get_all_records(self) -> List[Record]: return self.failed_checks + self.passed_checks + self.skipped_checks def get_dict(self, is_quiet: bool = False, url: str | None = None, full_report: bool = False, s3_setup_failed: bool = False, support_path: str | None = None) -> dict[str, Any]: if not url and not s3_setup_failed: url = "Add an api key '--bc-api-key <api-key>' to see more detailed insights via https://bridgecrew.cloud" elif s3_setup_failed: url = S3_UPLOAD_DETAILS_MESSAGE if is_quiet: return { "check_type": self.check_type, "results": { "failed_checks": [check.__dict__ for check in self.failed_checks] }, "summary": self.get_summary(), } if full_report: return { "check_type": self.check_type, "checks": { "passed_checks": [check.__dict__ for check in self.passed_checks], "failed_checks": [check.__dict__ for check in self.failed_checks], "skipped_checks": [check.__dict__ for check in self.skipped_checks] }, "image_cached_results": [res.__dict__ for res in self.image_cached_results] } else: result = { "check_type": self.check_type, "results": { "passed_checks": [check.__dict__ for check in self.passed_checks], "failed_checks": [check.__dict__ for check in self.failed_checks], "skipped_checks": [check.__dict__ for check in self.skipped_checks], "parsing_errors": list(self.parsing_errors), }, "summary": self.get_summary(), "url": url, } if support_path: result["support_path"] = support_path return result def get_exit_code(self, exit_code_thresholds: Union[_ExitCodeThresholds, _ScaExitCodeThresholds]) -> int: """ Returns the appropriate exit code depending on the flags that are passed in. :return: Exit code 0 or 1. """ hard_fail_on_parsing_errors = os.getenv(PARSE_ERROR_FAIL_FLAG, "false").lower() == 'true' logging.debug(f'In get_exit_code; exit code thresholds: {exit_code_thresholds}, hard_fail_on_parsing_errors: {hard_fail_on_parsing_errors}') if self.parsing_errors and hard_fail_on_parsing_errors: logging.debug('hard_fail_on_parsing_errors is True and there were parsing errors - returning 1') return 1 if not self.failed_checks: logging.debug('No failed checks in this report - returning 0') return 0 # we will have two different sets of logic in this method, determined by this variable. # if we are using enforcement rules, then there are two different sets of thresholds that apply for licenses and vulnerabilities # and we have to handle that throughout while processing the report # if we are not using enforcement rules, then we can combine licenses and vulnerabilities like normal and same as all other report types # this determination is made in runner_registry.get_fail_thresholds has_split_enforcement = CodeCategoryType.LICENSES in exit_code_thresholds hard_fail_threshold: Optional[Severity | Dict[str, Severity]] soft_fail: Optional[bool | Dict[str, bool]] if has_split_enforcement: sca_thresholds = cast(_ScaExitCodeThresholds, exit_code_thresholds) # these three are the same even in split enforcement rules generic_thresholds = cast(_ExitCodeThresholds, next(iter(sca_thresholds.values()))) soft_fail_on_checks = generic_thresholds['soft_fail_checks'] soft_fail_threshold = generic_thresholds['soft_fail_threshold'] hard_fail_on_checks = generic_thresholds['hard_fail_checks'] # these two can be different for licenses / vulnerabilities hard_fail_threshold = {category: thresholds['hard_fail_threshold'] for category, thresholds in sca_thresholds.items()} # type:ignore[index] # thinks it's an object, can't possibly be more clear soft_fail = {category: thresholds['soft_fail'] for category, thresholds in sca_thresholds.items()} # type:ignore[index] # thinks it's an object failed_checks_by_category = { CodeCategoryType.LICENSES: [fc for fc in self.failed_checks if '_LIC_' in fc.check_id], CodeCategoryType.VULNERABILITIES: [fc for fc in self.failed_checks if '_VUL_' in fc.check_id] } has_soft_fail_values = soft_fail_on_checks or soft_fail_threshold if all( not failed_checks_by_category[cast(CodeCategoryType, c)] or ( not has_soft_fail_values and not (hard_fail_threshold[c] or hard_fail_on_checks) and soft_fail[c] ) for c in sca_thresholds.keys() ): logging.debug( 'No failed checks, or soft_fail is True and soft_fail_on and hard_fail_on are empty for all SCA types - returning 0') return 0 if any( not has_soft_fail_values and not (hard_fail_threshold[c] or hard_fail_on_checks) and failed_checks_by_category[cast(CodeCategoryType, c)] for c in sca_thresholds.keys() ): logging.debug('There are failed checks and all soft/hard fail args are empty for one or more SCA reports - returning 1') return 1 else: non_sca_thresholds = cast(_ExitCodeThresholds, exit_code_thresholds) soft_fail_on_checks = non_sca_thresholds['soft_fail_checks'] soft_fail_threshold = non_sca_thresholds['soft_fail_threshold'] hard_fail_on_checks = non_sca_thresholds['hard_fail_checks'] hard_fail_threshold = non_sca_thresholds['hard_fail_threshold'] soft_fail = non_sca_thresholds['soft_fail'] has_soft_fail_values = soft_fail_on_checks or soft_fail_threshold has_hard_fail_values = hard_fail_threshold or hard_fail_on_checks if not has_soft_fail_values and not has_hard_fail_values and soft_fail: logging.debug('Soft_fail is True and soft_fail_on and hard_fail_on are empty - returning 0') return 0 elif not has_soft_fail_values and not has_hard_fail_values: logging.debug('There are failed checks and all soft/hard fail args are empty - returning 1') return 1 for failed_check in self.failed_checks: check_id = failed_check.check_id bc_check_id = failed_check.bc_check_id severity = failed_check.severity secret_validation_status = failed_check.validation_status if hasattr(failed_check, 'validation_status') else '' hf_threshold: Severity sf: bool if has_split_enforcement: category = CodeCategoryType.LICENSES if '_LIC_' in check_id else CodeCategoryType.VULNERABILITIES hard_fail_threshold = cast(Dict[str, Severity], hard_fail_threshold) hf_threshold = hard_fail_threshold[category] soft_fail = cast(Dict[str, bool], soft_fail) sf = soft_fail[category] else: hard_fail_threshold = cast(Severity, hard_fail_threshold) hf_threshold = hard_fail_threshold soft_fail = cast(bool, soft_fail) sf = soft_fail soft_fail_severity = severity and soft_fail_threshold and severity.level <= soft_fail_threshold.level hard_fail_severity = severity and hf_threshold and severity.level >= hf_threshold.level explicit_soft_fail = RunnerFilter.check_matches(check_id, bc_check_id, soft_fail_on_checks) explicit_hard_fail = RunnerFilter.check_matches(check_id, bc_check_id, hard_fail_on_checks) explicit_secrets_soft_fail = RunnerFilter.secret_validation_status_matches(secret_validation_status, soft_fail_on_checks) explicit_secrets_hard_fail = RunnerFilter.secret_validation_status_matches(secret_validation_status, hard_fail_on_checks) implicit_soft_fail = not explicit_hard_fail and not explicit_secrets_hard_fail and not soft_fail_on_checks and not soft_fail_threshold implicit_hard_fail = not explicit_soft_fail and not soft_fail_severity and not explicit_secrets_soft_fail if explicit_hard_fail or \ (hard_fail_severity and not explicit_soft_fail) or \ (implicit_hard_fail and not implicit_soft_fail and not sf): logging.debug(f'Check {check_id} (BC ID: {bc_check_id}, severity: {severity.level if severity else None} triggered hard fail - returning 1') return 1 logging.debug('No failed check triggered hard fail - returning 0') return 0 def is_empty(self, full: bool = False) -> bool: checks_count = ( len(self.passed_checks) + len(self.failed_checks) + len(self.skipped_checks) + len(self.parsing_errors) ) if full: checks_count += len(self.resources) + len(self.extra_resources) + len(self.image_cached_results) return checks_count == 0 def add_errors_to_output(self) -> str: ret_value = '' for error_title, errors_messages in self.errors.items(): ret_value += colored(f"Encountered {error_title} error - {len(errors_messages)} times\n\n", "red") return ret_value def print_console( self, is_quiet: bool = False, is_compact: bool = False, created_baseline_path: str | None = None, baseline: Baseline | None = None, use_bc_ids: bool = False, summary_position: str = 'top', openai_api_key: str | None = None, ) -> str: summary = self.get_summary() output_data = colored(f"{self.check_type} scan results:\n", "blue") if self.parsing_errors: message = "\nPassed checks: {}, Failed checks: {}, Skipped checks: {}, Parsing errors: {}\n\n".format( summary["passed"], summary["failed"], summary["skipped"], summary["parsing_errors"], ) else: if self.check_type == CheckType.SCA_PACKAGE or self.check_type.lower().startswith(CheckType.SAST): message = f"\nFailed checks: {summary['failed']}, Skipped checks: {summary['skipped']}\n\n" else: message = f"\nPassed checks: {summary['passed']}, Failed checks: {summary['failed']}, Skipped checks: {summary['skipped']}\n\n" if summary_position == 'top': output_data += colored(message, "cyan") # output for vulnerabilities is different if self.check_type in (CheckType.SCA_PACKAGE, CheckType.SCA_IMAGE): if self.failed_checks or self.skipped_checks: create_cli_output = create_sca_package_cli_output_v2 output_data += create_cli_output(self.check_type == CheckType.SCA_PACKAGE, self.failed_checks, self.skipped_checks) elif self.check_type == CheckType.POLICY_3D: if self.failed_checks or self.skipped_checks: output_data += create_3d_policy_cli_output(self.failed_checks, self.skipped_checks) # type:ignore[arg-type] else: if self.check_type.lower().startswith(CheckType.SAST): output_data += colored(f"Source code files scanned: {summary.get(SOURCE_FILES_COUNT, -1)}, " f"Policies found: {summary.get(POLICY_COUNT, -1)}\n\n", "cyan") policies_errors: str = str(summary.get(POLICIES_ERRORS, "")) if policies_errors: output_data += colored(f"Policy parsing failures ({summary.get(POLICIES_ERRORS_COUNT)}):\n{policies_errors}\n\n", "red") if not is_quiet: for record in self.passed_checks: output_data += record.to_string(compact=is_compact, use_bc_ids=use_bc_ids) if self.failed_checks: OpenAi(api_key=openai_api_key).enhance_records(runner_type=self.check_type, records=self.failed_checks) for record in self.failed_checks: output_data += record.to_string(compact=is_compact, use_bc_ids=use_bc_ids) if not is_quiet: for record in self.skipped_checks: output_data += record.to_string(compact=is_compact, use_bc_ids=use_bc_ids) if not is_quiet: for file in self.parsing_errors: output_data += colored(f"Error parsing file {file}ֿ\n", "red") if created_baseline_path: output_data += colored( f"Created a checkov baseline file at {created_baseline_path}", "blue", ) if baseline: output_data += colored( f"Baseline analysis report using {baseline.path} - only new failed checks with respect to the baseline are reported", "blue", ) if summary_position == 'bottom': output_data += colored(message, "cyan") return output_data def _print_parsing_error_console(file: str) -> None: print(colored(f"Error parsing file {file}", "red")) def get_junit_xml_string(ts: list[TestSuite]) -> str: return to_xml_report_string(ts) def print_failed_github_md(self, use_bc_ids: bool = False) -> str: result = [] for record in self.failed_checks: result.append( [ record.get_output_id(use_bc_ids), record.file_path, record.resource, record.check_name, record.guideline, ] ) if result: table = tabulate( result, headers=["check_id", "file", "resource", "check_name", "guideline"], tablefmt="github", showindex=True, ) output_data = f"### {self.check_type} scan results:\n\n{table}\n\n---\n" return output_data else: return "\n\n---\n\n" def get_test_suite(self, properties: Optional[Dict[str, Any]] = None, use_bc_ids: bool = False) -> TestSuite: """Creates a test suite for the JUnit XML report""" test_cases = [] records = self.passed_checks + self.failed_checks + self.skipped_checks for record in records: severity = BcSeverities.NONE if record.severity: severity = record.severity.name if self.check_type == CheckType.SCA_PACKAGE: if record.check_name != SCA_PACKAGE_SCAN_CHECK_NAME: continue if not record.vulnerability_details: # this shouldn't normally happen logging.warning(f"Vulnerability check without details {record.file_path}") continue check_id = record.vulnerability_details["id"] test_name_detail = f"{record.vulnerability_details['package_name']}: {record.vulnerability_details['package_version']}" class_name = f"{record.file_path}.{record.vulnerability_details['package_name']}" else: check_id = record.bc_check_id if use_bc_ids else record.check_id test_name_detail = record.check_name class_name = f"{record.file_path}.{record.resource}" test_name = f"[{severity}][{check_id}] {test_name_detail}" test_case = TestCase(name=test_name, file=record.file_path, classname=class_name) if record.check_result["result"] == CheckResult.FAILED: test_case.add_failure_info( message=record.check_name, output=self._create_test_case_failure_output(record) ) if record.check_result["result"] == CheckResult.SKIPPED: if self.check_type == CheckType.SCA_PACKAGE: test_case.add_skipped_info(f"{check_id} skipped for {test_name_detail}") else: test_case.add_skipped_info(record.check_result.get("suppress_comment", "")) test_cases.append(test_case) test_suite = TestSuite(name=f"{self.check_type} scan", test_cases=test_cases, properties=properties) return test_suite def create_test_suite_properties_block(config: argparse.Namespace) -> Dict[str, Any]: """Creates a dictionary without 'None' values for the JUnit XML properties block""" properties = {k: v for k, v in config.__dict__.items() if v is not None} return properties def _create_test_case_failure_output(self, record: Record) -> str: """Creates the failure output for a JUnit XML test case IaC example: Resource: azurerm_network_security_rule.fail_rdp File: /main.tf: 71-83 Guideline: https://docs.bridgecrew.io/docs/bc_azr_networking_2 71 | resource "azurerm_network_security_rule" "fail_rdp" { 72 | resource_group_name = azurerm_resource_group.example.name 73 | network_security_group_name=azurerm_network_security_group.example_rdp.name 74 | name = "fail_security_rule" 75 | direction = "Inbound" 76 | access = "Allow" 77 | protocol = "TCP" 78 | source_port_range = "*" 79 | destination_port_range = "3389" 80 | source_address_prefix = "*" 81 | destination_address_prefix = "*" 82 | priority = 120 83 | } SCA example: Description: Django before 1.11.27, 2.x before 2.2.9, and 3.x before 3.0.1 allows account takeover. Link: https://nvd.nist.gov/vuln/detail/CVE-2019-19844 Published Date: 2019-12-18T20:15:00+01:00 Base Score: 9.8 Vector: CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H Risk Factors: ['Attack complexity: low', 'Attack vector: network', 'Critical severity', 'Has fix'] Resource: requirements.txt.django File: /requirements.txt: 0-0 0 | django: 1.2 """ failure_output = [] if self.check_type == CheckType.SCA_PACKAGE: if record.vulnerability_details: lowest_fixed_version = record.vulnerability_details.get('lowest_fixed_version') if lowest_fixed_version is not None: fix = lowest_fixed_version else: fixlist = record.vulnerability_details.get('fixed_versions') if fixlist is not None: fix = fixlist failure_output.extend( [ "", f"Description: {record.description}", f"Link: {record.vulnerability_details.get('link')}", f"Published Date: {record.vulnerability_details.get('published_date')}", f"Base Score: {record.vulnerability_details.get('cvss')}", f"Vector: {record.vulnerability_details.get('vector')}", f"Risk Factors: {record.vulnerability_details.get('risk_factors')}", "Fix Details:", f" Status: {record.vulnerability_details.get('status')}", f" Fixed Version: {fix}", ] ) else: # this shouldn't normally happen logging.warning(f"Vulnerability check without details {record.file_path}") failure_output.extend( [ "", f"Resource: {record.resource}", ] ) if record.file_path: file_line = f"File: {record.file_path}" if record.file_line_range: file_line += f": {record.file_line_range[0]}-{record.file_line_range[1]}" failure_output.append(file_line) if self.check_type != CheckType.SCA_PACKAGE: failure_output.append(f"Guideline: {record.guideline}") if record.code_block: failure_output.append("") failure_output.append(record._code_line_string(code_block=record.code_block, colorized=False)) return "\n".join(failure_output) def print_json(self) -> None: print(self.get_json()) def enrich_plan_report( report: "Report", enriched_resources: Dict[str, Dict[str, Any]] ) -> "Report": # This enriches reports with the appropriate filepath, line numbers, and codeblock for record in report.failed_checks: resource_raw_id = Report.get_plan_resource_raw_id(record.resource) enriched_resource = enriched_resources.get(resource_raw_id) if enriched_resource: record.file_path = enriched_resource["scanned_file"] record.file_line_range = enriched_resource["entity_lines_range"] record.code_block = enriched_resource["entity_code_lines"] return report def handle_skipped_checks( report: "Report", enriched_resources: Dict[str, Dict[str, Any]] ) -> "Report": module_address_len = len("module.") skip_records = [] for record in report.failed_checks: resource_raw_id = Report.get_plan_resource_raw_id(record.resource) resource_skips = enriched_resources.get(resource_raw_id, {}).get( "skipped_checks", [] ) for skip in resource_skips: if record.check_id in skip["id"]: # Mark for removal and add it as a skipped record. It is not safe to remove # the record from failed_checks immediately because we're iterating over it skip_records.append(record) record.check_result["result"] = CheckResult.SKIPPED record.check_result["suppress_comment"] = skip["suppress_comment"] report.add_record(record) if record.resource_address and record.resource_address.startswith("module."): module_path = record.resource_address[module_address_len:record.resource_address.index('.', module_address_len + 1)] module_enrichments = enriched_resources.get(module_path, {}) for module_skip in module_enrichments.get("skipped_checks", []): if record.check_id in module_skip["id"]: skip_records.append(record) record.check_result["result"] = CheckResult.SKIPPED record.check_result["suppress_comment"] = module_skip["suppress_comment"] report.add_record(record) for record in skip_records: if record in report.failed_checks: report.failed_checks.remove(record) return report def get_plan_resource_raw_id(resource_id: str) -> str: """ return the resource raw id without the modules and the indexes example: from resource_id='module.module_name.type.name[1]' return 'type.name' """ resource_raw_id = ".".join(resource_id.split(".")[-2:]) if '[' in resource_raw_id: resource_raw_id = resource_raw_id[:resource_raw_id.index('[')] return resource_raw_id def from_reduced_json(cls, json_report: dict[str, Any], check_type: str) -> Report: report = Report(check_type) report.image_cached_results = json_report['image_cached_results'] all_json_records = json_report["checks"]["passed_checks"] + \ json_report["checks"]["failed_checks"] + \ json_report["checks"]["skipped_checks"] for json_record in all_json_records: report.add_record( Record.from_reduced_json(json_record) ) return report The provided code snippet includes necessary dependencies for implementing the `fix_related_resource_ids` function. Write a Python function `def fix_related_resource_ids(report: Report | None, tmp_dir: str) -> None` to solve the following problem: Remove tmp dir prefix from 'relatedResourceId Here is the function: def fix_related_resource_ids(report: Report | None, tmp_dir: str) -> None: """Remove tmp dir prefix from 'relatedResourceId'""" if report and report.image_cached_results: for cached_result in report.image_cached_results: related_resource_id = cached_result.get("relatedResourceId") if related_resource_id and isinstance(related_resource_id, str): cached_result["relatedResourceId"] = related_resource_id.replace(tmp_dir, "", 1)
Remove tmp dir prefix from 'relatedResourceId
2,342
from __future__ import annotations import asyncio import logging from abc import abstractmethod from collections.abc import Iterable from pathlib import Path from typing import Any, TYPE_CHECKING, Generic, TypeVar import aiohttp import docker from checkov.common.bridgecrew.vulnerability_scanning.image_scanner import image_scanner from checkov.common.bridgecrew.vulnerability_scanning.integrations.docker_image_scanning import \ docker_image_scanning_integration from checkov.common.output.common import ImageDetails from checkov.common.output.report import Report, CheckType from checkov.common.sca.commons import should_run_scan from checkov.common.sca.output import add_to_report_sca_data, get_license_statuses_async from checkov.common.typing import _LicenseStatus INVALID_IMAGE_NAME_CHARS = ("[", "{", "(", "<", "$") def is_valid_public_image_name(image_name: str) -> bool: if image_name.startswith('localhost'): return False if any(char in image_name for char in INVALID_IMAGE_NAME_CHARS): return False if image_name.count(":") > 1: # if there is more than one colon, then it is typically a private registry with port reference return False return True
null
2,343
from __future__ import annotations from io import StringIO from typing import Any, TYPE_CHECKING, cast, List import configargparse from checkov.common.bridgecrew.check_type import checkov_runners from checkov.common.runners.runner_registry import OUTPUT_CHOICES, SUMMARY_POSITIONS from checkov.common.util.consts import DEFAULT_EXTERNAL_MODULES_DIR from checkov.common.util.type_forcers import convert_str_to_bool from checkov.version import version The provided code snippet includes necessary dependencies for implementing the `flatten_csv` function. Write a Python function `def flatten_csv(list_to_flatten: List[List[str]]) -> List[str]` to solve the following problem: Flattens a list of list of strings into a list of strings, while also splitting out comma-separated values Duplicates will be removed. [['terraform', 'arm'], ['bicep,cloudformation,arm']] -> ['terraform', 'arm', 'bicep', 'cloudformation'] (Order is not guaranteed) Here is the function: def flatten_csv(list_to_flatten: List[List[str]]) -> List[str]: """ Flattens a list of list of strings into a list of strings, while also splitting out comma-separated values Duplicates will be removed. [['terraform', 'arm'], ['bicep,cloudformation,arm']] -> ['terraform', 'arm', 'bicep', 'cloudformation'] (Order is not guaranteed) """ if not list_to_flatten: return [] return list({s for sublist in list_to_flatten for val in sublist for s in val.split(',')})
Flattens a list of list of strings into a list of strings, while also splitting out comma-separated values Duplicates will be removed. [['terraform', 'arm'], ['bicep,cloudformation,arm']] -> ['terraform', 'arm', 'bicep', 'cloudformation'] (Order is not guaranteed)
2,344
from __future__ import annotations import os.path import tarfile import base64 import gzip import io import logging from pathlib import Path from typing import Dict from zipfile import ZipFile from charset_normalizer import from_path from checkov.common.resource_code_logger_filter import add_resource_code_filter_to_logger def convert_to_unix_path(path: str) -> str: return path.replace('\\', '/')
null
2,345
from __future__ import annotations import os.path import tarfile import base64 import gzip import io import logging from pathlib import Path from typing import Dict from zipfile import ZipFile from charset_normalizer import from_path from checkov.common.resource_code_logger_filter import add_resource_code_filter_to_logger def extract_tar_archive(source_path: str, dest_path: str) -> None: with tarfile.open(source_path) as tar: tar.extractall(path=dest_path) # nosec # only trusted source
null
2,346
from __future__ import annotations import os.path import tarfile import base64 import gzip import io import logging from pathlib import Path from typing import Dict from zipfile import ZipFile from charset_normalizer import from_path from checkov.common.resource_code_logger_filter import add_resource_code_filter_to_logger def extract_zip_archive(source_path: str, dest_path: str) -> None: with ZipFile(source_path) as zip: zip.extractall(path=dest_path) # nosec # only trusted source
null
2,347
from __future__ import annotations import os.path import tarfile import base64 import gzip import io import logging from pathlib import Path from typing import Dict from zipfile import ZipFile from charset_normalizer import from_path from checkov.common.resource_code_logger_filter import add_resource_code_filter_to_logger def compress_file_gzip_base64(input_path: str) -> str: try: with open(input_path, 'rb') as json_results_file: data = json_results_file.read() zip_file = gzip.compress(data) # to gzip - return in bytes base64_bytes = base64.b64encode(zip_file) # to base64 base64_string = base64_bytes.decode("utf-8") return base64_string except Exception: logging.exception("failed to open and load results file") raise
null
2,348
from __future__ import annotations import os.path import tarfile import base64 import gzip import io import logging from pathlib import Path from typing import Dict from zipfile import ZipFile from charset_normalizer import from_path from checkov.common.resource_code_logger_filter import add_resource_code_filter_to_logger def compress_string_io_tar(string_io: io.StringIO) -> io.BytesIO: file_io = io.BytesIO() str_data = string_io.getvalue().encode('utf8') bio = io.BytesIO(str_data) try: with tarfile.open(fileobj=file_io, mode='w:gz') as tar: info = tar.tarinfo(name='logs_file.txt') bio.seek(0) info.size = string_io.tell() tar.addfile(info, bio) file_io.seek(0) return file_io except Exception: logging.exception("failed to compress logging file") raise
null
2,349
from __future__ import annotations import os.path import tarfile import base64 import gzip import io import logging from pathlib import Path from typing import Dict from zipfile import ZipFile from charset_normalizer import from_path from checkov.common.resource_code_logger_filter import add_resource_code_filter_to_logger def read_file_safe(file_path: str) -> str: try: with open(file_path, 'r') as f: file_content = f.read() return file_content except Exception: logging.warning( "Could not open file", extra={"file_path": file_path} ) return ""
null
2,350
from __future__ import annotations import os.path import tarfile import base64 import gzip import io import logging from pathlib import Path from typing import Dict from zipfile import ZipFile from charset_normalizer import from_path from checkov.common.resource_code_logger_filter import add_resource_code_filter_to_logger def get_file_size_safe(file_path: str) -> int: try: return os.path.getsize(file_path) except Exception as e: logging.warning( f"Could not obtain file size, {str(e)}", extra={"file_path": file_path} ) return -1
null
2,351
import re def removeprefix(input_str: str, prefix: str) -> str: if input_str.startswith(prefix): return input_str[len(prefix):] return input_str
null
2,352
import re seconds_per_unit = {"s": 1, "m": 60, "h": 3600, "d": 86400, "w": 604800} seconds_per_unit_regex = r"^\d+[s|m|h|d|w]" def convert_to_seconds(input_str: str) -> int: if re.search(seconds_per_unit_regex, input_str) is None: raise Exception(f"format error for input str, usage: {seconds_per_unit_regex}") return int(input_str[:-1]) * seconds_per_unit[input_str[-1]]
null
2,353
import datetime import json from json import JSONDecodeError from typing import Any, Dict from lark import Tree from bc_jsonpath_ng import parse, JSONPath from checkov.common.bridgecrew.severities import Severity from checkov.common.output.common import ImageDetails from checkov.common.packaging.version import LegacyVersion, Version from checkov.common.sast.report_types import MatchMetadata, DataFlow, MatchLocation, Point from detect_secrets.core.potential_secret import PotentialSecret from checkov.common.util.data_structures_utils import pickle_deepcopy def get_jsonpath_from_evaluated_key(evaluated_key: str) -> JSONPath: evaluated_key = evaluated_key.replace("/", ".") return parse(f"$..{evaluated_key}") # type:ignore[no-any-return]
null
2,354
from __future__ import annotations import json import re from dataclasses import dataclass from enum import Enum from typing import Any, List import hcl2 def find_var_blocks(value: str) -> List[VarBlockMatch]: """ Find and return all the var blocks within a given string. Order is important and may contain portions of one another. """ if "$" not in value: # not relevant, typically just a normal string value return [] to_return: List[VarBlockMatch] = [] mode_stack: List[ParserMode] = [] eval_start_pos_stack: List[int] = [] # location of first char inside brackets param_start_pos_stack: List[int] = [] # location of open parens preceding_dollar = False preceding_string_escape = False # NOTE: function calls can be nested, but since param args are only being inspected for variables, # it's alright to ignore outer calls. param_arg_start = -1 for index, c in enumerate(value): current_mode = ParserMode.BLANK if not mode_stack else mode_stack[-1] # Print statement of power... # print(f"{str(index).ljust(3, ' ')} {c} {'$' if preceding_dollar else ' '} " # f"{'`' if preceding_string_escape else ' '} " # f"{current_mode.ljust(2)} - {mode_stack}") if c == "$": if preceding_dollar: # ignore double $ preceding_dollar = False continue preceding_dollar = True continue if c == "{" and preceding_dollar: mode_stack.append(ParserMode.EVAL) eval_start_pos_stack.append(index + 1) # next char preceding_dollar = False continue elif c == "\\" and ParserMode.is_string(current_mode): preceding_string_escape = True continue preceding_dollar = False if c == "}": if current_mode == ParserMode.EVAL: mode_stack.pop() start_pos = eval_start_pos_stack.pop() eval_string = value[start_pos:index] to_return.append(VarBlockMatch("${" + eval_string + "}", eval_string)) elif current_mode == ParserMode.MAP: mode_stack.pop() elif c == "]" and current_mode == ParserMode.ARRAY: mode_stack.pop() elif c == ")" and current_mode == ParserMode.PARAMS: if param_arg_start > 0: param_arg = value[param_arg_start:index].strip() if _ARG_VAR_PATTERN.match(param_arg): to_return.append(VarBlockMatch(param_arg, param_arg)) param_arg_start = -1 mode_stack.pop() start_pos = param_start_pos_stack.pop() # See if these params are for a function call. Back up from the index to determine if there's # a function preceding. function_name_start_index = start_pos for function_index in range(start_pos - 1, 0, -1): if value[function_index] in _FUNCTION_NAME_CHARS: function_name_start_index = function_index else: break # We know now there's a function call here. But, don't call it out if it's directly wrapped # in eval markers. in_eval_markers = False if function_name_start_index >= 2: in_eval_markers = ( value[function_name_start_index - 2] == "$" and value[function_name_start_index - 1] == "{" ) if function_name_start_index < start_pos and not in_eval_markers: to_return.append( VarBlockMatch( value[function_name_start_index : index + 1], value[function_name_start_index : index + 1] ) ) elif c == '"': if preceding_string_escape: preceding_string_escape = False continue elif current_mode == ParserMode.STRING_DOUBLE_QUOTE: mode_stack.pop() else: mode_stack.append(ParserMode.STRING_DOUBLE_QUOTE) elif c == "'": if preceding_string_escape: preceding_string_escape = False continue elif current_mode == ParserMode.STRING_SINGLE_QUOTE: mode_stack.pop() else: mode_stack.append(ParserMode.STRING_SINGLE_QUOTE) elif c == "{": # NOTE: Can't be preceded by a dollar sign (that was checked earlier) if not ParserMode.is_string(current_mode): mode_stack.append(ParserMode.MAP) elif c == "[": # do we care? if not ParserMode.is_string(current_mode): mode_stack.append(ParserMode.ARRAY) elif c == "(": # do we care? if not ParserMode.is_string(current_mode): mode_stack.append(ParserMode.PARAMS) param_start_pos_stack.append(index) param_arg_start = index + 1 elif c == ",": if current_mode == ParserMode.PARAMS and param_arg_start > 0: param_arg = value[param_arg_start:index].strip() if _ARG_VAR_PATTERN.match(param_arg): to_return.append(VarBlockMatch(param_arg, param_arg)) param_arg_start = index + 1 elif c == "?" and current_mode == ParserMode.EVAL: # ternary # If what's been processed in the ternary so far is "true" or "false" (boolean or string type) # then nothing special will happen here and only the full expression will be returned. # Anything else will be treated as an unresolved variable block. start_pos = eval_start_pos_stack[-1] # DO NOT pop: there's no separate eval start indicator eval_string = value[start_pos:index].strip() # HACK ALERT: For the cases with the trailing quotes, see: # test_hcl2_load_assumptions.py -> test_weird_ternary_string_clipping if eval_string not in {"true", "false", '"true"', '"false"', 'true"', 'false"'}: # REMINDER: The eval string is not wrapped in a eval markers since they didn't really # appear in the original value. If they're put in, substitution doesn't # work properly. to_return.append(VarBlockMatch(eval_string, eval_string)) preceding_string_escape = False return to_return The provided code snippet includes necessary dependencies for implementing the `is_acceptable_module_param` function. Write a Python function `def is_acceptable_module_param(value: Any) -> bool` to solve the following problem: This function determines if a value should be passed to a module as a parameter. We don't want to pass unresolved var, local or module references because they can't be resolved from the module, so they need to be resolved prior to being passed down. Here is the function: def is_acceptable_module_param(value: Any) -> bool: """ This function determines if a value should be passed to a module as a parameter. We don't want to pass unresolved var, local or module references because they can't be resolved from the module, so they need to be resolved prior to being passed down. """ value_type = type(value) if value_type is dict: for k, v in value.items(): if not is_acceptable_module_param(v) or not is_acceptable_module_param(k): return False return True if value_type is set or value_type is list: for v in value: if not is_acceptable_module_param(v): return False return True if value_type is not str: return True for vbm in find_var_blocks(value): if vbm.is_simple_var(): return False return True
This function determines if a value should be passed to a module as a parameter. We don't want to pass unresolved var, local or module references because they can't be resolved from the module, so they need to be resolved prior to being passed down.
2,355
from __future__ import annotations import ctypes import threading from .utils import TimeoutException, BaseTimeout, base_timeoutable The provided code snippet includes necessary dependencies for implementing the `async_raise` function. Write a Python function `def async_raise(target_tid: int, exception: type[Exception]) -> None` to solve the following problem: Raises an asynchronous exception in another thread. Read http://docs.python.org/c-api/init.html#PyThreadState_SetAsyncExc for further enlightenments. :param target_tid: target thread identifier :param exception: Exception class to be raised in that thread Here is the function: def async_raise(target_tid: int, exception: type[Exception]) -> None: """Raises an asynchronous exception in another thread. Read http://docs.python.org/c-api/init.html#PyThreadState_SetAsyncExc for further enlightenments. :param target_tid: target thread identifier :param exception: Exception class to be raised in that thread """ # Ensuring and releasing GIL are useless since we're not in C # gil_state = ctypes.pythonapi.PyGILState_Ensure() ret = ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(target_tid), ctypes.py_object(exception)) # ctypes.pythonapi.PyGILState_Release(gil_state) if ret == 0: raise ValueError(f"Invalid thread ID {target_tid}") elif ret > 1: ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(target_tid), None) raise SystemError("PyThreadState_SetAsyncExc failed")
Raises an asynchronous exception in another thread. Read http://docs.python.org/c-api/init.html#PyThreadState_SetAsyncExc for further enlightenments. :param target_tid: target thread identifier :param exception: Exception class to be raised in that thread
2,356
from __future__ import annotations import json import uuid import requests import logging import time import os import aiohttp import asyncio from typing import Any, TYPE_CHECKING, cast, Optional, overload from urllib3.response import HTTPResponse from urllib3.util import parse_url from checkov.common.resource_code_logger_filter import add_resource_code_filter_to_logger from checkov.common.util.consts import DEV_API_GET_HEADERS, DEV_API_POST_HEADERS, PRISMA_API_GET_HEADERS, \ PRISMA_PLATFORM, BRIDGECREW_PLATFORM from checkov.common.util.data_structures_utils import merge_dicts from checkov.common.util.type_forcers import force_int, force_float from checkov.version import version as checkov_version def normalize_bc_url(url: None) -> None: ...
null
2,357
from __future__ import annotations import json import uuid import requests import logging import time import os import aiohttp import asyncio from typing import Any, TYPE_CHECKING, cast, Optional, overload from urllib3.response import HTTPResponse from urllib3.util import parse_url from checkov.common.resource_code_logger_filter import add_resource_code_filter_to_logger from checkov.common.util.consts import DEV_API_GET_HEADERS, DEV_API_POST_HEADERS, PRISMA_API_GET_HEADERS, \ PRISMA_PLATFORM, BRIDGECREW_PLATFORM from checkov.common.util.data_structures_utils import merge_dicts from checkov.common.util.type_forcers import force_int, force_float from checkov.version import version as checkov_version def normalize_bc_url(url: str) -> str: ...
null
2,358
from __future__ import annotations import json import uuid import requests import logging import time import os import aiohttp import asyncio from typing import Any, TYPE_CHECKING, cast, Optional, overload from urllib3.response import HTTPResponse from urllib3.util import parse_url from checkov.common.resource_code_logger_filter import add_resource_code_filter_to_logger from checkov.common.util.consts import DEV_API_GET_HEADERS, DEV_API_POST_HEADERS, PRISMA_API_GET_HEADERS, \ PRISMA_PLATFORM, BRIDGECREW_PLATFORM from checkov.common.util.data_structures_utils import merge_dicts from checkov.common.util.type_forcers import force_int, force_float from checkov.version import version as checkov_version def normalize_bc_url(url: str | None) -> str | None: if not url: return None return url.lower().replace('http:', 'https:').strip().rstrip('/')
null