quantum-scan 0.1.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.
- quantum_scan/__init__.py +3 -0
- quantum_scan/__main__.py +6 -0
- quantum_scan/accepted.py +202 -0
- quantum_scan/cli.py +313 -0
- quantum_scan/engine/__init__.py +1 -0
- quantum_scan/engine/callsite.py +64 -0
- quantum_scan/engine/javascript.py +912 -0
- quantum_scan/engine/matcher.py +393 -0
- quantum_scan/engine/python.py +807 -0
- quantum_scan/mcp_server.py +128 -0
- quantum_scan/models.py +158 -0
- quantum_scan/py.typed +0 -0
- quantum_scan/redact.py +183 -0
- quantum_scan/reporters/__init__.py +1 -0
- quantum_scan/reporters/html.py +264 -0
- quantum_scan/reporters/templates/report.html.j2 +177 -0
- quantum_scan/reporters/terminal.py +291 -0
- quantum_scan/rule.py +131 -0
- quantum_scan/rule_loader.py +543 -0
- quantum_scan/rules/README.md +6 -0
- quantum_scan/rules/any/committed-private-key.yaml +35 -0
- quantum_scan/rules/javascript/jose-asymmetric-sign.yaml +51 -0
- quantum_scan/rules/javascript/jsonwebtoken-asymmetric-sign.yaml +49 -0
- quantum_scan/rules/javascript/node-crypto-ec.yaml +52 -0
- quantum_scan/rules/javascript/node-crypto-rsa-keygen.yaml +57 -0
- quantum_scan/rules/python/cryptography-ec-keygen.yaml +52 -0
- quantum_scan/rules/python/cryptography-rsa-keygen.yaml +57 -0
- quantum_scan/rules/python/paramiko-keygen.yaml +42 -0
- quantum_scan/rules/python/pycryptodome-rsa-keygen.yaml +46 -0
- quantum_scan/rules/python/pyjwt-asymmetric-sign.yaml +57 -0
- quantum_scan/scan.py +91 -0
- quantum_scan/scanners/__init__.py +1 -0
- quantum_scan/scanners/base.py +31 -0
- quantum_scan/scanners/code.py +416 -0
- quantum_scan/scanners/keyfile.py +93 -0
- quantum_scan/scope.py +4 -0
- quantum_scan/scoring.py +158 -0
- quantum_scan/walker.py +326 -0
- quantum_scan-0.1.0.dist-info/METADATA +128 -0
- quantum_scan-0.1.0.dist-info/RECORD +43 -0
- quantum_scan-0.1.0.dist-info/WHEEL +4 -0
- quantum_scan-0.1.0.dist-info/entry_points.txt +2 -0
- quantum_scan-0.1.0.dist-info/licenses/LICENSE +202 -0
quantum_scan/__init__.py
ADDED
quantum_scan/__main__.py
ADDED
quantum_scan/accepted.py
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
"""Accepted risk (ADR 0004): inline comments, `.quantum-scan-ignore`, and baselines.
|
|
2
|
+
|
|
3
|
+
Accepted findings are kept and reported; they never count toward the score or --fail-on.
|
|
4
|
+
Precedence: inline > ignore-file > baseline.
|
|
5
|
+
|
|
6
|
+
Baselines are relative to the scan root: fingerprints include the path relative to the root
|
|
7
|
+
that was scanned, so write and use a baseline from the same root. Fingerprints are stable
|
|
8
|
+
across line shifts and secret rotation but change when a call is renamed or moved to
|
|
9
|
+
another file.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import contextlib
|
|
15
|
+
import json
|
|
16
|
+
import os
|
|
17
|
+
import re
|
|
18
|
+
import stat
|
|
19
|
+
import tempfile
|
|
20
|
+
from collections.abc import Iterable, Sequence
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
from typing import Any
|
|
23
|
+
|
|
24
|
+
from quantum_scan.models import Finding
|
|
25
|
+
from quantum_scan.walker import read_bounded
|
|
26
|
+
|
|
27
|
+
BASELINE_VERSION = 1
|
|
28
|
+
MAX_BASELINE_BYTES = 10_000_000
|
|
29
|
+
MAX_BASELINE_ENTRIES = 1_000_000
|
|
30
|
+
_FINGERPRINT_RE = re.compile(r"[0-9a-f]{32}")
|
|
31
|
+
_INLINE_RE = re.compile(r"quantum-scan:\s*ignore(?:\[([^\]]*)\])?")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class BaselineError(Exception):
|
|
35
|
+
"""The baseline file cannot be used. The message says what to do."""
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
_DIRECTIVE_RE = re.compile(r"quantum-scan:\s*ignore(?![\w-])(?:\[([^\]]*)\])?")
|
|
39
|
+
_COMMENT_LEADERS = ("#", "//", "/*", "*")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _comment_part(line: str) -> str | None:
|
|
43
|
+
"""The comment text of `line` (after a comment leader that is outside any string)."""
|
|
44
|
+
stripped = line.lstrip()
|
|
45
|
+
if stripped.startswith("*"):
|
|
46
|
+
return stripped[1:]
|
|
47
|
+
quote = ""
|
|
48
|
+
i, n = 0, len(line)
|
|
49
|
+
while i < n:
|
|
50
|
+
ch = line[i]
|
|
51
|
+
if quote:
|
|
52
|
+
if ch == "\\":
|
|
53
|
+
i += 1
|
|
54
|
+
elif ch == quote:
|
|
55
|
+
quote = ""
|
|
56
|
+
elif ch in "\"'`":
|
|
57
|
+
quote = ch
|
|
58
|
+
elif ch == "#":
|
|
59
|
+
return line[i + 1 :]
|
|
60
|
+
elif line.startswith(("//", "/*"), i):
|
|
61
|
+
return line[i + 2 :]
|
|
62
|
+
i += 1
|
|
63
|
+
return None
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def inline_directives(
|
|
67
|
+
lines: Sequence[str], start: int, end: int | None = None
|
|
68
|
+
) -> list[tuple[int, frozenset[str] | None]]:
|
|
69
|
+
"""`quantum-scan: ignore[...]` comments relevant to a finding spanning `start..end`.
|
|
70
|
+
|
|
71
|
+
Looks at every line of the span, and at the line above only if it is a comment-only
|
|
72
|
+
line. Returns (line number, ids); ids None means "all rules", `ignore[]` is an empty set.
|
|
73
|
+
The marker must sit in a real comment (after `#`, `//`, `/*` or a leading `*`), so a
|
|
74
|
+
marker inside a string literal is ignored; `ignored` / `ignore-me` do not count.
|
|
75
|
+
"""
|
|
76
|
+
found: list[tuple[int, frozenset[str] | None]] = []
|
|
77
|
+
last = max(end if end is not None else start, start)
|
|
78
|
+
for number in range(start - 1, last + 1):
|
|
79
|
+
if not 1 <= number <= len(lines):
|
|
80
|
+
continue
|
|
81
|
+
text = lines[number - 1]
|
|
82
|
+
if number == start - 1 and not text.lstrip().startswith(_COMMENT_LEADERS):
|
|
83
|
+
continue
|
|
84
|
+
comment = _comment_part(text)
|
|
85
|
+
if comment is None:
|
|
86
|
+
continue
|
|
87
|
+
for match in _DIRECTIVE_RE.finditer(comment):
|
|
88
|
+
listed = match.group(1)
|
|
89
|
+
if listed is None:
|
|
90
|
+
found.append((number, None))
|
|
91
|
+
else:
|
|
92
|
+
ids = {part.strip() for part in listed.split(",") if part.strip()}
|
|
93
|
+
found.append((number, frozenset(ids)))
|
|
94
|
+
return found
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def directive_covers(directives: Sequence[tuple[int, frozenset[str] | None]], rule_id: str) -> bool:
|
|
98
|
+
return any(ids is None or rule_id in ids for _, ids in directives)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def inline_suppressed(
|
|
102
|
+
lines: Sequence[str], line: int, rule_id: str, end_line: int | None = None
|
|
103
|
+
) -> bool:
|
|
104
|
+
"""True if a directive on the finding's lines (or a comment line above) covers `rule_id`."""
|
|
105
|
+
return directive_covers(inline_directives(lines, line, end_line), rule_id)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def apply_ignore_and_baseline(
|
|
109
|
+
findings: Iterable[Finding], ignore_spec: Any | None, baseline: set[str] | None
|
|
110
|
+
) -> None:
|
|
111
|
+
"""Mark findings accepted in place; never overrides an earlier (higher-precedence) reason."""
|
|
112
|
+
for finding in findings:
|
|
113
|
+
if finding.accepted is not None:
|
|
114
|
+
continue
|
|
115
|
+
if ignore_spec is not None and ignore_spec.match_file(finding.location.path):
|
|
116
|
+
finding.accepted = "ignore-file"
|
|
117
|
+
elif baseline and finding.fingerprint in baseline:
|
|
118
|
+
finding.accepted = "baseline"
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def write_baseline(path: Path, findings: Iterable[Finding]) -> None:
|
|
122
|
+
"""Write ALL given findings (active and accepted) as a baseline.
|
|
123
|
+
|
|
124
|
+
Refuses symlinks and non-regular targets; writes atomically (temp file + replace).
|
|
125
|
+
"""
|
|
126
|
+
hint = "Choose a normal file path, e.g. `quantum-scan --write-baseline baseline.json`."
|
|
127
|
+
try:
|
|
128
|
+
mode = os.lstat(path).st_mode
|
|
129
|
+
except FileNotFoundError:
|
|
130
|
+
mode = None
|
|
131
|
+
except OSError as exc:
|
|
132
|
+
raise BaselineError(f"Cannot write baseline {path} ({exc}). {hint}") from exc
|
|
133
|
+
if mode is not None and (stat.S_ISLNK(mode) or not stat.S_ISREG(mode)):
|
|
134
|
+
raise BaselineError(
|
|
135
|
+
f"Refusing to write baseline {path}: it is a symlink or not a regular file. {hint}"
|
|
136
|
+
)
|
|
137
|
+
entries = sorted(
|
|
138
|
+
(
|
|
139
|
+
{"fingerprint": f.fingerprint, "rule_id": f.rule_id, "path": f.location.path}
|
|
140
|
+
for f in findings
|
|
141
|
+
),
|
|
142
|
+
key=lambda e: (e["path"], e["rule_id"], e["fingerprint"]),
|
|
143
|
+
)
|
|
144
|
+
payload = {"version": BASELINE_VERSION, "tool": "quantum-scan", "findings": entries}
|
|
145
|
+
try:
|
|
146
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
147
|
+
fd, tmp_name = tempfile.mkstemp(dir=path.parent, prefix=".baseline-", suffix=".tmp")
|
|
148
|
+
except OSError as exc:
|
|
149
|
+
raise BaselineError(f"Cannot write baseline {path} ({exc}). {hint}") from exc
|
|
150
|
+
try:
|
|
151
|
+
with os.fdopen(fd, "w", encoding="utf-8") as handle:
|
|
152
|
+
handle.write(json.dumps(payload, indent=2) + "\n")
|
|
153
|
+
os.chmod(tmp_name, 0o644)
|
|
154
|
+
os.replace(tmp_name, path)
|
|
155
|
+
except OSError as exc:
|
|
156
|
+
with contextlib.suppress(OSError):
|
|
157
|
+
os.unlink(tmp_name)
|
|
158
|
+
raise BaselineError(f"Cannot write baseline {path} ({exc}). {hint}") from exc
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def load_baseline(path: Path) -> set[str]:
|
|
162
|
+
"""Fingerprints in a baseline file; `BaselineError` (with a fix) if unusable."""
|
|
163
|
+
hint = f"Fix the JSON, or regenerate it with `quantum-scan --write-baseline {path}`."
|
|
164
|
+
try:
|
|
165
|
+
raw = read_bounded(path, MAX_BASELINE_BYTES)
|
|
166
|
+
except FileNotFoundError:
|
|
167
|
+
raise BaselineError(
|
|
168
|
+
f"Baseline file not found: {path}. Create one with "
|
|
169
|
+
f"`quantum-scan --write-baseline {path}`."
|
|
170
|
+
) from None
|
|
171
|
+
except OSError as exc:
|
|
172
|
+
raise BaselineError(f"Cannot read baseline file {path} ({exc}). {hint}") from exc
|
|
173
|
+
try:
|
|
174
|
+
data = json.loads(raw.decode("utf-8-sig"))
|
|
175
|
+
except (ValueError, RecursionError) as exc: # JSONDecodeError and UnicodeDecodeError
|
|
176
|
+
raise BaselineError(f"Baseline file {path} is not valid JSON. {hint}") from exc
|
|
177
|
+
if (
|
|
178
|
+
not isinstance(data, dict)
|
|
179
|
+
or type(data.get("version")) is not int
|
|
180
|
+
or data["version"] != BASELINE_VERSION
|
|
181
|
+
):
|
|
182
|
+
got = data.get("version") if isinstance(data, dict) else None
|
|
183
|
+
raise BaselineError(
|
|
184
|
+
f"Baseline file {path} has unsupported version {got!r} "
|
|
185
|
+
f"(expected {BASELINE_VERSION}). {hint}"
|
|
186
|
+
)
|
|
187
|
+
entries = data.get("findings")
|
|
188
|
+
if not isinstance(entries, list):
|
|
189
|
+
raise BaselineError(f"Baseline file {path} has no `findings` list. {hint}")
|
|
190
|
+
if len(entries) > MAX_BASELINE_ENTRIES:
|
|
191
|
+
raise BaselineError(
|
|
192
|
+
f"Baseline file {path} has more than {MAX_BASELINE_ENTRIES} entries. {hint}"
|
|
193
|
+
)
|
|
194
|
+
fingerprints: set[str] = set()
|
|
195
|
+
for entry in entries:
|
|
196
|
+
fp = entry.get("fingerprint") if isinstance(entry, dict) else None
|
|
197
|
+
if not isinstance(fp, str) or not _FINGERPRINT_RE.fullmatch(fp):
|
|
198
|
+
raise BaselineError(
|
|
199
|
+
f"Baseline file {path} has an entry without a valid fingerprint. {hint}"
|
|
200
|
+
)
|
|
201
|
+
fingerprints.add(fp)
|
|
202
|
+
return fingerprints
|
quantum_scan/cli.py
ADDED
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
"""Command line interface. `quantum-scan` with no arguments scans the current folder."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import contextlib
|
|
6
|
+
import difflib
|
|
7
|
+
import os
|
|
8
|
+
import tempfile
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
import typer
|
|
13
|
+
from rich.console import Console
|
|
14
|
+
from rich.markup import escape
|
|
15
|
+
from rich.progress import BarColumn, Progress, ProgressColumn, SpinnerColumn, Task, TextColumn
|
|
16
|
+
from rich.text import Text
|
|
17
|
+
from typer.core import TyperGroup
|
|
18
|
+
|
|
19
|
+
from quantum_scan import __version__
|
|
20
|
+
from quantum_scan.accepted import BaselineError, write_baseline
|
|
21
|
+
from quantum_scan.models import ScanResult, Severity
|
|
22
|
+
from quantum_scan.reporters.html import render_html
|
|
23
|
+
from quantum_scan.reporters.terminal import make_console, render_terminal
|
|
24
|
+
from quantum_scan.rule_loader import RuleError, load_rules
|
|
25
|
+
from quantum_scan.scan import run_scan
|
|
26
|
+
from quantum_scan.walker import ScanPathError
|
|
27
|
+
|
|
28
|
+
DEFAULT_OUT = "quantum-scan-report"
|
|
29
|
+
BIG_REPO_FILES = 500
|
|
30
|
+
EXIT_OK, EXIT_FINDINGS, EXIT_ERROR, EXIT_CANCELLED = 0, 1, 2, 130
|
|
31
|
+
_FORMATS = ("html", "md", "cbom", "sarif")
|
|
32
|
+
_COMMANDS = {"scan", "explain", "init", "fix", "mcp"}
|
|
33
|
+
|
|
34
|
+
_EPILOG = """\b
|
|
35
|
+
Examples:
|
|
36
|
+
quantum-scan scan this folder, write the report
|
|
37
|
+
quantum-scan scan src --fail-on high fail CI on new high-risk findings
|
|
38
|
+
quantum-scan explain py.cryptography.rsa-keygen
|
|
39
|
+
|
|
40
|
+
More options: quantum-scan scan --help
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
_FAIL_ON = ("critical", "high", "medium", "low")
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class _DefaultScanGroup(TyperGroup):
|
|
48
|
+
"""Treat `quantum-scan [args]` as `quantum-scan scan [args]` unless a command is named."""
|
|
49
|
+
|
|
50
|
+
def parse_args(self, ctx: Any, args: list[str]) -> list[str]:
|
|
51
|
+
if not args:
|
|
52
|
+
args = ["scan"]
|
|
53
|
+
elif args[0] not in _COMMANDS and args[0] not in ("--help", "-h", "--version"):
|
|
54
|
+
args = ["scan", *args]
|
|
55
|
+
return super().parse_args(ctx, args)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
app = typer.Typer(
|
|
59
|
+
cls=_DefaultScanGroup,
|
|
60
|
+
help="Find quantum-vulnerable encryption (RSA, ECC, DH) in your code. Free, offline, no setup.",
|
|
61
|
+
epilog=_EPILOG,
|
|
62
|
+
rich_markup_mode=None,
|
|
63
|
+
add_completion=False,
|
|
64
|
+
context_settings={"help_option_names": ["-h", "--help"]},
|
|
65
|
+
no_args_is_help=False,
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _version(value: bool) -> None:
|
|
70
|
+
if value:
|
|
71
|
+
typer.echo(f"quantum-scan {__version__}")
|
|
72
|
+
raise typer.Exit()
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
@app.callback()
|
|
76
|
+
def _root(
|
|
77
|
+
version: bool = typer.Option(
|
|
78
|
+
False, "--version", callback=_version, is_eager=True, help="Show the version and exit."
|
|
79
|
+
),
|
|
80
|
+
) -> None:
|
|
81
|
+
pass
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _fail(message: str, todo: str) -> typer.Exit:
|
|
85
|
+
"""Print a one-line error plus what to do; return the Exit to raise."""
|
|
86
|
+
err = Console(stderr=True, no_color=bool(os.environ.get("NO_COLOR")))
|
|
87
|
+
err.print(f"[bold red]Error:[/] {escape(message)}", soft_wrap=True)
|
|
88
|
+
err.print(f"[bold]What to do:[/] {escape(todo)}", soft_wrap=True)
|
|
89
|
+
return typer.Exit(EXIT_ERROR)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _split_error(exc: Exception, default_todo: str) -> typer.Exit:
|
|
93
|
+
"""Errors carry 'problem. fix' text: show the first sentence, then the rest as the fix."""
|
|
94
|
+
text = " ".join(str(exc).split()) if "\n" not in str(exc) else str(exc)
|
|
95
|
+
head, sep, tail = text.partition(". ")
|
|
96
|
+
if sep and "\n" not in text:
|
|
97
|
+
return _fail(head + ".", tail)
|
|
98
|
+
return _fail(text, default_todo)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _parse_formats(raw: str) -> list[str]:
|
|
102
|
+
wanted: list[str] = []
|
|
103
|
+
for part in raw.lower().replace(" ", "").split(","):
|
|
104
|
+
if part == "all":
|
|
105
|
+
wanted.extend(_FORMATS)
|
|
106
|
+
elif part in _FORMATS:
|
|
107
|
+
wanted.append(part)
|
|
108
|
+
elif part:
|
|
109
|
+
raise _fail(f"Unknown format '{part}'.", "Use html, md, cbom, sarif, or all.")
|
|
110
|
+
return list(dict.fromkeys(wanted)) or ["html"]
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _parse_fail_on(value: str | None) -> int | None:
|
|
114
|
+
if value is None:
|
|
115
|
+
return None
|
|
116
|
+
if value.lower() not in _FAIL_ON:
|
|
117
|
+
raise _fail(f"Unknown --fail-on value '{value}'.", f"Use one of: {', '.join(_FAIL_ON)}.")
|
|
118
|
+
return Severity(value.lower()).rank
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _prepare_out_dir(out: Path) -> None:
|
|
122
|
+
if out.is_symlink() or (out.exists() and not out.is_dir()):
|
|
123
|
+
raise _fail(
|
|
124
|
+
f"Cannot write reports to {out}: it is a file or a symlink.",
|
|
125
|
+
"Pass a folder with --out, for example `--out reports`.",
|
|
126
|
+
)
|
|
127
|
+
try:
|
|
128
|
+
out.mkdir(parents=True, exist_ok=True)
|
|
129
|
+
gitignore = out / ".gitignore"
|
|
130
|
+
if not gitignore.exists():
|
|
131
|
+
gitignore.write_text("*\n", encoding="utf-8")
|
|
132
|
+
except OSError as exc:
|
|
133
|
+
raise _write_failed(out, exc) from exc
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _write_failed(out: Path, exc: OSError) -> typer.Exit:
|
|
137
|
+
return _fail(
|
|
138
|
+
f"Cannot write the report to {out} ({exc.strerror or exc}).",
|
|
139
|
+
"Check that the folder is writable, or pick another with --out.",
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _write_report(out: Path, html: str) -> Path:
|
|
144
|
+
target = out / "report.html"
|
|
145
|
+
try:
|
|
146
|
+
fd, tmp = tempfile.mkstemp(dir=out, prefix=".report-", suffix=".tmp")
|
|
147
|
+
try:
|
|
148
|
+
with os.fdopen(fd, "w", encoding="utf-8") as handle:
|
|
149
|
+
handle.write(html)
|
|
150
|
+
os.chmod(tmp, 0o644)
|
|
151
|
+
os.replace(tmp, target)
|
|
152
|
+
except BaseException:
|
|
153
|
+
with contextlib.suppress(OSError):
|
|
154
|
+
os.unlink(tmp)
|
|
155
|
+
raise
|
|
156
|
+
except OSError as exc:
|
|
157
|
+
raise _write_failed(out, exc) from exc
|
|
158
|
+
return target
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
class _MaybeBar(BarColumn):
|
|
162
|
+
"""Show the bar only for big repos; small ones get a spinner."""
|
|
163
|
+
|
|
164
|
+
def render(self, task: Task) -> Any:
|
|
165
|
+
return super().render(task) if task.fields.get("big") else Text("")
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
class _Count(ProgressColumn):
|
|
169
|
+
def render(self, task: Task) -> Text:
|
|
170
|
+
if task.fields.get("big"):
|
|
171
|
+
return Text(f"{task.completed:.0f}/{task.total:.0f} files")
|
|
172
|
+
return Text("")
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _scan_with_progress(path: Path, baseline: Path | None) -> ScanResult:
|
|
176
|
+
err = Console(stderr=True, no_color=bool(os.environ.get("NO_COLOR")))
|
|
177
|
+
progress = Progress(
|
|
178
|
+
SpinnerColumn(),
|
|
179
|
+
TextColumn("Scanning {task.fields[where]}"),
|
|
180
|
+
_MaybeBar(),
|
|
181
|
+
_Count(),
|
|
182
|
+
console=err,
|
|
183
|
+
transient=True,
|
|
184
|
+
)
|
|
185
|
+
with progress:
|
|
186
|
+
task = progress.add_task("scan", total=None, where=escape(str(path)), big=False)
|
|
187
|
+
|
|
188
|
+
def on_progress(done: int, total: int) -> None:
|
|
189
|
+
progress.update(task, completed=done, total=total, big=total > BIG_REPO_FILES)
|
|
190
|
+
|
|
191
|
+
return run_scan(path, baseline=baseline, progress=on_progress)
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _display_path(path: Path) -> str:
|
|
195
|
+
try:
|
|
196
|
+
return os.path.relpath(path)
|
|
197
|
+
except ValueError: # different drive on Windows
|
|
198
|
+
return str(path)
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
@app.command(help="Scan a folder (default: the current one) and write a report.")
|
|
202
|
+
def scan(
|
|
203
|
+
path: Path = typer.Argument(Path(), help="Folder or file to scan."),
|
|
204
|
+
format: str = typer.Option(
|
|
205
|
+
"html", "--format", "-f", help="html (default), md, cbom, sarif, or all. Comma-separate."
|
|
206
|
+
),
|
|
207
|
+
out: Path = typer.Option(
|
|
208
|
+
Path(DEFAULT_OUT), "--out", "-o", help="Folder for the reports (made if missing)."
|
|
209
|
+
),
|
|
210
|
+
fail_on: str | None = typer.Option(
|
|
211
|
+
None,
|
|
212
|
+
"--fail-on",
|
|
213
|
+
metavar="SEVERITY",
|
|
214
|
+
help="Exit 1 if an active finding is at least this severe: critical, high, medium, low.",
|
|
215
|
+
),
|
|
216
|
+
baseline: Path | None = typer.Option(
|
|
217
|
+
None, "--baseline", help="Ignore findings already listed in this baseline file."
|
|
218
|
+
),
|
|
219
|
+
write_baseline_to: Path | None = typer.Option(
|
|
220
|
+
None, "--write-baseline", help="Save today's findings as a baseline file."
|
|
221
|
+
),
|
|
222
|
+
plain: bool = typer.Option(
|
|
223
|
+
False, "--plain", help="Plain ASCII output (also used when piped or NO_COLOR is set)."
|
|
224
|
+
),
|
|
225
|
+
) -> None:
|
|
226
|
+
formats = _parse_formats(format)
|
|
227
|
+
limit = _parse_fail_on(fail_on)
|
|
228
|
+
_prepare_out_dir(out)
|
|
229
|
+
console = make_console()
|
|
230
|
+
try:
|
|
231
|
+
result = _scan_with_progress(path, baseline)
|
|
232
|
+
if write_baseline_to is not None:
|
|
233
|
+
write_baseline(write_baseline_to, result.findings)
|
|
234
|
+
report = _write_report(out, render_html(result))
|
|
235
|
+
except KeyboardInterrupt:
|
|
236
|
+
Console(stderr=True).print("Scan cancelled.")
|
|
237
|
+
raise typer.Exit(EXIT_CANCELLED) from None
|
|
238
|
+
except ScanPathError as exc:
|
|
239
|
+
raise _split_error(exc, "Check the path and try again.") from exc
|
|
240
|
+
except RuleError as exc:
|
|
241
|
+
raise _split_error(
|
|
242
|
+
exc, "Fix the rule file named above, or reinstall quantum-scan."
|
|
243
|
+
) from exc
|
|
244
|
+
except BaselineError as exc:
|
|
245
|
+
raise _split_error(exc, "Check the baseline file path.") from exc
|
|
246
|
+
except OSError as exc:
|
|
247
|
+
raise _write_failed(out, exc) from exc
|
|
248
|
+
|
|
249
|
+
render_terminal(result, console, _display_path(report), plain=plain)
|
|
250
|
+
if write_baseline_to is not None:
|
|
251
|
+
console.print(f"Baseline saved to {escape(str(write_baseline_to))}.", soft_wrap=True)
|
|
252
|
+
if any(f != "html" for f in formats):
|
|
253
|
+
Console(stderr=True).print("md/cbom/sarif output arrives in the next update.")
|
|
254
|
+
if limit is not None and any(f.severity.rank >= limit for f in result.active):
|
|
255
|
+
raise typer.Exit(EXIT_FINDINGS)
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
@app.command(help="Explain a rule in plain English: what it finds, why, and how to fix it.")
|
|
259
|
+
def explain(
|
|
260
|
+
rule_id: str = typer.Argument(..., help="For example py.cryptography.rsa-keygen"),
|
|
261
|
+
) -> None:
|
|
262
|
+
console = make_console()
|
|
263
|
+
try:
|
|
264
|
+
rules = {rule.id: rule for rule in load_rules()}
|
|
265
|
+
except RuleError as exc:
|
|
266
|
+
raise _split_error(exc, "Reinstall quantum-scan.") from exc
|
|
267
|
+
rule = rules.get(rule_id)
|
|
268
|
+
if rule is None:
|
|
269
|
+
close = difflib.get_close_matches(rule_id, list(rules), n=3, cutoff=0.5)
|
|
270
|
+
hint = f" Did you mean: {', '.join(close)}?" if close else ""
|
|
271
|
+
raise _fail(
|
|
272
|
+
f"No rule called '{rule_id}'.{hint}",
|
|
273
|
+
"Rule ids look like py.cryptography.rsa-keygen. Known ids: " + ", ".join(sorted(rules)),
|
|
274
|
+
)
|
|
275
|
+
console.print(f"[bold]{escape(rule.title)}[/] ({escape(rule.id)}, {rule.severity.value})")
|
|
276
|
+
console.print(f"\n{escape(' '.join(rule.message.split()))}")
|
|
277
|
+
console.print(f"\n[bold]Why it matters[/]\n{escape(' '.join(rule.why.split()))}")
|
|
278
|
+
console.print(f"\n[bold]How to fix it[/]\n{escape(rule.fix.rstrip())}", highlight=False)
|
|
279
|
+
if rule.references:
|
|
280
|
+
console.print("\n[bold]Read more[/]")
|
|
281
|
+
for ref in rule.references:
|
|
282
|
+
console.print(f" {escape(ref)}", soft_wrap=True)
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
@app.command(help="Run as an MCP server over stdio, for Claude Code, Cursor and other AI tools.")
|
|
286
|
+
def mcp() -> None:
|
|
287
|
+
try:
|
|
288
|
+
from quantum_scan.mcp_server import serve
|
|
289
|
+
except ModuleNotFoundError as exc:
|
|
290
|
+
if exc.name is None or not exc.name.startswith("mcp"):
|
|
291
|
+
raise
|
|
292
|
+
raise _fail(
|
|
293
|
+
"The MCP server needs an optional package that is not installed.",
|
|
294
|
+
'Run: pip install "quantum-scan[mcp]" (or: pipx install "quantum-scan[mcp]")',
|
|
295
|
+
) from exc
|
|
296
|
+
serve()
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
@app.command(help="Set up a GitHub Action for this repo (coming soon).")
|
|
300
|
+
def init() -> None:
|
|
301
|
+
typer.echo("`quantum-scan init` (GitHub Action setup) arrives soon. Nothing was changed.")
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
@app.command(help="Show a post-quantum fix as a diff (coming soon).")
|
|
305
|
+
def fix(
|
|
306
|
+
dry_run: bool = typer.Option(False, "--dry-run", help="Show changes without writing them."),
|
|
307
|
+
) -> None:
|
|
308
|
+
del dry_run
|
|
309
|
+
typer.echo("`quantum-scan fix --dry-run` arrives soon. Nothing was changed.")
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def main() -> None:
|
|
313
|
+
app()
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Code-scanning engine: prefilter, parse, resolve, match."""
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""Resolver output: language-neutral call sites with canonical names.
|
|
2
|
+
|
|
3
|
+
Each language resolver (python.py, javascript.py) parses one file and returns a list of
|
|
4
|
+
`CallSite`. The matcher only ever sees `CallSite`s, so rules stay language-agnostic.
|
|
5
|
+
|
|
6
|
+
Canonical names
|
|
7
|
+
---------------
|
|
8
|
+
Python: full import path + attribute chain.
|
|
9
|
+
`from cryptography.hazmat.primitives.asymmetric import rsa as r; r.generate_private_key()`
|
|
10
|
+
-> "cryptography.hazmat.primitives.asymmetric.rsa.generate_private_key"
|
|
11
|
+
JS/TS: module specifier WITHOUT a `node:` prefix + member chain.
|
|
12
|
+
`const { generateKeyPairSync: g } = require('node:crypto'); g('rsa')`
|
|
13
|
+
-> "crypto.generateKeyPairSync"
|
|
14
|
+
`import jwt from 'jsonwebtoken'; jwt.sign(...)` -> "jsonwebtoken.sign"
|
|
15
|
+
(default import and `import * as` both resolve to the module itself)
|
|
16
|
+
`new forge.pki.rsa.KeyPair()` style `new X()` is a call to X.
|
|
17
|
+
Variables assigned from a call (flow-insensitive, same file):
|
|
18
|
+
`k = rsa.generate_private_key(...); k.sign(...)`
|
|
19
|
+
-> "cryptography.hazmat.primitives.asymmetric.rsa.generate_private_key().sign"
|
|
20
|
+
Unresolvable callees (local functions, unknown receivers) are not emitted.
|
|
21
|
+
Alternative imports of one name (`try: from Cryptodome.X import RSA` /
|
|
22
|
+
`except ImportError: from Crypto.X import RSA`) yield ONE CallSite PER canonical name,
|
|
23
|
+
at the same location. Consumers must deduplicate findings per (rule, location).
|
|
24
|
+
`text` may be truncated for very long expressions; don't rely on it beyond snippets and
|
|
25
|
+
fingerprints.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
from __future__ import annotations
|
|
29
|
+
|
|
30
|
+
from dataclasses import dataclass, field
|
|
31
|
+
from typing import Union
|
|
32
|
+
|
|
33
|
+
from quantum_scan.models import Location
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass(frozen=True, slots=True)
|
|
37
|
+
class Unknown:
|
|
38
|
+
"""An argument whose value can't be determined statically (variable, expression)."""
|
|
39
|
+
|
|
40
|
+
text: str = ""
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass(frozen=True, slots=True)
|
|
44
|
+
class CallRef:
|
|
45
|
+
"""An argument that is itself a resolved call, e.g. `ec.SECP256R1()`."""
|
|
46
|
+
|
|
47
|
+
name: str # canonical name of the callee
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
# Literal values, lists/tuples of values, dicts (JS object literals / Python dict
|
|
51
|
+
# literals with string keys), nested calls, or Unknown. Same-file constants
|
|
52
|
+
# (`ALG = "RS256"` at module level / `const ALG = 'RS256'`) are substituted.
|
|
53
|
+
ArgValue = Union[ # noqa: UP007 - recursive alias needs Union
|
|
54
|
+
str, int, float, bool, None, Unknown, CallRef, list["ArgValue"], dict[str, "ArgValue"]
|
|
55
|
+
]
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@dataclass(frozen=True, slots=True)
|
|
59
|
+
class CallSite:
|
|
60
|
+
name: str # canonical callee name
|
|
61
|
+
args: tuple[ArgValue, ...] # positional arguments in order (spread -> Unknown)
|
|
62
|
+
kwargs: dict[str, ArgValue] = field(default_factory=dict) # Python keyword args
|
|
63
|
+
location: Location = field(default_factory=lambda: Location("", 0, 0, 0, 0))
|
|
64
|
+
text: str = "" # source text of the whole call expression (for snippet/fingerprint)
|