toolfence-crypto 0.3.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.
@@ -0,0 +1,3 @@
1
+ """ToolFence Crypto: scan repositories for quantum-vulnerable and weak cryptography."""
2
+
3
+ __version__ = "0.3.0"
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
@@ -0,0 +1,158 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import sys
5
+ from pathlib import Path
6
+
7
+ from . import __version__
8
+ from .config import ScanConfig, load_config
9
+ from .export import write_cbom, write_json_report, write_sarif
10
+ from .html_report import write_html
11
+ from .models import SEVERITY_RANK
12
+ from .policy import POLICY_IDS, evaluate_policy
13
+ from .repo import looks_like_remote, prepare_scan_target
14
+ from .report import print_report
15
+ from .scanner import scan_path
16
+
17
+
18
+ def build_parser() -> argparse.ArgumentParser:
19
+ parser = argparse.ArgumentParser(
20
+ prog="toolfence-crypto",
21
+ description=(
22
+ "Simple crypto checkup for solo developers and small teams: "
23
+ "scan a local folder or a GitHub repo URL. "
24
+ "Zero required third-party dependencies (git required for remote URLs)."
25
+ ),
26
+ )
27
+ parser.add_argument(
28
+ "target",
29
+ nargs="?",
30
+ default=".",
31
+ help=(
32
+ "Local path, GitHub URL, or owner/repo "
33
+ "(examples: . ./my-app https://github.com/org/app org/app)"
34
+ ),
35
+ )
36
+ parser.add_argument(
37
+ "--branch",
38
+ "-b",
39
+ default=None,
40
+ help="Branch or tag to clone when scanning a remote repo (default: remote default branch)",
41
+ )
42
+ parser.add_argument(
43
+ "--json",
44
+ dest="json_out",
45
+ metavar="FILE",
46
+ help="Write JSON report to FILE",
47
+ )
48
+ parser.add_argument(
49
+ "--cbom",
50
+ dest="cbom_out",
51
+ metavar="FILE",
52
+ help="Write CycloneDX 1.6 CBOM JSON to FILE",
53
+ )
54
+ parser.add_argument(
55
+ "--sarif",
56
+ dest="sarif_out",
57
+ metavar="FILE",
58
+ help="Write SARIF 2.1.0 report to FILE (CI / code scanning)",
59
+ )
60
+ parser.add_argument(
61
+ "--html",
62
+ dest="html_out",
63
+ metavar="FILE",
64
+ help="Write a standalone HTML report to FILE (easy to open in a browser)",
65
+ )
66
+ parser.add_argument(
67
+ "--fail-on",
68
+ choices=list(SEVERITY_RANK),
69
+ default=None,
70
+ help="Exit 1 if any finding at this severity or higher is found",
71
+ )
72
+ parser.add_argument(
73
+ "--policy",
74
+ choices=list(POLICY_IDS),
75
+ default=None,
76
+ help=(
77
+ "Evaluate a built-in policy pack and exit 1 on failure "
78
+ "(baseline-weak | nist-8547 | cnsa-2.0)"
79
+ ),
80
+ )
81
+ parser.add_argument(
82
+ "--no-config",
83
+ action="store_true",
84
+ help="Ignore toolfence-crypto.toml",
85
+ )
86
+ parser.add_argument(
87
+ "--verbose",
88
+ "-v",
89
+ action="store_true",
90
+ help="Show the full finding list (default shows Top fixes only)",
91
+ )
92
+ parser.add_argument(
93
+ "--quiet",
94
+ action="store_true",
95
+ help="Suppress terminal report (useful with --json/--cbom/--sarif/--html)",
96
+ )
97
+ parser.add_argument("--version", action="version", version=f"toolfence-crypto {__version__}")
98
+ return parser
99
+
100
+
101
+ def main(argv: list[str] | None = None) -> int:
102
+ parser = build_parser()
103
+ args = parser.parse_args(argv)
104
+
105
+ try:
106
+ with prepare_scan_target(args.target, branch=args.branch) as (target, label):
107
+ if not target.exists():
108
+ print(f"Path not found: {target}", file=sys.stderr)
109
+ return 2
110
+
111
+ if looks_like_remote(args.target) and not args.quiet:
112
+ print(f"Cloned {label} — scanning…")
113
+
114
+ config = ScanConfig() if args.no_config else load_config(target)
115
+ summary = scan_path(target, config)
116
+
117
+ policy_id = args.policy or config.policy
118
+ if policy_id:
119
+ summary.policy = evaluate_policy(policy_id, summary.findings)
120
+
121
+ if not args.quiet:
122
+ print_report(summary, verbose=args.verbose)
123
+
124
+ wrote: list[str] = []
125
+ if args.json_out:
126
+ write_json_report(summary, Path(args.json_out))
127
+ wrote.append(args.json_out)
128
+ if args.cbom_out:
129
+ write_cbom(summary, Path(args.cbom_out))
130
+ wrote.append(args.cbom_out)
131
+ if args.sarif_out:
132
+ write_sarif(summary, Path(args.sarif_out))
133
+ wrote.append(args.sarif_out)
134
+ if args.html_out:
135
+ write_html(summary, Path(args.html_out), scanned_path=label)
136
+ wrote.append(args.html_out)
137
+
138
+ if wrote and not args.quiet:
139
+ print("Wrote: " + ", ".join(wrote))
140
+
141
+ exit_code = 0
142
+ fail_on = args.fail_on or config.fail_on
143
+ if fail_on:
144
+ threshold = SEVERITY_RANK[fail_on]
145
+ if any(SEVERITY_RANK.get(f.severity, 99) <= threshold for f in summary.findings):
146
+ exit_code = 1
147
+
148
+ if summary.policy is not None and not summary.policy.passed:
149
+ exit_code = 1
150
+
151
+ return exit_code
152
+ except (ValueError, RuntimeError) as exc:
153
+ print(str(exc), file=sys.stderr)
154
+ return 2
155
+
156
+
157
+ if __name__ == "__main__":
158
+ sys.exit(main())
@@ -0,0 +1,77 @@
1
+ from __future__ import annotations
2
+
3
+ import sys
4
+ from dataclasses import dataclass, field
5
+ from pathlib import Path
6
+
7
+ if sys.version_info >= (3, 11):
8
+ import tomllib
9
+ else: # pragma: no cover - py3.10
10
+ try:
11
+ import tomli as tomllib # type: ignore
12
+ except ImportError:
13
+ tomllib = None # type: ignore
14
+
15
+
16
+ @dataclass
17
+ class ScanConfig:
18
+ """Minimal project config — no schema framework required."""
19
+
20
+ ignore_rules: set[str] = field(default_factory=set)
21
+ ignore_paths: list[str] = field(default_factory=list)
22
+ fail_on: str | None = None
23
+ policy: str | None = None
24
+
25
+ def is_path_ignored(self, relative_path: str) -> bool:
26
+ norm = relative_path.replace("\\", "/")
27
+ for pattern in self.ignore_paths:
28
+ p = pattern.replace("\\", "/").lstrip("./")
29
+ if not p:
30
+ continue
31
+ if p.endswith("/**"):
32
+ prefix = p[:-3]
33
+ if norm == prefix.rstrip("/") or norm.startswith(prefix):
34
+ return True
35
+ elif p.endswith("/*"):
36
+ parent = p[:-2].rstrip("/")
37
+ parent_part = str(Path(norm).parent).replace("\\", "/")
38
+ if parent_part == parent or (parent == "." and "/" not in norm):
39
+ return True
40
+ elif norm == p or norm.endswith("/" + p) or norm.startswith(p.rstrip("/") + "/"):
41
+ return True
42
+ elif Path(norm).match(p):
43
+ return True
44
+ return False
45
+
46
+
47
+ def load_config(start: Path) -> ScanConfig:
48
+ """Load toolfence-crypto.toml from start or nearest parent. Missing file = defaults."""
49
+ path = _find_config(start)
50
+ if path is None:
51
+ return ScanConfig()
52
+ if tomllib is None:
53
+ raise RuntimeError(
54
+ "toolfence-crypto.toml found but TOML parsing needs Python 3.11+ "
55
+ "(or install optional 'tomli' on 3.10)."
56
+ )
57
+ data = tomllib.loads(path.read_text(encoding="utf-8"))
58
+ section = data.get("toolfence-crypto") or data.get("cryptoscan") or data
59
+ return ScanConfig(
60
+ ignore_rules={str(x) for x in section.get("ignore_rules", [])},
61
+ ignore_paths=[str(x) for x in section.get("ignore_paths", [])],
62
+ fail_on=section.get("fail_on"),
63
+ policy=section.get("policy"),
64
+ )
65
+
66
+
67
+ def _find_config(start: Path) -> Path | None:
68
+ cur = start.resolve()
69
+ if cur.is_file():
70
+ cur = cur.parent
71
+ for directory in [cur, *cur.parents]:
72
+ candidate = directory / "toolfence-crypto.toml"
73
+ if candidate.is_file():
74
+ return candidate
75
+ if (directory / ".git").exists():
76
+ break
77
+ return None
@@ -0,0 +1,214 @@
1
+ """Scan dependency manifests for cryptography-related packages (stdlib only)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import re
7
+ from pathlib import Path
8
+
9
+ from .models import Category, Finding, Severity
10
+
11
+ # package name (normalized) -> (severity, note)
12
+ CRYPTO_PACKAGES: dict[str, tuple[Severity, str]] = {
13
+ "cryptography": (Severity.INFO, "Modern Python crypto library — inventory for RSA/ECC/PQC usage in code"),
14
+ "pycryptodome": (Severity.MEDIUM, "Often used for classical public-key crypto; review algorithms in use"),
15
+ "pycrypto": (Severity.HIGH, "Abandoned crypto library; migrate off PyCrypto"),
16
+ "pyopenssl": (Severity.MEDIUM, "OpenSSL bindings — check TLS and cert usage"),
17
+ "paramiko": (Severity.MEDIUM, "SSH uses classical public-key crypto (quantum-vulnerable long-term)"),
18
+ "pyjwt": (Severity.MEDIUM, "JWT library — check for RS*/ES* algorithms"),
19
+ "python-jose": (Severity.MEDIUM, "JWT/JOSE — check signing algorithms"),
20
+ "jwcrypto": (Severity.MEDIUM, "JWK/JWS — check algorithms"),
21
+ "bcrypt": (Severity.INFO, "Password hashing (good for passwords; not a PQC substitute)"),
22
+ "argon2-cffi": (Severity.INFO, "Password hashing (good for passwords)"),
23
+ "pynacl": (Severity.MEDIUM, "NaCl/libsodium — classical crypto; plan PQC where needed"),
24
+ "libnacl": (Severity.MEDIUM, "NaCl bindings — classical crypto"),
25
+ "openssl": (Severity.MEDIUM, "Native OpenSSL dependency — inventory algorithms"),
26
+ "node-forge": (Severity.MEDIUM, "JS crypto — review algorithms"),
27
+ "crypto-js": (Severity.HIGH, "Legacy JS crypto; prefer WebCrypto / audited libs"),
28
+ "jsonwebtoken": (Severity.MEDIUM, "JWT — check RS*/ES* algorithms"),
29
+ "jose": (Severity.MEDIUM, "JOSE/JWT — check algorithms"),
30
+ "bcryptjs": (Severity.INFO, "Password hashing"),
31
+ "tweetnacl": (Severity.MEDIUM, "Classical public-key crypto"),
32
+ "libsodium-wrappers": (Severity.MEDIUM, "Classical crypto wrappers"),
33
+ "golang.org/x/crypto": (Severity.MEDIUM, "Extended Go crypto — review algorithms"),
34
+ "github.com/golang-jwt/jwt": (Severity.MEDIUM, "JWT — check signing method"),
35
+ "github.com/dgrijalva/jwt-go": (Severity.HIGH, "Unmaintained JWT library"),
36
+ "org.bouncycastle": (Severity.MEDIUM, "BouncyCastle — inventory algorithms"),
37
+ "commons-codec": (Severity.LOW, "Codec/hash helpers — check for MD5/SHA-1"),
38
+ }
39
+
40
+
41
+ MANIFEST_NAMES = {
42
+ "requirements.txt",
43
+ "requirements-dev.txt",
44
+ "pyproject.toml",
45
+ "Pipfile",
46
+ "package.json",
47
+ "package-lock.json",
48
+ "yarn.lock",
49
+ "pnpm-lock.yaml",
50
+ "go.mod",
51
+ "Cargo.toml",
52
+ "Gemfile",
53
+ "composer.json",
54
+ "pom.xml",
55
+ }
56
+
57
+
58
+ def _norm(name: str) -> str:
59
+ return name.strip().lower().replace("_", "-")
60
+
61
+
62
+ def _finding(rel: str, line: int, pkg: str, severity: Severity, note: str) -> Finding:
63
+ sev = severity.value
64
+ # INFO deps are inventory; treat medium+ as actionable debt for solos
65
+ title = f"Crypto-related dependency: {pkg}"
66
+ return Finding(
67
+ rule_id="DEP001",
68
+ title=title,
69
+ category=Category.DEPENDENCY.value,
70
+ severity=sev,
71
+ file=rel,
72
+ line=line,
73
+ column=1,
74
+ snippet=pkg,
75
+ description=note,
76
+ remediation=(
77
+ "Confirm how this library is used in your app. Prefer maintained libraries, "
78
+ "avoid abandoned crypto packages, and plan PQC/hybrid migration for public-key features."
79
+ ),
80
+ references=[],
81
+ confidence="medium",
82
+ detail=f"package={pkg}",
83
+ source="dependency",
84
+ )
85
+
86
+
87
+ def _match_package(name: str) -> tuple[str, Severity, str] | None:
88
+ n = _norm(name)
89
+ if n in CRYPTO_PACKAGES:
90
+ sev, note = CRYPTO_PACKAGES[n]
91
+ return n, sev, note
92
+ for key, (sev, note) in CRYPTO_PACKAGES.items():
93
+ if n == key or n.endswith("/" + key) or n.endswith(":" + key):
94
+ return key, sev, note
95
+ return None
96
+
97
+
98
+ def scan_manifest(path: Path, root: Path) -> list[Finding]:
99
+ name = path.name
100
+ if name not in MANIFEST_NAMES and path.suffix.lower() not in {".toml", ".json", ".txt", ".xml"}:
101
+ return []
102
+ # Only known manifests by name (avoid scanning every json)
103
+ if name not in MANIFEST_NAMES:
104
+ return []
105
+
106
+ try:
107
+ text = path.read_text(encoding="utf-8", errors="replace")
108
+ except OSError:
109
+ return []
110
+
111
+ rel = str(path.relative_to(root))
112
+ findings: list[Finding] = []
113
+ seen: set[str] = set()
114
+
115
+ def add(pkg_raw: str, line_no: int) -> None:
116
+ matched = _match_package(pkg_raw)
117
+ if not matched:
118
+ return
119
+ pkg, sev, note = matched
120
+ if pkg in seen:
121
+ return
122
+ seen.add(pkg)
123
+ findings.append(_finding(rel, line_no, pkg, sev, note))
124
+
125
+ if name.startswith("requirements") and name.endswith(".txt"):
126
+ for i, line in enumerate(text.splitlines(), start=1):
127
+ raw = line.split("#", 1)[0].strip()
128
+ if not raw or raw.startswith("-"):
129
+ continue
130
+ pkg = re.split(r"[=<>!~\[]", raw, maxsplit=1)[0].strip()
131
+ add(pkg, i)
132
+
133
+ elif name == "pyproject.toml":
134
+ # Lightweight: find quoted package names near dependencies tables
135
+ for i, line in enumerate(text.splitlines(), start=1):
136
+ for m in re.finditer(r'["\']([A-Za-z0-9_.\-]+)["\']\s*[>=<~!]', line):
137
+ add(m.group(1), i)
138
+ for m in re.finditer(r'^\s*([A-Za-z0-9_.\-]+)\s*\[', line):
139
+ add(m.group(1), i)
140
+
141
+ elif name == "package.json":
142
+ try:
143
+ data = json.loads(text)
144
+ except json.JSONDecodeError:
145
+ data = {}
146
+ for section in ("dependencies", "devDependencies", "optionalDependencies"):
147
+ deps = data.get(section) or {}
148
+ if isinstance(deps, dict):
149
+ for pkg in deps:
150
+ add(pkg, 1)
151
+
152
+ elif name in {"package-lock.json", "yarn.lock", "pnpm-lock.yaml"}:
153
+ for i, line in enumerate(text.splitlines(), start=1):
154
+ for key in CRYPTO_PACKAGES:
155
+ if key in line.lower():
156
+ add(key, i)
157
+
158
+ elif name == "go.mod":
159
+ for i, line in enumerate(text.splitlines(), start=1):
160
+ parts = line.strip().split()
161
+ if len(parts) >= 1 and ("/" in parts[0] or parts[0].startswith("golang.org")):
162
+ add(parts[0], i)
163
+ for part in parts:
164
+ add(part, i)
165
+
166
+ elif name == "Cargo.toml":
167
+ for i, line in enumerate(text.splitlines(), start=1):
168
+ m = re.match(r"\s*([A-Za-z0-9_\-]+)\s*=", line)
169
+ if m:
170
+ add(m.group(1), i)
171
+
172
+ elif name == "Gemfile":
173
+ for i, line in enumerate(text.splitlines(), start=1):
174
+ m = re.search(r"gem\s+['\"]([^'\"]+)['\"]", line)
175
+ if m:
176
+ add(m.group(1), i)
177
+
178
+ elif name == "composer.json":
179
+ try:
180
+ data = json.loads(text)
181
+ except json.JSONDecodeError:
182
+ data = {}
183
+ for section in ("require", "require-dev"):
184
+ deps = data.get(section) or {}
185
+ if isinstance(deps, dict):
186
+ for pkg in deps:
187
+ add(pkg, 1)
188
+
189
+ elif name == "pom.xml":
190
+ for i, line in enumerate(text.splitlines(), start=1):
191
+ if "bouncycastle" in line.lower() or "commons-codec" in line.lower():
192
+ if "bouncycastle" in line.lower():
193
+ add("org.bouncycastle", i)
194
+ if "commons-codec" in line.lower():
195
+ add("commons-codec", i)
196
+
197
+ return findings
198
+
199
+
200
+ def iter_manifests(root: Path, ignore) -> list[Path]:
201
+ files: list[Path] = []
202
+ for path in root.rglob("*"):
203
+ if not path.is_file():
204
+ continue
205
+ if path.name not in MANIFEST_NAMES:
206
+ continue
207
+ try:
208
+ rel = str(path.relative_to(root))
209
+ except ValueError:
210
+ continue
211
+ if ignore(rel):
212
+ continue
213
+ files.append(path)
214
+ return files