blint 2.3.1__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.1 → blint-2.3.2}/PKG-INFO +2 -1
  2. {blint-2.3.1 → blint-2.3.2}/blint/cli.py +42 -56
  3. {blint-2.3.1 → blint-2.3.2}/blint/config.py +54 -0
  4. blint-2.3.2/blint/lib/__init__.py +0 -0
  5. blint-2.3.2/blint/lib/analysis.py +356 -0
  6. {blint-2.3.1/blint → blint-2.3.2/blint/lib}/android.py +14 -11
  7. {blint-2.3.1/blint → blint-2.3.2/blint/lib}/binary.py +1 -1
  8. {blint-2.3.1/blint → blint-2.3.2/blint/lib}/checks.py +1 -1
  9. blint-2.3.2/blint/lib/runners.py +373 -0
  10. {blint-2.3.1/blint → blint-2.3.2/blint/lib}/sbom.py +34 -58
  11. {blint-2.3.1/blint → blint-2.3.2/blint/lib}/utils.py +27 -0
  12. {blint-2.3.1 → blint-2.3.2}/pyproject.toml +2 -1
  13. blint-2.3.1/blint/analysis.py +0 -714
  14. {blint-2.3.1 → blint-2.3.2}/LICENSE +0 -0
  15. {blint-2.3.1 → blint-2.3.2}/README.md +0 -0
  16. {blint-2.3.1 → blint-2.3.2}/blint/__init__.py +0 -0
  17. {blint-2.3.1 → blint-2.3.2}/blint/cyclonedx/README.md +0 -0
  18. {blint-2.3.1 → blint-2.3.2}/blint/cyclonedx/__init__.py +0 -0
  19. {blint-2.3.1 → blint-2.3.2}/blint/cyclonedx/spdx.py +0 -0
  20. {blint-2.3.1 → blint-2.3.2}/blint/cyclonedx/spec.py +0 -0
  21. {blint-2.3.1 → blint-2.3.2}/blint/data/__init__.py +0 -0
  22. {blint-2.3.1 → blint-2.3.2}/blint/data/annotations/__init__.py +0 -0
  23. {blint-2.3.1 → blint-2.3.2}/blint/data/annotations/review_entries_generic.yml +0 -0
  24. {blint-2.3.1 → blint-2.3.2}/blint/data/annotations/review_entries_pe.yml +0 -0
  25. {blint-2.3.1 → blint-2.3.2}/blint/data/annotations/review_exe_go.yml +0 -0
  26. {blint-2.3.1 → blint-2.3.2}/blint/data/annotations/review_imports_pe.yml +0 -0
  27. {blint-2.3.1 → blint-2.3.2}/blint/data/annotations/review_methods_generic.yml +0 -0
  28. {blint-2.3.1 → blint-2.3.2}/blint/data/annotations/review_methods_mips.yml +0 -0
  29. {blint-2.3.1 → blint-2.3.2}/blint/data/annotations/review_monero_generic.yml +0 -0
  30. {blint-2.3.1 → blint-2.3.2}/blint/data/annotations/review_monero_go.yml +0 -0
  31. {blint-2.3.1 → blint-2.3.2}/blint/data/annotations/review_monero_rust.yml +0 -0
  32. {blint-2.3.1 → blint-2.3.2}/blint/data/annotations/review_rootkits_win.yml +0 -0
  33. {blint-2.3.1 → blint-2.3.2}/blint/data/annotations/review_symbols_antiforensic.yml +0 -0
  34. {blint-2.3.1 → blint-2.3.2}/blint/data/annotations/review_symbols_generic.yml +0 -0
  35. {blint-2.3.1 → blint-2.3.2}/blint/data/annotations/review_symbols_hooka.yml +0 -0
  36. {blint-2.3.1 → blint-2.3.2}/blint/data/annotations/review_symbols_macho.yml +0 -0
  37. {blint-2.3.1 → blint-2.3.2}/blint/data/annotations/review_symbols_rust.yml +0 -0
  38. {blint-2.3.1 → blint-2.3.2}/blint/data/rules.yml +0 -0
  39. {blint-2.3.1 → blint-2.3.2}/blint/logger.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: blint
3
- Version: 2.3.1
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
@@ -22,6 +22,7 @@ Classifier: Topic :: Security
22
22
  Classifier: Topic :: Utilities
23
23
  Requires-Dist: PyYAML (>=6.0.1,<7.0.0)
24
24
  Requires-Dist: ar (>=0.9.1,<0.10.0)
25
+ Requires-Dist: custom-json-diff (>=2.1.4,<2.2.0)
25
26
  Requires-Dist: defusedxml (>=0.7.1,<0.8.0)
26
27
  Requires-Dist: lief (>=0.15.1,<0.16.0)
27
28
  Requires-Dist: orjson (>=3.10.6,<4.0.0)
@@ -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,14 +95,14 @@ 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",
@@ -127,7 +140,8 @@ def build_args():
127
140
  nargs="+",
128
141
  help="Directories containing pre-build and build BOMs. Use to improve the precision.",
129
142
  )
130
- return parser.parse_args()
143
+
144
+ return parser
131
145
 
132
146
 
133
147
  def parse_input(src):
@@ -153,68 +167,40 @@ def parse_input(src):
153
167
  def handle_args():
154
168
  """Handles the command-line arguments.
155
169
 
156
- This function parses the command-line arguments and returns the parsed
157
- arguments, reports directory, and source directory.
170
+ This function parses the command-line arguments and returns a BlintOptions object
158
171
 
159
172
  Returns:
160
- tuple: A tuple containing the parsed arguments, reports directory, and
161
- source directory.
173
+ BlintOptions: A class containing the parsed command-line arguments
162
174
  """
163
175
  args = build_args()
164
176
  if not args.no_banner and args.subcommand_name != "sbom":
165
177
  print(BLINT_LOGO)
166
- if not args.src_dir_image:
167
- args.src_dir_image = [os.getcwd()]
168
- if not os.getenv("CI"):
169
- src_dirs = args.src_dir_image
170
- else:
171
- src_dirs = parse_input(args.src_dir_image)
172
-
173
- # Create reports directory
174
- reports_dir = args.reports_dir
175
-
176
- for src in src_dirs:
177
- if not os.path.exists(src):
178
- LOG.error(f"{src} is an invalid file or directory!")
179
- sys.exit(1)
180
- 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
181
192
 
182
193
 
183
194
  def main():
184
195
  """Main function of the blint tool"""
185
- args, reports_dir, src_dirs = handle_args()
196
+ blint_options = handle_args()
186
197
 
187
198
  # SBOM command
188
- if args.subcommand_name == "sbom":
189
- if args.stdout_mode:
190
- sbom_output = sys.stdout
191
- LOG.setLevel(logging.ERROR)
192
- else:
193
- if args.sbom_output:
194
- sbom_output = args.sbom_output
195
- if os.path.isdir(sbom_output):
196
- sbom_output = os.path.join(sbom_output, "bom-post-build.cdx.json")
197
- else:
198
- sbom_output = os.path.join(os.getcwd(), "bom-post-build.cdx.json")
199
- sbom_output_dir = os.path.dirname(sbom_output)
200
- if sbom_output_dir and not os.path.exists(sbom_output_dir):
201
- os.makedirs(sbom_output_dir)
202
- generate(src_dirs, sbom_output, args.deep_mode, args.exports_prefix, args.src_dir_boms)
199
+ if blint_options.sbom_mode:
200
+ run_sbom_mode(blint_options)
203
201
  # Default case
204
202
  else:
205
- if reports_dir and not os.path.exists(reports_dir):
206
- os.makedirs(reports_dir)
207
- files = gen_file_list(src_dirs)
208
- analyzer = AnalysisRunner()
209
- findings, reviews, fuzzables = analyzer.start(
210
- files, reports_dir, args.no_reviews, args.suggest_fuzzable
211
- )
212
- report(src_dirs, reports_dir, findings, reviews, files, fuzzables)
213
-
214
- if os.getenv("CI") and not args.noerror:
215
- for f in findings:
216
- if f['severity'] == 'critical':
217
- sys.exit(1)
203
+ run_default_mode(blint_options)
218
204
 
219
205
 
220
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}")
@@ -4,7 +4,10 @@ import subprocess
4
4
  import sys
5
5
  import tempfile
6
6
 
7
- from blint.binary import parse, parse_dex
7
+ from blint.lib.binary import parse, parse_dex
8
+ from custom_json_diff.lib.utils import file_read
9
+
10
+ from blint.lib.binary import parse, parse_dex
8
11
  from blint.config import SYMBOL_DELIMITER
9
12
  from blint.cyclonedx.spec import (
10
13
  Component,
@@ -14,7 +17,8 @@ from blint.cyclonedx.spec import (
14
17
  Type,
15
18
  )
16
19
  from blint.logger import LOG
17
- from blint.utils import check_command, create_component_evidence, find_files, unzip_unsafe
20
+ from blint.lib.utils import check_command, create_component_evidence, find_files, unzip_unsafe
21
+
18
22
 
19
23
  ANDROID_HOME = os.getenv("ANDROID_HOME")
20
24
  APKANALYZER_CMD = os.getenv("APKANALYZER_CMD")
@@ -134,16 +138,15 @@ def collect_version_files_metadata(app_file, app_temp_dir):
134
138
  name = ""
135
139
  if "_" in file_name:
136
140
  group, name = parse_file_name(file_name, group)
137
- with open(vf, encoding="utf-8") as fp:
138
- version_data = fp.read().strip()
139
- # Sometimes the version data could be dynamic. Eg:
140
- # task ':lifecycle:lifecycle-viewmodel:writeVersionFile' property 'version'"
141
- # These can be treated as dynamic
142
- if version_data and version_data.startswith("task"):
141
+ # Sometimes the version data could be dynamic. Eg:
142
+ # task ':lifecycle:lifecycle-viewmodel:writeVersionFile' property 'version'"
143
+ # These can be treated as dynamic
144
+ if version_data := file_read(vf, False, log=LOG).strip():
145
+ if version_data.startswith("task"):
143
146
  version_data = "dynamic"
144
- if name and version_data:
145
- component = create_version_component(app_file, group, name, rel_path, version_data)
146
- file_components.append(component)
147
+ if name:
148
+ component = create_version_component(app_file, group, name, rel_path, version_data)
149
+ file_components.append(component)
147
150
  return file_components
148
151
 
149
152
 
@@ -11,7 +11,7 @@ import lief
11
11
 
12
12
  from blint.config import FIRST_STAGE_WORDS, PII_WORDS, get_float_from_env, get_int_from_env
13
13
  from blint.logger import DEBUG, LOG
14
- from blint.utils import (
14
+ from blint.lib.utils import (
15
15
  camel_to_snake,
16
16
  calculate_entropy,
17
17
  check_secret,
@@ -1,5 +1,5 @@
1
1
  # pylint: disable=missing-function-docstring,unused-argument
2
- from blint.utils import parse_pe_manifest
2
+ from blint.lib.utils import parse_pe_manifest
3
3
 
4
4
 
5
5
  def check_nx(f, metadata, rule_obj): # noqa