|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import json |
| 4 | +import lzma |
| 5 | +from base64 import b64encode |
| 6 | +from pathlib import Path |
| 7 | +from shlex import split |
| 8 | +from subprocess import CalledProcessError, run |
| 9 | +from tempfile import TemporaryDirectory |
| 10 | +from typing import TYPE_CHECKING, Iterable |
| 11 | + |
| 12 | +from bs4 import BeautifulSoup |
| 13 | +from docker.types import Mount |
| 14 | +from pydantic import BaseModel, Field |
| 15 | +from semver import Version |
| 16 | + |
| 17 | +import config |
| 18 | +from analysis.plugin import AnalysisPluginV0 |
| 19 | +from helperFunctions.docker import run_docker_container |
| 20 | + |
| 21 | +if TYPE_CHECKING: |
| 22 | + from io import FileIO |
| 23 | + |
| 24 | +MIN_SIZE = 2048 |
| 25 | +DOCKER_IMAGE = 'fact/coderec' |
| 26 | + |
| 27 | +try: |
| 28 | + # https://github.com/vobst/coderec |
| 29 | + TOOL = run(split('which coderec'), capture_output=True, text=True, check=True).stdout.strip() |
| 30 | +except CalledProcessError as error: |
| 31 | + raise RuntimeError('coderec not found. Please rerun the installation of the coderec plugin.') from error |
| 32 | + |
| 33 | + |
| 34 | +class AddressRange(BaseModel): |
| 35 | + start: int |
| 36 | + end: int |
| 37 | + size: int |
| 38 | + |
| 39 | + |
| 40 | +class Region(BaseModel): |
| 41 | + type: str |
| 42 | + total_size: int |
| 43 | + address_ranges: list[AddressRange] |
| 44 | + plot_color: str | None = Field(None, description='The color of this region in the plot.') |
| 45 | + |
| 46 | + |
| 47 | +def _find_arch(regions: list[Region], blacklist: Iterable[str]) -> str | None: |
| 48 | + for region in sorted(regions, key=lambda r: r.total_size, reverse=True): |
| 49 | + if region.type.startswith('_') or region.type in blacklist: |
| 50 | + continue |
| 51 | + if region.total_size > MIN_SIZE: # at least 3 blocks must match to avoid false positives |
| 52 | + return region.type |
| 53 | + return None |
| 54 | + |
| 55 | + |
| 56 | +def _find_regions(output: dict[str, tuple[dict[str, int], int, str]]) -> list[Region]: |
| 57 | + regions = [] |
| 58 | + for label, address_ranges in _group_regions_by_type(output).items(): |
| 59 | + regions.append( |
| 60 | + Region( |
| 61 | + type=label, |
| 62 | + total_size=sum(ar.size for ar in address_ranges), |
| 63 | + address_ranges=sorted(address_ranges, key=lambda ar: ar.start), |
| 64 | + ) |
| 65 | + ) |
| 66 | + return regions |
| 67 | + |
| 68 | + |
| 69 | +def _group_regions_by_type(output: dict[str, tuple[dict[str, int], int, str]]) -> dict[str, list[AddressRange]]: |
| 70 | + region_dict = {} |
| 71 | + for address_range, size, label in output: |
| 72 | + region_dict.setdefault(label, []).append( |
| 73 | + AddressRange( |
| 74 | + start=address_range['start'], |
| 75 | + end=address_range['end'], |
| 76 | + size=size, |
| 77 | + ) |
| 78 | + ) |
| 79 | + _merge_overlapping_regions(region_dict) |
| 80 | + return region_dict |
| 81 | + |
| 82 | + |
| 83 | +def _merge_overlapping_regions(region_dict: dict[str, list[AddressRange]]): |
| 84 | + for label, range_list in region_dict.items(): |
| 85 | + range_by_offset = {r.start: r for r in range_list} |
| 86 | + merged = [] |
| 87 | + for start, range_ in sorted(range_by_offset.items()): |
| 88 | + if start not in range_by_offset: |
| 89 | + continue |
| 90 | + while overlap := range_by_offset.get(range_.end): |
| 91 | + range_ = AddressRange( # noqa: PLW2901 |
| 92 | + start=range_.start, |
| 93 | + end=overlap.end, |
| 94 | + size=range_.size + overlap.size, |
| 95 | + ) |
| 96 | + range_by_offset.pop(overlap.start) |
| 97 | + merged.append(range_) |
| 98 | + region_dict[label] = merged |
| 99 | + |
| 100 | + |
| 101 | +def _compress(string: bytes) -> str: |
| 102 | + return b64encode(lzma.compress(string)).decode() |
| 103 | + |
| 104 | + |
| 105 | +class AnalysisPlugin(AnalysisPluginV0): |
| 106 | + class Schema(BaseModel): |
| 107 | + regions: list[Region] |
| 108 | + architecture: str | None |
| 109 | + plot: str = Field(description='Byte plot (base64 encoded and lzma compressed)') |
| 110 | + |
| 111 | + def __init__(self): |
| 112 | + metadata = AnalysisPluginV0.MetaData( |
| 113 | + name='coderec', |
| 114 | + description='Find machine code in binary files or memory dumps.', |
| 115 | + version=Version(0, 1, 0), |
| 116 | + system_version=self._get_system_version(), |
| 117 | + mime_whitelist=['application/octet-stream'], |
| 118 | + Schema=AnalysisPlugin.Schema, |
| 119 | + ) |
| 120 | + super().__init__(metadata=metadata) |
| 121 | + self.blacklist = getattr(config.backend.plugin.get(metadata.name, {}), 'region-blacklist', '').split(',') |
| 122 | + |
| 123 | + @staticmethod |
| 124 | + def _get_system_version() -> str | None: |
| 125 | + try: |
| 126 | + return run(split(f'{TOOL} --version'), capture_output=True, text=True, check=True).stdout.strip().split()[1] |
| 127 | + except IndexError: |
| 128 | + return None |
| 129 | + |
| 130 | + def summarize(self, result: Schema) -> list[str]: |
| 131 | + return [result.architecture] if result.architecture else [] |
| 132 | + |
| 133 | + def analyze(self, file_handle: FileIO, virtual_file_path: str, analyses: dict) -> Schema: |
| 134 | + del virtual_file_path, analyses |
| 135 | + raw_output, output_svg = _run_coderec_in_docker(file_handle) |
| 136 | + output = json.loads(raw_output) |
| 137 | + regions = _find_regions(output['range_results']) |
| 138 | + _add_region_colors(regions, output_svg) |
| 139 | + |
| 140 | + return AnalysisPlugin.Schema( |
| 141 | + regions=sorted(regions, key=lambda r: r.total_size, reverse=True), |
| 142 | + architecture=_find_arch(regions, self.blacklist), |
| 143 | + plot=_compress(output_svg), |
| 144 | + ) |
| 145 | + |
| 146 | + |
| 147 | +def _add_region_colors(regions: list[Region], output_svg: bytes): |
| 148 | + types = {r.type for r in regions}.union({'unknown'}) |
| 149 | + svg = BeautifulSoup(output_svg.decode(), 'html.parser') |
| 150 | + |
| 151 | + # find the start of the legend in the SVG's contents |
| 152 | + for node in svg.find_all('text'): |
| 153 | + if node.text.strip() in types: |
| 154 | + break |
| 155 | + else: |
| 156 | + return |
| 157 | + |
| 158 | + type_list, color_list = [], [] |
| 159 | + while node.name == 'text': |
| 160 | + type_list.append(node.getText().strip()) |
| 161 | + node = node.find_next_sibling() |
| 162 | + while node.name == 'rect': |
| 163 | + color_list.append(node.get('fill')) |
| 164 | + node = node.find_next_sibling() |
| 165 | + |
| 166 | + type_to_color = {type_: color for type_, color in zip(type_list, color_list) if type_ in types} |
| 167 | + for region in regions: |
| 168 | + region.plot_color = type_to_color.get(region.type) |
| 169 | + |
| 170 | + |
| 171 | +def _run_coderec_in_docker(file: FileIO) -> tuple[str, bytes]: |
| 172 | + with TemporaryDirectory() as tmp_dir: |
| 173 | + result = run_docker_container( |
| 174 | + DOCKER_IMAGE, |
| 175 | + command='--big-file /io/input', |
| 176 | + mounts=[ |
| 177 | + Mount('/io', tmp_dir, type='bind'), |
| 178 | + Mount('/io/input', str(file.name), type='bind'), |
| 179 | + ], |
| 180 | + ) |
| 181 | + output_svg = Path(tmp_dir, 'regions_plot.svg').read_bytes() |
| 182 | + return result.stdout, output_svg |
0 commit comments