blint 2.3.0__tar.gz → 2.3.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. {blint-2.3.0 → blint-2.3.2}/PKG-INFO +12 -6
  2. {blint-2.3.0 → blint-2.3.2}/README.md +8 -4
  3. {blint-2.3.0 → blint-2.3.2}/blint/cli.py +50 -57
  4. {blint-2.3.0 → blint-2.3.2}/blint/config.py +54 -0
  5. blint-2.3.2/blint/lib/__init__.py +0 -0
  6. blint-2.3.2/blint/lib/analysis.py +356 -0
  7. {blint-2.3.0/blint → blint-2.3.2/blint/lib}/android.py +33 -26
  8. {blint-2.3.0/blint → blint-2.3.2/blint/lib}/binary.py +1 -1
  9. {blint-2.3.0/blint → blint-2.3.2/blint/lib}/checks.py +1 -1
  10. blint-2.3.2/blint/lib/runners.py +373 -0
  11. {blint-2.3.0/blint → blint-2.3.2/blint/lib}/sbom.py +92 -54
  12. {blint-2.3.0/blint → blint-2.3.2/blint/lib}/utils.py +38 -1
  13. {blint-2.3.0 → blint-2.3.2}/pyproject.toml +5 -3
  14. blint-2.3.0/blint/analysis.py +0 -714
  15. {blint-2.3.0 → blint-2.3.2}/LICENSE +0 -0
  16. {blint-2.3.0 → blint-2.3.2}/blint/__init__.py +0 -0
  17. {blint-2.3.0 → blint-2.3.2}/blint/cyclonedx/README.md +0 -0
  18. {blint-2.3.0 → blint-2.3.2}/blint/cyclonedx/__init__.py +0 -0
  19. {blint-2.3.0 → blint-2.3.2}/blint/cyclonedx/spdx.py +0 -0
  20. {blint-2.3.0 → blint-2.3.2}/blint/cyclonedx/spec.py +0 -0
  21. {blint-2.3.0 → blint-2.3.2}/blint/data/__init__.py +0 -0
  22. {blint-2.3.0 → blint-2.3.2}/blint/data/annotations/__init__.py +0 -0
  23. {blint-2.3.0 → blint-2.3.2}/blint/data/annotations/review_entries_generic.yml +0 -0
  24. {blint-2.3.0 → blint-2.3.2}/blint/data/annotations/review_entries_pe.yml +0 -0
  25. {blint-2.3.0 → blint-2.3.2}/blint/data/annotations/review_exe_go.yml +0 -0
  26. {blint-2.3.0 → blint-2.3.2}/blint/data/annotations/review_imports_pe.yml +0 -0
  27. {blint-2.3.0 → blint-2.3.2}/blint/data/annotations/review_methods_generic.yml +0 -0
  28. {blint-2.3.0 → blint-2.3.2}/blint/data/annotations/review_methods_mips.yml +0 -0
  29. {blint-2.3.0 → blint-2.3.2}/blint/data/annotations/review_monero_generic.yml +0 -0
  30. {blint-2.3.0 → blint-2.3.2}/blint/data/annotations/review_monero_go.yml +0 -0
  31. {blint-2.3.0 → blint-2.3.2}/blint/data/annotations/review_monero_rust.yml +0 -0
  32. {blint-2.3.0 → blint-2.3.2}/blint/data/annotations/review_rootkits_win.yml +0 -0
  33. {blint-2.3.0 → blint-2.3.2}/blint/data/annotations/review_symbols_antiforensic.yml +0 -0
  34. {blint-2.3.0 → blint-2.3.2}/blint/data/annotations/review_symbols_generic.yml +0 -0
  35. {blint-2.3.0 → blint-2.3.2}/blint/data/annotations/review_symbols_hooka.yml +0 -0
  36. {blint-2.3.0 → blint-2.3.2}/blint/data/annotations/review_symbols_macho.yml +0 -0
  37. {blint-2.3.0 → blint-2.3.2}/blint/data/annotations/review_symbols_rust.yml +0 -0
  38. {blint-2.3.0 → blint-2.3.2}/blint/data/rules.yml +0 -0
  39. {blint-2.3.0 → blint-2.3.2}/blint/logger.py +0 -0
@@ -1,13 +1,13 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: blint
3
- Version: 2.3.0
3
+ Version: 2.3.2
4
4
  Summary: Linter and SBOM generator for binary files.
5
5
  Home-page: https://github.com/OWASP-dep-scan/blint
6
6
  License: MIT
7
7
  Keywords: linter,binary,security,sast
8
8
  Author: Prabhu Subramanian
9
9
  Author-email: prabhu@appthreat.com
10
- Requires-Python: >=3.10,<3.13
10
+ Requires-Python: >=3.10,<3.14
11
11
  Classifier: Development Status :: 5 - Production/Stable
12
12
  Classifier: Intended Audience :: Developers
13
13
  Classifier: Intended Audience :: System Administrators
@@ -17,10 +17,12 @@ Classifier: Programming Language :: Python :: 3
17
17
  Classifier: Programming Language :: Python :: 3.10
18
18
  Classifier: Programming Language :: Python :: 3.11
19
19
  Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
20
21
  Classifier: Topic :: Security
21
22
  Classifier: Topic :: Utilities
22
23
  Requires-Dist: PyYAML (>=6.0.1,<7.0.0)
23
24
  Requires-Dist: ar (>=0.9.1,<0.10.0)
25
+ Requires-Dist: custom-json-diff (>=2.1.4,<2.2.0)
24
26
  Requires-Dist: defusedxml (>=0.7.1,<0.8.0)
25
27
  Requires-Dist: lief (>=0.15.1,<0.16.0)
26
28
  Requires-Dist: orjson (>=3.10.6,<4.0.0)
@@ -102,17 +104,21 @@ sub-commands:
102
104
  ### SBOM sub-command
103
105
 
104
106
  ```shell
105
- usage: blint sbom [-h] [-i SRC_DIR_IMAGE [SRC_DIR_IMAGE ...]] [-o SBOM_OUTPUT] [--deep]
107
+ usage: blint sbom [-h] [-i SRC_DIR_IMAGE [SRC_DIR_IMAGE ...]] [-o SBOM_OUTPUT] [--deep] [--stdout] [--exports-prefix EXPORTS_PREFIX [EXPORTS_PREFIX ...]]
108
+ [--bom-src SRC_DIR_BOMS [SRC_DIR_BOMS ...]]
106
109
 
107
110
  options:
108
111
  -h, --help show this help message and exit
109
112
  -i SRC_DIR_IMAGE [SRC_DIR_IMAGE ...], --src SRC_DIR_IMAGE [SRC_DIR_IMAGE ...]
110
113
  Source directories, container images or binary files. Defaults to current directory.
111
114
  -o SBOM_OUTPUT, --output-file SBOM_OUTPUT
112
- SBOM output file. Defaults to bom.json in current directory.
113
- --deep Enable deep mode to collect more used symbols and modules aggressively. Slow
114
- operation.
115
+ SBOM output file. Defaults to bom-post-build.cdx.json in current directory.
116
+ --deep Enable deep mode to collect more used symbols and modules aggressively. Slow operation.
115
117
  --stdout Print the SBOM to stdout instead of a file.
118
+ --exports-prefix EXPORTS_PREFIX [EXPORTS_PREFIX ...]
119
+ prefixes for the exports to be included in the SBOM.
120
+ --bom-src SRC_DIR_BOMS [SRC_DIR_BOMS ...]
121
+ Directories containing pre-build and build BOMs. Use to improve the precision.
116
122
  ```
117
123
 
118
124
  To test any binary, including default commands
@@ -69,17 +69,21 @@ sub-commands:
69
69
  ### SBOM sub-command
70
70
 
71
71
  ```shell
72
- usage: blint sbom [-h] [-i SRC_DIR_IMAGE [SRC_DIR_IMAGE ...]] [-o SBOM_OUTPUT] [--deep]
72
+ usage: blint sbom [-h] [-i SRC_DIR_IMAGE [SRC_DIR_IMAGE ...]] [-o SBOM_OUTPUT] [--deep] [--stdout] [--exports-prefix EXPORTS_PREFIX [EXPORTS_PREFIX ...]]
73
+ [--bom-src SRC_DIR_BOMS [SRC_DIR_BOMS ...]]
73
74
 
74
75
  options:
75
76
  -h, --help show this help message and exit
76
77
  -i SRC_DIR_IMAGE [SRC_DIR_IMAGE ...], --src SRC_DIR_IMAGE [SRC_DIR_IMAGE ...]
77
78
  Source directories, container images or binary files. Defaults to current directory.
78
79
  -o SBOM_OUTPUT, --output-file SBOM_OUTPUT
79
- SBOM output file. Defaults to bom.json in current directory.
80
- --deep Enable deep mode to collect more used symbols and modules aggressively. Slow
81
- operation.
80
+ SBOM output file. Defaults to bom-post-build.cdx.json in current directory.
81
+ --deep Enable deep mode to collect more used symbols and modules aggressively. Slow operation.
82
82
  --stdout Print the SBOM to stdout instead of a file.
83
+ --exports-prefix EXPORTS_PREFIX [EXPORTS_PREFIX ...]
84
+ prefixes for the exports to be included in the SBOM.
85
+ --bom-src SRC_DIR_BOMS [SRC_DIR_BOMS ...]
86
+ Directories containing pre-build and build BOMs. Use to improve the precision.
83
87
  ```
84
88
 
85
89
  To test any binary, including default commands
@@ -2,14 +2,14 @@
2
2
  # -*- coding: utf-8 -*-
3
3
 
4
4
  import argparse
5
- import logging
6
5
  import os
7
- import sys
8
6
 
9
- from blint.analysis import AnalysisRunner, report
7
+ from blint.lib.runners import run_default_mode, run_sbom_mode
8
+ from blint.lib.runners import AnalysisRunner, run_default_mode, run_sbom_mode
9
+ from blint.config import BlintOptions
10
10
  from blint.logger import LOG
11
- from blint.sbom import generate
12
- from blint.utils import gen_file_list
11
+ from blint.lib.sbom import generate
12
+ from blint.lib.utils import gen_file_list
13
13
 
14
14
  BLINT_LOGO = """
15
15
  ██████╗ ██╗ ██╗███╗ ██╗████████╗
@@ -25,10 +25,23 @@ def build_args():
25
25
  """
26
26
  Constructs command line arguments for the blint tool
27
27
  """
28
+ parser = build_parser()
29
+ return parser.parse_args()
30
+
31
+
32
+ def build_parser():
28
33
  parser = argparse.ArgumentParser(
29
34
  prog="blint",
30
35
  description="Binary linter and SBOM generator.",
31
36
  )
37
+ parser.set_defaults(
38
+ deep_mode=False,
39
+ sbom_output="",
40
+ stdout_mode=False,
41
+ exports_prefix=[],
42
+ src_dir_boms=[],
43
+ sbom_mode=False
44
+ )
32
45
  parser.add_argument(
33
46
  "-i",
34
47
  "--src",
@@ -82,20 +95,20 @@ def build_args():
82
95
  sbom_parser = subparsers.add_parser(
83
96
  "sbom", help="Command to generate SBOM for supported binaries."
84
97
  )
98
+ sbom_parser.set_defaults(sbom_mode=True)
85
99
  sbom_parser.add_argument(
86
100
  "-i",
87
101
  "--src",
88
102
  dest="src_dir_image",
89
103
  action="extend",
90
104
  nargs="+",
91
- help="Source directories, container images or binary files. Defaults "
92
- "to current directory.",
105
+ help="Source directories, container images or binary files. Defaults to current directory.",
93
106
  )
94
107
  sbom_parser.add_argument(
95
108
  "-o",
96
109
  "--output-file",
97
110
  dest="sbom_output",
98
- help="SBOM output file. Defaults to bom.json in current directory.",
111
+ help="SBOM output file. Defaults to bom-post-build.cdx.json in current directory.",
99
112
  )
100
113
  sbom_parser.add_argument(
101
114
  "--deep",
@@ -120,7 +133,15 @@ def build_args():
120
133
  dest="exports_prefix",
121
134
  help="prefixes for the exports to be included in the SBOM.",
122
135
  )
123
- return parser.parse_args()
136
+ sbom_parser.add_argument(
137
+ "--bom-src",
138
+ dest="src_dir_boms",
139
+ action="extend",
140
+ nargs="+",
141
+ help="Directories containing pre-build and build BOMs. Use to improve the precision.",
142
+ )
143
+
144
+ return parser
124
145
 
125
146
 
126
147
  def parse_input(src):
@@ -146,68 +167,40 @@ def parse_input(src):
146
167
  def handle_args():
147
168
  """Handles the command-line arguments.
148
169
 
149
- This function parses the command-line arguments and returns the parsed
150
- arguments, reports directory, and source directory.
170
+ This function parses the command-line arguments and returns a BlintOptions object
151
171
 
152
172
  Returns:
153
- tuple: A tuple containing the parsed arguments, reports directory, and
154
- source directory.
173
+ BlintOptions: A class containing the parsed command-line arguments
155
174
  """
156
175
  args = build_args()
157
176
  if not args.no_banner and args.subcommand_name != "sbom":
158
177
  print(BLINT_LOGO)
159
- if not args.src_dir_image:
160
- args.src_dir_image = [os.getcwd()]
161
- if not os.getenv("CI"):
162
- src_dirs = args.src_dir_image
163
- else:
164
- src_dirs = parse_input(args.src_dir_image)
165
-
166
- # Create reports directory
167
- reports_dir = args.reports_dir
168
-
169
- for src in src_dirs:
170
- if not os.path.exists(src):
171
- LOG.error(f"{src} is an invalid file or directory!")
172
- sys.exit(1)
173
- return args, reports_dir, src_dirs
178
+ blint_options = BlintOptions(
179
+ deep_mode=args.deep_mode,
180
+ exports_prefix=args.exports_prefix,
181
+ fuzzy=args.suggest_fuzzable,
182
+ no_error=args.noerror,
183
+ no_reviews=args.no_reviews,
184
+ reports_dir=args.reports_dir,
185
+ sbom_mode=args.sbom_mode,
186
+ sbom_output=args.sbom_output,
187
+ src_dir_boms=args.src_dir_boms,
188
+ src_dir_image=args.src_dir_image,
189
+ stdout_mode=args.stdout_mode
190
+ )
191
+ return blint_options
174
192
 
175
193
 
176
194
  def main():
177
195
  """Main function of the blint tool"""
178
- args, reports_dir, src_dirs = handle_args()
196
+ blint_options = handle_args()
179
197
 
180
198
  # SBOM command
181
- if args.subcommand_name == "sbom":
182
- if args.stdout_mode:
183
- sbom_output = sys.stdout
184
- LOG.setLevel(logging.ERROR)
185
- else:
186
- if args.sbom_output:
187
- sbom_output = args.sbom_output
188
- if os.path.isdir(sbom_output):
189
- sbom_output = os.path.join(sbom_output, "bom.json")
190
- else:
191
- sbom_output = os.path.join(os.getcwd(), "bom.json")
192
- sbom_output_dir = os.path.dirname(sbom_output)
193
- if sbom_output_dir and not os.path.exists(sbom_output_dir):
194
- os.makedirs(sbom_output_dir)
195
- generate(src_dirs, sbom_output, args.deep_mode, args.exports_prefix)
199
+ if blint_options.sbom_mode:
200
+ run_sbom_mode(blint_options)
196
201
  # Default case
197
202
  else:
198
- if reports_dir and not os.path.exists(reports_dir):
199
- os.makedirs(reports_dir)
200
- files = gen_file_list(src_dirs)
201
- analyzer = AnalysisRunner()
202
- findings, reviews, fuzzables = analyzer.start(
203
- files, reports_dir, args.no_reviews, args.suggest_fuzzable
204
- )
205
- report(src_dirs, reports_dir, findings, reviews, files, fuzzables)
206
-
207
- if os.getenv("CI") and not args.noerror:
208
- for f in findings:
209
- if f['severity'] == 'critical':
210
- sys.exit(1)
203
+ run_default_mode(blint_options)
211
204
 
212
205
 
213
206
  if __name__ == "__main__":
@@ -1,6 +1,10 @@
1
1
  # pylint: disable=too-many-lines
2
+ import sys
3
+ from dataclasses import dataclass, field
2
4
  import os
3
5
  import re
6
+ from typing import List
7
+
4
8
 
5
9
  # Default ignore list
6
10
  ignore_directories = [
@@ -1268,6 +1272,56 @@ def get_int_from_env(name, default):
1268
1272
  return int(get_float_from_env(name, default))
1269
1273
 
1270
1274
 
1275
+ @dataclass
1276
+ class BlintOptions:
1277
+ """
1278
+ A data class representing the command-line options for the blint tool.
1279
+
1280
+ Attributes:
1281
+ deep_mode (bool): Flag indicating whether to perform deep analysis.
1282
+ exports_prefix (list): Prefixes to determine exported symbols.
1283
+ fuzzy (bool): Flag indicating whether to perform fuzzy analysis.
1284
+ no_error (bool): Flag indicating whether to suppress error messages.
1285
+ no_reviews (bool): Flag indicating whether to perform symbol reviews.
1286
+ reports_dir (str): The path to the reports directory.
1287
+ sbom_mode (bool): Flag indicating whether to perform SBOM analysis.
1288
+ src_dir_image (list): A list of source directories.
1289
+ sbom_output (str): The path to the output file.
1290
+ deep_mode (bool): Flag indicating whether to perform deep analysis.
1291
+ export_prefixes (list): Prefixes to determine exported symbols.
1292
+ src_dir_boms (list): Directory containing pre-build and build sboms.
1293
+ """
1294
+ deep_mode: bool = False
1295
+ exports_prefix: List = field(default_factory=list)
1296
+ fuzzy: bool = False
1297
+ no_error: bool = False
1298
+ no_reviews: bool = False
1299
+ reports_dir: str = ""
1300
+ sbom_mode: bool = False
1301
+ sbom_output: str = ""
1302
+ sbom_output_dir: str = ""
1303
+ src_dir_boms: List = field(default_factory=list)
1304
+ src_dir_image: List = field(default_factory=list)
1305
+ stdout_mode: bool = False
1306
+
1307
+ def __post_init__(self):
1308
+ if not self.src_dir_image and not (self.sbom_mode and self.src_dir_boms):
1309
+ self.sources = [os.getcwd()]
1310
+ if not self.reports_dir:
1311
+ self.reports_dir = os.getcwd()
1312
+ if self.sbom_mode:
1313
+ if self.stdout_mode:
1314
+ self.sbom_output = sys.stdout
1315
+ elif not self.sbom_output:
1316
+ self.sbom_output = os.path.join(self.reports_dir, "bom-post-build.cdx.json")
1317
+ self.sbom_output_dir = os.path.join(self.reports_dir)
1318
+ elif os.path.isdir(self.sbom_output):
1319
+ self.sbom_output_dir = self.sbom_output
1320
+ self.sbom_output = os.path.join(self.sbom_output, "bom-post-build.cdx.json")
1321
+ else:
1322
+ self.sbom_output_dir = os.path.dirname(self.sbom_output)
1323
+
1324
+
1271
1325
  # PII related symbols
1272
1326
  PII_WORDS = (
1273
1327
  "FirstName",
File without changes
@@ -0,0 +1,356 @@
1
+ import contextlib
2
+ import importlib # noqa
3
+ import os
4
+ import re
5
+ import sys
6
+ import uuid
7
+ from collections import defaultdict
8
+ from datetime import datetime
9
+ from itertools import islice
10
+ from pathlib import Path
11
+
12
+ import yaml
13
+ from rich.terminal_theme import MONOKAI
14
+
15
+ from blint.lib.binary import parse
16
+
17
+ # pylint: disable-next=unused-import
18
+ from blint.lib.checks import (
19
+ check_nx,
20
+ check_pie,
21
+ check_relro,
22
+ check_canary,
23
+ check_rpath,
24
+ check_virtual_size,
25
+ check_authenticode,
26
+ check_dll_characteristics,
27
+ check_codesign,
28
+ check_trust_info,
29
+ )
30
+ from blint.config import FIRST_STAGE_WORDS, PII_WORDS, get_int_from_env
31
+ from blint.logger import LOG, console
32
+ from blint.lib.utils import (
33
+ create_findings_table,
34
+ is_fuzzable_name,
35
+ print_findings_table,
36
+ export_metadata
37
+ )
38
+
39
+ try:
40
+ import importlib.resources # pylint: disable=ungrouped-imports
41
+
42
+ HAVE_RESOURCE_READER = True
43
+ except ImportError:
44
+ HAVE_RESOURCE_READER = False
45
+
46
+ review_files = []
47
+ if HAVE_RESOURCE_READER:
48
+ with contextlib.suppress(NameError, FileNotFoundError):
49
+ review_files = (
50
+ resource.name
51
+ for resource in importlib.resources.files("blint.data.annotations").iterdir()
52
+ if resource.is_file() and resource.name.endswith(".yml")
53
+ )
54
+ if not review_files:
55
+ review_methods_dir = Path(__file__).parent / "data" / "annotations"
56
+ review_files = [p.as_posix() for p in Path(review_methods_dir).rglob("*.yml")]
57
+
58
+ rules_dict = {}
59
+ review_exe_dict = defaultdict(list)
60
+ review_methods_dict = defaultdict(list)
61
+ review_symbols_dict = defaultdict(list)
62
+ review_imports_dict = defaultdict(list)
63
+ review_entries_dict = defaultdict(list)
64
+ review_rules_cache = {
65
+ "PII_READ": {
66
+ "id": "PII_READ",
67
+ "title": "Detect PII Read Operations",
68
+ "summary": "Can Retrieve Sensitive PII data",
69
+ "description": "Contains logic to retrieve sensitive data such as names, email, passwords etc.",
70
+ "patterns": PII_WORDS,
71
+ },
72
+ "LOADER_SYMBOLS": {
73
+ "id": "LOADER_SYMBOLS",
74
+ "title": "Detect Initial Loader",
75
+ "summary": "Behaves like a loader",
76
+ "description": "The binary behaves like a loader by downloading and executing additional payloads.",
77
+ "patterns": FIRST_STAGE_WORDS,
78
+ },
79
+ }
80
+
81
+ # Debug mode
82
+ DEBUG_MODE = os.getenv("SCAN_DEBUG_MODE") == "debug"
83
+
84
+ # No of evidences per category
85
+ EVIDENCE_LIMIT = get_int_from_env("EVIDENCE_LIMIT", 5)
86
+
87
+
88
+ def get_resource(package, resource):
89
+ """Return a file handle on a named resource in a Package."""
90
+
91
+ # Prefer ResourceReader APIs, as they are newest.
92
+ if HAVE_RESOURCE_READER:
93
+ # If we're in the context of a module, we could also use
94
+ # ``__loader__.get_resource_reader(__name__).open_resource(resource)``.
95
+ # We use open_binary() because it is simple.
96
+ return importlib.resources.files(package).joinpath(resource).open("r", encoding="utf-8")
97
+
98
+ # Fall back to __file__.
99
+
100
+ # We need to first import the package so we can find its location.
101
+ # This could raise an exception!
102
+ mod = importlib.import_module(package)
103
+
104
+ # Undefined __file__ will raise NameError on variable access.
105
+ try:
106
+ package_path = os.path.abspath(os.path.dirname(mod.__file__))
107
+ except NameError:
108
+ package_path = None
109
+
110
+ if package_path is not None:
111
+ # Warning: there is a path traversal attack possible here if
112
+ # resource contains values like ../../../../etc/password. Input
113
+ # must be trusted or sanitized before blindly opening files or
114
+ # you may have a security vulnerability!
115
+ resource_path = os.path.join(package_path, resource)
116
+
117
+ return open(resource_path, "r", encoding="utf-8")
118
+
119
+ # Could not resolve package path from __file__.
120
+ LOG.warning(f"Unable to load resource: {package}:{resource}")
121
+ return None
122
+
123
+
124
+ # Load the rules
125
+ with get_resource("blint.data", "rules.yml") as fp:
126
+ raw_rules = fp.read().split("---")
127
+ for tmp_data in raw_rules:
128
+ if not tmp_data:
129
+ continue
130
+ rules_list = yaml.safe_load(tmp_data)
131
+ for rule in rules_list:
132
+ rules_dict[rule.get("id")] = rule
133
+
134
+ # Load the default review methods
135
+ for review_methods_file in review_files:
136
+ raw_annotations = []
137
+ if DEBUG_MODE:
138
+ LOG.debug(f"Loading review file {review_methods_file}")
139
+ with get_resource("blint.data.annotations", review_methods_file) as fp:
140
+ raw_annotations = fp.read().split("---")
141
+ for tmp_data in raw_annotations:
142
+ if not tmp_data:
143
+ continue
144
+ methods_reviews_groups = yaml.safe_load(tmp_data)
145
+ exe_type_list = methods_reviews_groups.get("exe_type")
146
+ if isinstance(exe_type_list, str):
147
+ exe_type_list = [exe_type_list]
148
+ all_rules = methods_reviews_groups.get("rules")
149
+ method_rules_dict = {}
150
+ for rule in all_rules:
151
+ method_rules_dict[rule.get("id")] = rule
152
+ review_rules_cache[rule.get("id")] = rule
153
+ for etype in exe_type_list:
154
+ if methods_reviews_groups.get("group") == "METHOD_REVIEWS":
155
+ review_methods_dict[etype].append(method_rules_dict)
156
+ elif methods_reviews_groups.get("group") == "EXE_REVIEWS":
157
+ review_exe_dict[etype].append(method_rules_dict)
158
+ elif methods_reviews_groups.get("group") == "SYMBOL_REVIEWS":
159
+ review_symbols_dict[etype].append(method_rules_dict)
160
+ elif methods_reviews_groups.get("group") == "IMPORT_REVIEWS":
161
+ review_imports_dict[etype].append(method_rules_dict)
162
+ elif methods_reviews_groups.get("group") == "ENTRIES_REVIEWS":
163
+ review_entries_dict[etype].append(method_rules_dict)
164
+
165
+
166
+ def run_checks(f, metadata):
167
+ """Runs the checks on the provided metadata using the loaded rules.
168
+
169
+ Args:
170
+ f: The metadata of the functions.
171
+ metadata: The metadata containing information about the executable.
172
+
173
+ Returns:
174
+ A list of result dictionaries representing the outcomes of the checks.
175
+
176
+ """
177
+ results = []
178
+ if not rules_dict:
179
+ LOG.warning("No rules loaded!")
180
+ return results
181
+ if not metadata:
182
+ return results
183
+ exe_type = metadata.get("exe_type")
184
+ for cid, rule_obj in rules_dict.items():
185
+ rule_exe_types = rule_obj.get("exe_types")
186
+ # Skip rules that are not valid for this exe type
187
+ if exe_type and rule_exe_types and exe_type not in rule_exe_types:
188
+ continue
189
+ if result := run_rule(f, metadata, rule_obj, exe_type, cid):
190
+ results.append(result)
191
+ return results
192
+
193
+
194
+ def run_rule(f, metadata, rule_obj, exe_type, cid):
195
+ """
196
+ Runs a rule on a file with the provided metadata, rule object, executable
197
+ type, and component ID.
198
+
199
+ Args:
200
+ f (str): The file path to run the rule on.
201
+ metadata (dict): The metadata of the file.
202
+ rule_obj (dict): The rule object to compare against.
203
+ exe_type (str): The executable type of the file.
204
+ cid (str): The component ID.
205
+
206
+ Returns:
207
+ str or dict: The result of running the rule on the file
208
+ """
209
+ if cfn := getattr(sys.modules[__name__], cid.lower(), None):
210
+ result = cfn(f, metadata, rule_obj=rule_obj)
211
+ if result is False or isinstance(result, str):
212
+ aresult = {**rule_obj, "filename": f}
213
+ return process_result(metadata, aresult, exe_type, result)
214
+ return ""
215
+
216
+
217
+ def process_result(metadata, aresult, exe_type, result):
218
+ """Processes the result by modifying the provided result dictionary.
219
+
220
+ Args:
221
+ metadata: The metadata containing information about the executable.
222
+ aresult: The result dictionary to be modified.
223
+ exe_type: The type of the executable.
224
+ result: The result value to be processed.
225
+
226
+ Returns:
227
+ The modified result dictionary.
228
+
229
+ """
230
+ if isinstance(result, str):
231
+ aresult["title"] = f"{aresult['title']} ({result})"
232
+ if metadata.get("name"):
233
+ aresult["exe_name"] = metadata.get("name")
234
+ aresult["exe_type"] = exe_type
235
+ return aresult
236
+
237
+
238
+ def run_prefuzz(metadata):
239
+ """Runs the pre-fuzzing process on the given metadata.
240
+
241
+ Generates a list of fuzzable methods from the provided metadata by
242
+ extracting the function names and addresses.
243
+
244
+ Args:
245
+ metadata: The metadata containing the functions.
246
+
247
+ Returns:
248
+ A list of fuzzable methods with their names and addresses.
249
+
250
+ """
251
+ functions_list = [
252
+ {
253
+ "name": re.sub(r"[*&()]", "", f.get("name", "")),
254
+ "address": f.get("address", ""),
255
+ }
256
+ for f in metadata.get("functions", [])
257
+ ]
258
+ functions_list += [
259
+ {
260
+ "name": re.sub(r"[*&()]", "", f.get("name", "")),
261
+ "address": f.get("address", ""),
262
+ }
263
+ for f in metadata.get("ctor_functions", [])
264
+ ]
265
+ functions_list += [
266
+ {
267
+ "name": re.sub(r"[*&()]", "", f.get("name", "")),
268
+ "address": f.get("address", ""),
269
+ }
270
+ for f in metadata.get("exception_functions", [])
271
+ ]
272
+ functions_list += [
273
+ {
274
+ "name": re.sub(r"[*&()]", "", f.get("name", "")),
275
+ "address": f.get("address", ""),
276
+ }
277
+ for f in metadata.get("unwind_functions", [])
278
+ ]
279
+ functions_list += [
280
+ {"name": f.get("name", ""), "address": f.get("address", "")}
281
+ for f in metadata.get("exports", [])
282
+ ]
283
+ fuzzables = [
284
+ {"name": f.get("name"), "address": f.get("address", "").strip()}
285
+ for f in functions_list
286
+ if is_fuzzable_name(f.get("name"))
287
+ ]
288
+ LOG.debug(f"Found {len(fuzzables)} fuzzable methods")
289
+ return fuzzables
290
+
291
+
292
+ def print_reviews_table(reviews, files):
293
+ """Prints the capability review table.
294
+
295
+ Args:
296
+ reviews: A list of dictionaries representing the capability reviews.
297
+ files: A list of file names associated with the reviews.
298
+
299
+ """
300
+ table = create_findings_table(files, "BLint Capability Review")
301
+ table.add_column("Capabilities")
302
+ table.add_column("Evidence (Top 5)", overflow="fold")
303
+ for r in reviews:
304
+ evidences = [e.get("function") for e in r.get("evidence")]
305
+ evidences = list(islice(evidences, EVIDENCE_LIMIT))
306
+ if len(files) > 1:
307
+ table.add_row(
308
+ r.get("id"),
309
+ r.get("exe_name"),
310
+ r.get("summary"),
311
+ "\n".join(evidences),
312
+ )
313
+ else:
314
+ table.add_row(
315
+ r.get("id"),
316
+ r.get("summary"),
317
+ "\n".join(evidences),
318
+ )
319
+ console.print(table)
320
+
321
+
322
+ def report(blint_options, exe_files, findings, reviews, fuzzables):
323
+ """Generates a report based on the analysis results.
324
+
325
+ Args:
326
+ blint_options: A BlintOptions object containing settings.
327
+ exe_files: A list of file names associated with the findings and reviews.
328
+ findings: A list of dictionaries representing the findings.
329
+ reviews: A list of dictionaries representing the reviews.
330
+ fuzzables: A list of fuzzable methods.
331
+
332
+ """
333
+ if not findings and not reviews:
334
+ LOG.info(f":white_heavy_check_mark: No issues found in {blint_options.src_dir_image}!")
335
+ return
336
+ if not os.path.exists(blint_options.reports_dir):
337
+ os.makedirs(blint_options.reports_dir)
338
+ run_uuid = os.environ.get("SCAN_ID", str(uuid.uuid4()))
339
+ common_metadata = {
340
+ "scan_id": run_uuid,
341
+ "created": f"{datetime.now():%Y-%m-%d %H:%M:%S%z}",
342
+ }
343
+ if findings:
344
+ print_findings_table(findings, exe_files)
345
+ export_metadata(blint_options.reports_dir, {**common_metadata, "findings": findings}, "Findings")
346
+ if reviews:
347
+ print_reviews_table(reviews, exe_files)
348
+ export_metadata(blint_options.reports_dir, {**common_metadata, "reviews": reviews}, "Reviews")
349
+ if fuzzables:
350
+ export_metadata(blint_options.reports_dir, {**common_metadata, "fuzzables": fuzzables}, "Fuzzables")
351
+ else:
352
+ LOG.debug("No suggestion available for fuzzing")
353
+ # Try console output as html
354
+ html_file = Path(blint_options.reports_dir) / "blint-output.html"
355
+ console.save_html(html_file, theme=MONOKAI)
356
+ LOG.info(f"HTML report written to {html_file}")