sherlockscan 0.2.0__py3-none-any.whl
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.
- sherlockscan/__init__.py +53 -0
- sherlockscan/cli.py +319 -0
- sherlockscan/config/__init__.py +101 -0
- sherlockscan/config/approved_packages.yaml +116 -0
- sherlockscan/config/risk_patterns.yaml +191 -0
- sherlockscan/exceptions.py +62 -0
- sherlockscan/report/__init__.py +36 -0
- sherlockscan/report/json_formatter.py +140 -0
- sherlockscan/report/markdown_formatter.py +210 -0
- sherlockscan/scanner/__init__.py +42 -0
- sherlockscan/scanner/ast_scanner.py +343 -0
- sherlockscan/scanner/deps.py +203 -0
- sherlockscan/scanner/explainer.py +167 -0
- sherlockscan/scanner/heuristics.py +282 -0
- sherlockscan/scanner/install_script_analyzer.py +343 -0
- sherlockscan/utils.py +313 -0
- sherlockscan-0.2.0.dist-info/METADATA +377 -0
- sherlockscan-0.2.0.dist-info/RECORD +22 -0
- sherlockscan-0.2.0.dist-info/WHEEL +5 -0
- sherlockscan-0.2.0.dist-info/entry_points.txt +2 -0
- sherlockscan-0.2.0.dist-info/licenses/LICENSE +21 -0
- sherlockscan-0.2.0.dist-info/top_level.txt +1 -0
sherlockscan/__init__.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
# sherlockscan/__init__.py
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
from logging import NullHandler
|
|
5
|
+
|
|
6
|
+
# --- Package Version ---
|
|
7
|
+
# Define package version in one place. Read dynamically in setup.py/pyproject.toml.
|
|
8
|
+
__version__ = "0.2.0"
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
# --- Configure Library Logging ---
|
|
12
|
+
# Set up a null handler for the root logger of this package.
|
|
13
|
+
# This prevents the library from outputting log messages if the consuming
|
|
14
|
+
# application has not configured logging. Applications using sherlockscan
|
|
15
|
+
# should configure their own logging handlers.
|
|
16
|
+
logging.getLogger(__name__).addHandler(NullHandler())
|
|
17
|
+
# Optional: Set a default level for the library's logger if needed during development
|
|
18
|
+
# logging.getLogger(__name__).setLevel(logging.INFO)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
# --- Expose Key Public Elements (Optional but often useful) ---
|
|
22
|
+
# Make custom exceptions easily accessible directly from the package.
|
|
23
|
+
try:
|
|
24
|
+
from .exceptions import (
|
|
25
|
+
SherlockScanError,
|
|
26
|
+
ConfigError,
|
|
27
|
+
PackageNotFoundError,
|
|
28
|
+
ScannerError,
|
|
29
|
+
ReportFormattingError
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
# Define what 'from sherlockscan import *' would import (generally discouraged)
|
|
33
|
+
# But also serves as documentation for the public API elements exposed here.
|
|
34
|
+
__all__ = [
|
|
35
|
+
"__version__",
|
|
36
|
+
"SherlockScanError",
|
|
37
|
+
"ConfigError",
|
|
38
|
+
"PackageNotFoundError",
|
|
39
|
+
"ScannerError",
|
|
40
|
+
"ReportFormattingError",
|
|
41
|
+
# Add other core functions/classes intended for public library use here if desired
|
|
42
|
+
# e.g., maybe a high-level 'scan_package' function later?
|
|
43
|
+
]
|
|
44
|
+
|
|
45
|
+
except ImportError as e:
|
|
46
|
+
# This might happen during initial setup or if structure changes.
|
|
47
|
+
logging.getLogger(__name__).error(f"Could not import submodules on package init: {e}")
|
|
48
|
+
__all__ = ["__version__"] # Only expose version if imports fail
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
# --- Optional Package-Level Initialization ---
|
|
52
|
+
# Avoid complex logic here if possible. Keep it lightweight.
|
|
53
|
+
# Example: logging.getLogger(__name__).debug(f"SherlockScan package ({__version__}) loaded.")
|
sherlockscan/cli.py
ADDED
|
@@ -0,0 +1,319 @@
|
|
|
1
|
+
#!/usr/bin/env python
|
|
2
|
+
# coding: utf-8
|
|
3
|
+
|
|
4
|
+
# sherlockscan/cli.py
|
|
5
|
+
|
|
6
|
+
import typer
|
|
7
|
+
import json
|
|
8
|
+
import logging
|
|
9
|
+
import os
|
|
10
|
+
import sys
|
|
11
|
+
import shutil
|
|
12
|
+
import tempfile
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import List, Dict, Any, Optional, Tuple
|
|
15
|
+
from sherlockscan.exceptions import ConfigError
|
|
16
|
+
|
|
17
|
+
# --- SherlockScan Core Imports ---
|
|
18
|
+
try:
|
|
19
|
+
from sherlockscan.scanner import ast_scanner, heuristics, deps, install_script_analyzer
|
|
20
|
+
from sherlockscan.report import json_formatter, markdown_formatter
|
|
21
|
+
from sherlockscan.scanner import explainer
|
|
22
|
+
from sherlockscan import utils
|
|
23
|
+
except ImportError as e:
|
|
24
|
+
print(f"Error: Failed to import SherlockScan modules. Make sure the package is installed correctly or PYTHONPATH is set.")
|
|
25
|
+
print(f"Details: {e}")
|
|
26
|
+
sys.exit(1)
|
|
27
|
+
|
|
28
|
+
# --- Library Imports ---
|
|
29
|
+
try:
|
|
30
|
+
from importlib import metadata as importlib_metadata
|
|
31
|
+
except ImportError:
|
|
32
|
+
try:
|
|
33
|
+
import importlib_metadata # type: ignore
|
|
34
|
+
except ImportError:
|
|
35
|
+
print("Error: importlib.metadata (or backport) not found. Dependency scanning requires Python 3.8+ or `pip install importlib-metadata`.")
|
|
36
|
+
importlib_metadata = None # type: ignore
|
|
37
|
+
|
|
38
|
+
# --- Configuration ---
|
|
39
|
+
logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s')
|
|
40
|
+
SEVERITY_ORDER = ["CRITICAL", "HIGH", "MEDIUM", "LOW", "INFO"]
|
|
41
|
+
DEFAULT_SEVERITY_THRESHOLD = "INFO"
|
|
42
|
+
|
|
43
|
+
# --- Typer App Initialization ---
|
|
44
|
+
app = typer.Typer(
|
|
45
|
+
name="sherlockscan",
|
|
46
|
+
help="SherlockScan: A tool to analyze Python packages for potential security risks.",
|
|
47
|
+
add_completion=False
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
# With a single @app.command(), Typer collapses the app so `scan` was being
|
|
51
|
+
# parsed as the package_target. An explicit callback restores subcommand mode,
|
|
52
|
+
# making `sherlockscan scan <target>` work as documented in the README.
|
|
53
|
+
@app.callback()
|
|
54
|
+
def main_callback():
|
|
55
|
+
"""SherlockScan CLI."""
|
|
56
|
+
pass
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
# --- Helper Functions ---
|
|
60
|
+
|
|
61
|
+
def _calculate_summary(findings: List[Dict[str, Any]]) -> Dict[str, Any]:
|
|
62
|
+
"""Calculates the summary of findings by severity."""
|
|
63
|
+
summary = {
|
|
64
|
+
"total_findings": len(findings),
|
|
65
|
+
"by_severity": {severity: 0 for severity in SEVERITY_ORDER}
|
|
66
|
+
}
|
|
67
|
+
for finding in findings:
|
|
68
|
+
severity = finding.get("severity", "UNKNOWN")
|
|
69
|
+
if severity in summary["by_severity"]:
|
|
70
|
+
summary["by_severity"][severity] += 1
|
|
71
|
+
else:
|
|
72
|
+
if "UNKNOWN" not in summary["by_severity"]:
|
|
73
|
+
summary["by_severity"]["UNKNOWN"] = 0
|
|
74
|
+
summary["by_severity"]["UNKNOWN"] += 1
|
|
75
|
+
return summary
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _determine_overall_risk(summary: Dict[str, Any]) -> str:
|
|
79
|
+
"""Determines the overall risk level based on the highest severity finding."""
|
|
80
|
+
severity_counts = summary.get("by_severity", {})
|
|
81
|
+
for severity in SEVERITY_ORDER: # highest → lowest
|
|
82
|
+
if severity_counts.get(severity, 0) > 0:
|
|
83
|
+
return severity
|
|
84
|
+
return "INFO"
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _filter_findings_by_severity(findings: List[Dict[str, Any]], min_severity: str) -> List[Dict[str, Any]]:
|
|
88
|
+
"""Filters findings to include only those at or above the minimum severity level."""
|
|
89
|
+
if min_severity not in SEVERITY_ORDER:
|
|
90
|
+
logging.warning(f"Invalid severity level '{min_severity}'. Using default '{DEFAULT_SEVERITY_THRESHOLD}'.")
|
|
91
|
+
min_severity = DEFAULT_SEVERITY_THRESHOLD
|
|
92
|
+
|
|
93
|
+
min_severity_index = SEVERITY_ORDER.index(min_severity)
|
|
94
|
+
|
|
95
|
+
filtered_findings = []
|
|
96
|
+
for finding in findings:
|
|
97
|
+
finding_severity = finding.get("severity", "UNKNOWN")
|
|
98
|
+
try:
|
|
99
|
+
finding_severity_index = SEVERITY_ORDER.index(finding_severity)
|
|
100
|
+
if finding_severity_index <= min_severity_index: # lower index = higher severity
|
|
101
|
+
filtered_findings.append(finding)
|
|
102
|
+
except ValueError:
|
|
103
|
+
# Include unknown severities by default
|
|
104
|
+
logging.debug(f"Including finding with unknown severity: {finding_severity}")
|
|
105
|
+
filtered_findings.append(finding)
|
|
106
|
+
|
|
107
|
+
return filtered_findings
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _get_package_path_and_info(target: str) -> Optional[Tuple[Path, str, Optional[str]]]:
|
|
111
|
+
"""Resolves package directory, name, and version via utils.resolve_package_target."""
|
|
112
|
+
logging.info(f"Resolving package target: {target}")
|
|
113
|
+
try:
|
|
114
|
+
pkg_dir, pkg_name, pkg_version = utils.resolve_package_target(target)
|
|
115
|
+
return Path(pkg_dir), pkg_name, pkg_version
|
|
116
|
+
except Exception as e:
|
|
117
|
+
logging.error(f"Error resolving package '{target}': {e}")
|
|
118
|
+
return None
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _find_python_files(package_dir: Path, include_tests: bool = False) -> List[Path]:
|
|
122
|
+
"""Finds all .py files within the package directory via utils."""
|
|
123
|
+
files = utils.find_python_files(Path(package_dir), include_tests=include_tests)
|
|
124
|
+
logging.info(f"Found {len(files)} Python files to scan.")
|
|
125
|
+
return files
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _cleanup_temp_dir(package_dir: Path) -> None:
|
|
129
|
+
"""Remove temporary directories created by resolve_package_target (sherlock_download_*/sherlock_extract_*)."""
|
|
130
|
+
try:
|
|
131
|
+
pd = str(package_dir)
|
|
132
|
+
if not pd.startswith(tempfile.gettempdir()):
|
|
133
|
+
return
|
|
134
|
+
if "sherlock_download_" not in pd and "sherlock_extract_" not in pd:
|
|
135
|
+
return
|
|
136
|
+
root = Path(pd)
|
|
137
|
+
# Walk up until we find the sherlock_* directory created by mkdtemp
|
|
138
|
+
while root != root.parent:
|
|
139
|
+
if root.name.startswith("sherlock_download_") or root.name.startswith("sherlock_extract_"):
|
|
140
|
+
shutil.rmtree(root, ignore_errors=True)
|
|
141
|
+
logging.debug(f"Cleaned up temp dir: {root}")
|
|
142
|
+
return
|
|
143
|
+
root = root.parent
|
|
144
|
+
except Exception as e:
|
|
145
|
+
logging.debug(f"Temp cleanup skipped: {e}")
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
# --- Typer Command ---
|
|
149
|
+
|
|
150
|
+
@app.command()
|
|
151
|
+
def scan(
|
|
152
|
+
package_target: str = typer.Argument(..., help="Package name (from PyPI) or path to local package directory/archive."),
|
|
153
|
+
output: Optional[Path] = typer.Option(None, "--output", "-o", help="Path to save the report file."),
|
|
154
|
+
format: str = typer.Option("md", "--format", "-f", help="Output format ('json' or 'md'). Default is 'md'."),
|
|
155
|
+
config_dir: Optional[Path] = typer.Option(None, "--config", "-c", help="Path to the directory containing configuration files (risk_patterns.yaml, approved_packages.yaml). Defaults to the configs shipped with the package."),
|
|
156
|
+
severity: str = typer.Option(DEFAULT_SEVERITY_THRESHOLD, "--severity", "-s", help=f"Minimum severity level to report ({', '.join(SEVERITY_ORDER)}). Default: {DEFAULT_SEVERITY_THRESHOLD}."),
|
|
157
|
+
include_tests: bool = typer.Option(False, "--include-tests", help="Also scan bundled test and fixture code."),
|
|
158
|
+
sbom: Optional[Path] = typer.Option(None, "--sbom", help="Write a CycloneDX 1.5 JSON SBOM to this path.")
|
|
159
|
+
):
|
|
160
|
+
"""
|
|
161
|
+
Analyzes a Python package for potential security risks.
|
|
162
|
+
"""
|
|
163
|
+
logging.info(f"Starting SherlockScan for target: {package_target}")
|
|
164
|
+
|
|
165
|
+
# --- 1. Resolve Configuration Paths ---
|
|
166
|
+
if config_dir is None:
|
|
167
|
+
# Prefer the configs shipped inside the installed package
|
|
168
|
+
packaged_config = Path(__file__).parent / "config"
|
|
169
|
+
config_dir = packaged_config if packaged_config.is_dir() else Path("./config")
|
|
170
|
+
logging.info(f"No config directory specified, using default: {config_dir}")
|
|
171
|
+
|
|
172
|
+
if severity.upper() not in SEVERITY_ORDER:
|
|
173
|
+
raise typer.BadParameter(f"Choose one of: {', '.join(SEVERITY_ORDER)}", param_hint="--severity")
|
|
174
|
+
if format.lower() not in {"json", "md"}:
|
|
175
|
+
raise typer.BadParameter("Choose 'json' or 'md'", param_hint="--format")
|
|
176
|
+
|
|
177
|
+
risk_patterns_path = config_dir / "risk_patterns.yaml"
|
|
178
|
+
approved_packages_path = config_dir / "approved_packages.yaml"
|
|
179
|
+
try:
|
|
180
|
+
# Validate both files once before scanning so malformed policy cannot
|
|
181
|
+
# silently turn into a successful but incomplete report.
|
|
182
|
+
heuristics.load_risk_patterns(str(risk_patterns_path))
|
|
183
|
+
deps.load_approved_packages(str(approved_packages_path))
|
|
184
|
+
except ConfigError as exc:
|
|
185
|
+
logging.error(str(exc))
|
|
186
|
+
raise typer.Exit(code=2)
|
|
187
|
+
|
|
188
|
+
# --- 2. Resolve Package Path and Info ---
|
|
189
|
+
package_info = _get_package_path_and_info(package_target)
|
|
190
|
+
if not package_info:
|
|
191
|
+
logging.error("Failed to resolve package target. Exiting.")
|
|
192
|
+
raise typer.Exit(code=1)
|
|
193
|
+
package_dir, package_name, package_version = package_info
|
|
194
|
+
logging.info(f"Resolved package: Name='{package_name}', Version='{package_version}', Path='{package_dir}'")
|
|
195
|
+
|
|
196
|
+
# --- 3. Run Scanners ---
|
|
197
|
+
all_findings: List[Dict[str, Any]] = []
|
|
198
|
+
|
|
199
|
+
# 3a. Install Script Analysis (setup.py, pyproject.toml)
|
|
200
|
+
logging.info("Running install script analysis...")
|
|
201
|
+
try:
|
|
202
|
+
all_findings.extend(install_script_analyzer.scan_install_scripts(str(package_dir)))
|
|
203
|
+
except Exception as e:
|
|
204
|
+
logging.error(f"Error during install script analysis: {e}", exp_info=True)
|
|
205
|
+
|
|
206
|
+
# 3b. Dependency Analysis
|
|
207
|
+
logging.info("Running dependency analysis...")
|
|
208
|
+
try:
|
|
209
|
+
dep_findings = deps.scan_dependencies(package_name, str(approved_packages_path))
|
|
210
|
+
all_findings.extend(dep_findings)
|
|
211
|
+
except Exception as e:
|
|
212
|
+
logging.error(f"Error during dependency analysis: {e}", exp_info=True)
|
|
213
|
+
|
|
214
|
+
# 3c. Source Code Analysis (AST and Heuristics)
|
|
215
|
+
logging.info("Running source code analysis (AST & Heuristics)...")
|
|
216
|
+
python_files = _find_python_files(package_dir, include_tests=include_tests)
|
|
217
|
+
if not python_files:
|
|
218
|
+
logging.warning(f"No Python files found in {package_dir} to scan.")
|
|
219
|
+
|
|
220
|
+
for py_file in python_files:
|
|
221
|
+
try:
|
|
222
|
+
logging.debug(f"Scanning file: {py_file}")
|
|
223
|
+
all_findings.extend(ast_scanner.scan_file_ast(str(py_file)))
|
|
224
|
+
all_findings.extend(heuristics.scan_file_heuristics(str(py_file), str(risk_patterns_path)))
|
|
225
|
+
except Exception as e:
|
|
226
|
+
logging.error(f"Error scanning file {py_file}: {e}", exp_info=True)
|
|
227
|
+
|
|
228
|
+
# --- 4. Process Results ---
|
|
229
|
+
logging.info("Processing scan results...")
|
|
230
|
+
|
|
231
|
+
original_count = len(all_findings)
|
|
232
|
+
|
|
233
|
+
# IMPORTANT: Overall risk & full summary are always computed from *all* findings.
|
|
234
|
+
# Severity filtering only affects which findings appear in the detailed report.
|
|
235
|
+
# This prevents `-s HIGH` on a MEDIUM-only package from incorrectly reporting risk "INFO".
|
|
236
|
+
full_summary = _calculate_summary(all_findings)
|
|
237
|
+
overall_risk_level = _determine_overall_risk(full_summary)
|
|
238
|
+
logging.info(f"Overall risk level (based on all findings): {overall_risk_level}")
|
|
239
|
+
|
|
240
|
+
filtered_findings = _filter_findings_by_severity(all_findings, severity.upper())
|
|
241
|
+
filtered_count = len(filtered_findings)
|
|
242
|
+
logging.info(f"Total findings: {original_count}. Shown after severity filter (>= {severity.upper()}): {filtered_count}")
|
|
243
|
+
|
|
244
|
+
# Summary shown in the report reflects the *filtered* set so the table matches the listed findings.
|
|
245
|
+
# The overall_risk_level still reflects the true highest severity present.
|
|
246
|
+
report_summary = _calculate_summary(filtered_findings)
|
|
247
|
+
|
|
248
|
+
explanation = explainer.generate_overall_explanation(
|
|
249
|
+
all_findings, full_summary, package_name, overall_risk_level
|
|
250
|
+
)
|
|
251
|
+
|
|
252
|
+
# --- 5. Format Output ---
|
|
253
|
+
output_content = ""
|
|
254
|
+
if format.lower() == "json":
|
|
255
|
+
logging.info("Formatting report as JSON...")
|
|
256
|
+
output_content = json_formatter.format_report_json(
|
|
257
|
+
package_name=package_name,
|
|
258
|
+
package_version=package_version,
|
|
259
|
+
findings=filtered_findings,
|
|
260
|
+
summary=report_summary,
|
|
261
|
+
overall_risk_level=overall_risk_level,
|
|
262
|
+
explanation=explanation,
|
|
263
|
+
full_summary=full_summary,
|
|
264
|
+
)
|
|
265
|
+
elif format.lower() == "md":
|
|
266
|
+
logging.info("Formatting report as Markdown...")
|
|
267
|
+
output_content = markdown_formatter.format_report_markdown(
|
|
268
|
+
package_name=package_name,
|
|
269
|
+
package_version=package_version,
|
|
270
|
+
findings=filtered_findings,
|
|
271
|
+
summary=report_summary,
|
|
272
|
+
overall_risk_level=overall_risk_level,
|
|
273
|
+
explanation=explanation,
|
|
274
|
+
full_summary=full_summary,
|
|
275
|
+
)
|
|
276
|
+
else:
|
|
277
|
+
logging.error(f"Invalid output format specified: '{format}'. Use 'json' or 'md'.")
|
|
278
|
+
raise typer.Exit(code=1)
|
|
279
|
+
|
|
280
|
+
# --- 6. Output Report ---
|
|
281
|
+
if output:
|
|
282
|
+
try:
|
|
283
|
+
output.parent.mkdir(parents=True, exist_ok=True)
|
|
284
|
+
with open(output, 'w', encoding='utf-8') as f:
|
|
285
|
+
f.write(output_content)
|
|
286
|
+
logging.info(f"Report saved to: {output}")
|
|
287
|
+
except Exception as e:
|
|
288
|
+
logging.error(f"Failed to write report to file {output}: {e}")
|
|
289
|
+
raise typer.Exit(code=1)
|
|
290
|
+
else:
|
|
291
|
+
typer.echo(output_content)
|
|
292
|
+
|
|
293
|
+
if sbom:
|
|
294
|
+
try:
|
|
295
|
+
requirements = deps.get_package_dependencies(package_name) or []
|
|
296
|
+
sbom.parent.mkdir(parents=True, exist_ok=True)
|
|
297
|
+
sbom.write_text(json.dumps(deps.build_sbom(package_name, package_version, requirements), indent=2), encoding="utf-8")
|
|
298
|
+
logging.info(f"SBOM saved to: {sbom}")
|
|
299
|
+
except Exception as exc:
|
|
300
|
+
logging.error(f"Failed to write SBOM to {sbom}: {exc}")
|
|
301
|
+
raise typer.Exit(code=1)
|
|
302
|
+
|
|
303
|
+
# Clean up any temporary directories created during package resolution
|
|
304
|
+
_cleanup_temp_dir(package_dir)
|
|
305
|
+
|
|
306
|
+
logging.info("SherlockScan finished.")
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
# --- Main Execution Guard ---
|
|
310
|
+
if __name__ == "__main__":
|
|
311
|
+
# Convenience for direct execution during development
|
|
312
|
+
if not Path("./config").exists():
|
|
313
|
+
Path("./config").mkdir()
|
|
314
|
+
if not Path("./config/risk_patterns.yaml").exists():
|
|
315
|
+
Path("./config/risk_patterns.yaml").touch()
|
|
316
|
+
if not Path("./config/approved_packages.yaml").exists():
|
|
317
|
+
Path("./config/approved_packages.yaml").touch()
|
|
318
|
+
|
|
319
|
+
app()
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
#!/usr/bin/env python
|
|
2
|
+
# coding: utf-8
|
|
3
|
+
|
|
4
|
+
# In[ ]:
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
# sherlockscan/config/__init__.py
|
|
8
|
+
|
|
9
|
+
import logging
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
import importlib.resources as pkg_resources
|
|
12
|
+
# Use 'importlib.resources' for Python 3.7+
|
|
13
|
+
# For older versions, 'pkg_resources' from setuptools was used, but it's legacy.
|
|
14
|
+
|
|
15
|
+
# Configure logger for this module if needed, or rely on package logger
|
|
16
|
+
logger = logging.getLogger(__name__)
|
|
17
|
+
|
|
18
|
+
# Define constants for default config filenames
|
|
19
|
+
DEFAULT_RISK_PATTERNS_FILE = "risk_patterns.yaml"
|
|
20
|
+
DEFAULT_APPROVED_PACKAGES_FILE = "approved_packages.yaml"
|
|
21
|
+
|
|
22
|
+
def get_default_config_path(filename: str) -> Path:
|
|
23
|
+
"""
|
|
24
|
+
Gets the path to a default configuration file packaged within the library.
|
|
25
|
+
|
|
26
|
+
Uses importlib.resources to reliably find the file path even when the
|
|
27
|
+
package is installed (e.g., in site-packages).
|
|
28
|
+
|
|
29
|
+
Args:
|
|
30
|
+
filename: The name of the configuration file (e.g., "risk_patterns.yaml").
|
|
31
|
+
|
|
32
|
+
Returns:
|
|
33
|
+
A pathlib.Path object pointing to the default configuration file.
|
|
34
|
+
|
|
35
|
+
Raises:
|
|
36
|
+
FileNotFoundError: If the specified default file cannot be found within the package.
|
|
37
|
+
TypeError: If importlib.resources is unavailable (should not happen on Py >= 3.7).
|
|
38
|
+
"""
|
|
39
|
+
try:
|
|
40
|
+
# 'files()' returns a Traversable resource reader for the package
|
|
41
|
+
# Available Python 3.9+ (preferred).
|
|
42
|
+
# For 3.7, 3.8 use legacy 'path()' with context manager if needed,
|
|
43
|
+
# but 'files()' is generally compatible via backports if installed.
|
|
44
|
+
resource_path = pkg_resources.files('sherlockscan.config').joinpath(filename)
|
|
45
|
+
|
|
46
|
+
# Verify the resource actually exists as a file within the package data
|
|
47
|
+
# Note: resource_path might be a path inside a zip archive if installed from wheel
|
|
48
|
+
if resource_path.is_file():
|
|
49
|
+
logger.debug(f"Found default config file: {resource_path}")
|
|
50
|
+
return Path(str(resource_path)) # Ensure it's a Path object
|
|
51
|
+
else:
|
|
52
|
+
# This case might occur if the file wasn't included in MANIFEST.in
|
|
53
|
+
# or if the package structure is unexpected.
|
|
54
|
+
logger.error(f"Default config file '{filename}' not found within the package resources at expected location.")
|
|
55
|
+
raise FileNotFoundError(f"Default config file '{filename}' not found in package data.")
|
|
56
|
+
|
|
57
|
+
except (AttributeError, TypeError, ModuleNotFoundError) as e:
|
|
58
|
+
# Handle cases where importlib.resources might not be fully available
|
|
59
|
+
# or the package structure is broken. Should be rare on supported Python versions.
|
|
60
|
+
logger.exception(f"Could not access package resources using importlib.resources: {e}")
|
|
61
|
+
raise TypeError("Could not access package resources. Ensure Python >= 3.7 and package is installed correctly.") from e
|
|
62
|
+
except Exception as e:
|
|
63
|
+
logger.exception(f"An unexpected error occurred finding default config '{filename}': {e}")
|
|
64
|
+
# Re-raise FileNotFoundError for consistency if the file wasn't located
|
|
65
|
+
raise FileNotFoundError(f"Could not determine path for default config file '{filename}'.") from e
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def get_default_risk_patterns_path() -> Path:
|
|
69
|
+
"""Gets the path to the default risk_patterns.yaml file."""
|
|
70
|
+
return get_default_config_path(DEFAULT_RISK_PATTERNS_FILE)
|
|
71
|
+
|
|
72
|
+
def get_default_approved_packages_path() -> Path:
|
|
73
|
+
"""Gets the path to the default approved_packages.yaml file."""
|
|
74
|
+
return get_default_config_path(DEFAULT_APPROVED_PACKAGES_FILE)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
# Define what 'from sherlockscan.config import *' would import.
|
|
78
|
+
__all__ = [
|
|
79
|
+
"get_default_risk_patterns_path",
|
|
80
|
+
"get_default_approved_packages_path",
|
|
81
|
+
"DEFAULT_RISK_PATTERNS_FILE",
|
|
82
|
+
"DEFAULT_APPROVED_PACKAGES_FILE"
|
|
83
|
+
]
|
|
84
|
+
|
|
85
|
+
# Example usage (for understanding, not typically run directly)
|
|
86
|
+
# if __name__ == '__main__':
|
|
87
|
+
# try:
|
|
88
|
+
# patterns_path = get_default_risk_patterns_path()
|
|
89
|
+
# print(f"Default risk patterns path: {patterns_path}")
|
|
90
|
+
# print(f"Exists: {patterns_path.exists()}") # Note: exists() might not work correctly if inside a zip file
|
|
91
|
+
# print(f"Is file: {patterns_path.is_file()}")
|
|
92
|
+
#
|
|
93
|
+
# approved_path = get_default_approved_packages_path()
|
|
94
|
+
# print(f"Default approved packages path: {approved_path}")
|
|
95
|
+
# print(f"Exists: {approved_path.exists()}")
|
|
96
|
+
# print(f"Is file: {approved_path.is_file()}")
|
|
97
|
+
#
|
|
98
|
+
# except Exception as e:
|
|
99
|
+
# print(f"Error getting default config paths: {e}")
|
|
100
|
+
|
|
101
|
+
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
# sherlockscan/config/approved_packages.yaml
|
|
2
|
+
#
|
|
3
|
+
# Optional configuration file to define allowed and blocked package dependencies.
|
|
4
|
+
# The `deps.py` scanner uses these lists to check the direct dependencies
|
|
5
|
+
# of the package being scanned.
|
|
6
|
+
#
|
|
7
|
+
# Package names are case-insensitive and underscores/dashes are normalized
|
|
8
|
+
# by the scanner before comparison (e.g., "scikit-learn" matches "scikit_learn").
|
|
9
|
+
|
|
10
|
+
# An allowlist is only enforced when enforce_allowlist is true. Keeping it
|
|
11
|
+
# disabled by default prevents a general-purpose scan from reporting every
|
|
12
|
+
# package outside this DS/ML-focused policy as a security issue.
|
|
13
|
+
enforce_allowlist: false
|
|
14
|
+
|
|
15
|
+
# Only include packages explicitly vetted and approved for use when policy
|
|
16
|
+
# enforcement is enabled.
|
|
17
|
+
allowlist:
|
|
18
|
+
# --- Core Data Science / ML ---
|
|
19
|
+
- numpy
|
|
20
|
+
- pandas
|
|
21
|
+
- scikit-learn
|
|
22
|
+
- scipy
|
|
23
|
+
- matplotlib
|
|
24
|
+
- seaborn
|
|
25
|
+
- statsmodels
|
|
26
|
+
|
|
27
|
+
# --- Deep Learning Frameworks ---
|
|
28
|
+
- tensorflow # Or specific variant like tensorflow-cpu
|
|
29
|
+
- keras
|
|
30
|
+
- torch # PyTorch
|
|
31
|
+
- torchvision
|
|
32
|
+
- torchaudio
|
|
33
|
+
- jax # Often used in DL research
|
|
34
|
+
|
|
35
|
+
# --- Gradient Boosting ---
|
|
36
|
+
- xgboost
|
|
37
|
+
- lightgbm
|
|
38
|
+
- catboost
|
|
39
|
+
|
|
40
|
+
# --- NLP ---
|
|
41
|
+
- nltk
|
|
42
|
+
- spacy
|
|
43
|
+
|
|
44
|
+
# --- Computer Vision ---
|
|
45
|
+
- opencv-python # Common distribution for OpenCV
|
|
46
|
+
- opencv-python-headless
|
|
47
|
+
- pillow # PIL fork
|
|
48
|
+
|
|
49
|
+
# --- Hugging Face Ecosystem ---
|
|
50
|
+
- transformers
|
|
51
|
+
- datasets
|
|
52
|
+
- tokenizers
|
|
53
|
+
- accelerate
|
|
54
|
+
|
|
55
|
+
# --- LLM Frameworks & SDKs ---
|
|
56
|
+
- openai
|
|
57
|
+
- langchain
|
|
58
|
+
- langchain-core
|
|
59
|
+
- langchain-community # Add specific langchain integrations as needed
|
|
60
|
+
- llama-index
|
|
61
|
+
- llama-parse
|
|
62
|
+
|
|
63
|
+
# --- Agentic Frameworks ---
|
|
64
|
+
- pyautogen # Microsoft AutoGen
|
|
65
|
+
|
|
66
|
+
# --- MLOps / LLMOps / Experiment Tracking ---
|
|
67
|
+
- mlflow # MLflow Tracking, Models, Projects, etc.
|
|
68
|
+
- dvc # Data Version Control
|
|
69
|
+
- dvc-gdrive # DVC extensions as needed
|
|
70
|
+
- dvc-s3
|
|
71
|
+
- great-expectations # Data validation
|
|
72
|
+
- bentoml # Model Serving
|
|
73
|
+
- wandb # Weights & Biases
|
|
74
|
+
|
|
75
|
+
# --- DevOps / Infrastructure ---
|
|
76
|
+
- docker # Docker SDK for Python
|
|
77
|
+
- kubernetes # Kubernetes Python client
|
|
78
|
+
# - ansible # Less common as direct Python script dependency
|
|
79
|
+
# - python-terraform # Less common as direct Python script dependency
|
|
80
|
+
|
|
81
|
+
# --- Cloud SDKs (Examples - Add specific needed services) ---
|
|
82
|
+
- boto3 # AWS SDK
|
|
83
|
+
- google-api-python-client
|
|
84
|
+
- google-cloud-aiplatform
|
|
85
|
+
- google-cloud-storage
|
|
86
|
+
- google-cloud-bigquery
|
|
87
|
+
# - azure-identity # Add specific Azure SDK components as needed
|
|
88
|
+
# - azure-storage-blob
|
|
89
|
+
|
|
90
|
+
# --- Common Utilities & Infrastructure ---
|
|
91
|
+
- requests
|
|
92
|
+
- pyyaml # Used by sherlockscan itself
|
|
93
|
+
- packaging # Used by sherlockscan itself
|
|
94
|
+
- toml # Used by sherlockscan itself
|
|
95
|
+
- python-dateutil
|
|
96
|
+
- pytz
|
|
97
|
+
- tqdm # Progress bars
|
|
98
|
+
- python-dotenv # Environment variables
|
|
99
|
+
- fastapi # Web framework
|
|
100
|
+
- uvicorn # ASGI server
|
|
101
|
+
- flask # Web framework
|
|
102
|
+
- celery # Task queue
|
|
103
|
+
- redis # Often used with Celery/Caching
|
|
104
|
+
- joblib # Parallel processing, used by scikit-learn
|
|
105
|
+
|
|
106
|
+
# Add other vetted and approved packages here...
|
|
107
|
+
# - my-internal-approved-lib
|
|
108
|
+
|
|
109
|
+
# Blocklist: Any direct dependency found in this list will be flagged
|
|
110
|
+
# as "Blocked Dependency" with high/critical severity.
|
|
111
|
+
blocklist:
|
|
112
|
+
- malicious-package # Example of a known bad package
|
|
113
|
+
- insecure-lib-v1 # Example of an outdated/vulnerable library to block
|
|
114
|
+
- typo-squatting-pkg # Example of a potential typosquatting attempt
|
|
115
|
+
# Add any packages explicitly forbidden by policy
|
|
116
|
+
# - forbidden-tool
|