quantumguard-cnsa2 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.
@@ -0,0 +1,81 @@
1
+ """
2
+ QuantumGuard: CNSA 2.0 Hybrid PQC + ETSI GS QKD 014 Transport, Downgrade Firewall & CBOM CI Gate.
3
+ """
4
+
5
+ from quantumguard.crypto_core import (
6
+ AES256GCMChannel,
7
+ CNSA2_SUITE_HYBRID_QKD,
8
+ CNSA2_SUITE_PQC_ONLY,
9
+ Etsi014Client,
10
+ Etsi014Key,
11
+ IdentityKeyPair,
12
+ KeyProvider,
13
+ MLDSA87_PK_BYTES,
14
+ MLDSA87_SIG_BYTES,
15
+ MLKEM1024_CT_BYTES,
16
+ MLKEM1024_EK_BYTES,
17
+ MLKEM1024_SS_BYTES,
18
+ P384_POINT_BYTES,
19
+ SimulatedLEOBB84Provider,
20
+ WegmanCarterMAC,
21
+ derive_hybrid_session_keys,
22
+ generate_uuidv7,
23
+ verify_fips_sizes,
24
+ zeroize_bytes,
25
+ )
26
+ from quantumguard.guard import (
27
+ DowngradeBlockedError,
28
+ FirewallDecision,
29
+ HandshakeFirewall,
30
+ SecurityPolicy,
31
+ )
32
+ from quantumguard.kme_mock import create_kme_app, kme_app
33
+ from quantumguard.sidechannel import (
34
+ DudectPathResult,
35
+ SideChannelSuiteReport,
36
+ run_tec_91011_suite,
37
+ )
38
+ from quantumguard.cbom_scanner import (
39
+ CBOMReport,
40
+ CryptoFinding,
41
+ audit_path,
42
+ generate_cyclonedx_cbom,
43
+ )
44
+
45
+ __version__ = "0.2.0"
46
+
47
+ __all__ = [
48
+ "__version__",
49
+ "AES256GCMChannel",
50
+ "CNSA2_SUITE_HYBRID_QKD",
51
+ "CNSA2_SUITE_PQC_ONLY",
52
+ "CBOMReport",
53
+ "CryptoFinding",
54
+ "DowngradeBlockedError",
55
+ "DudectPathResult",
56
+ "Etsi014Client",
57
+ "Etsi014Key",
58
+ "FirewallDecision",
59
+ "HandshakeFirewall",
60
+ "IdentityKeyPair",
61
+ "KeyProvider",
62
+ "MLDSA87_PK_BYTES",
63
+ "MLDSA87_SIG_BYTES",
64
+ "MLKEM1024_CT_BYTES",
65
+ "MLKEM1024_EK_BYTES",
66
+ "MLKEM1024_SS_BYTES",
67
+ "P384_POINT_BYTES",
68
+ "SecurityPolicy",
69
+ "SideChannelSuiteReport",
70
+ "SimulatedLEOBB84Provider",
71
+ "WegmanCarterMAC",
72
+ "audit_path",
73
+ "create_kme_app",
74
+ "derive_hybrid_session_keys",
75
+ "generate_cyclonedx_cbom",
76
+ "generate_uuidv7",
77
+ "kme_app",
78
+ "run_tec_91011_suite",
79
+ "verify_fips_sizes",
80
+ "zeroize_bytes",
81
+ ]
@@ -0,0 +1,6 @@
1
+ """Entry point for `python -m quantumguard`."""
2
+
3
+ from quantumguard.cli import main
4
+
5
+ if __name__ == "__main__":
6
+ raise SystemExit(main())
@@ -0,0 +1,583 @@
1
+ """
2
+ QuantumGuard Automated Cryptographic Bill of Materials (CBOM) Scanner & CI Policy Gate.
3
+
4
+ Recursively scans Python (via AST analysis) and C/C++/JS/TS/Config/Dockerfile/YAML
5
+ files (via context-aware rules) to produce a CycloneDX v1.6 JSON CBOM mapped to:
6
+ - NSA CNSA 2.0 (Jan 1, 2027 NSS gate) & NSA Advisory PP-26-4956 (Dec 2, 2026)
7
+ - US Executive Order 14412 (Dec 31, 2030 / Dec 31, 2031)
8
+ - India DST / NQM CII Roadmap & CERT-In CBOM (FY 2027-28 / Dec 2029)
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import ast
14
+ import json
15
+ import re
16
+ import uuid
17
+ from dataclasses import asdict, dataclass, field
18
+ from datetime import datetime, timezone
19
+ from pathlib import Path
20
+ from typing import Any
21
+
22
+ SCAN_EXTENSIONS: frozenset[str] = frozenset(
23
+ {".py", ".c", ".cpp", ".h", ".js", ".ts", ".yml", ".yaml", ".conf"}
24
+ )
25
+ SCAN_FILENAMES: frozenset[str] = frozenset({"Dockerfile"})
26
+ SKIP_DIRS: frozenset[str] = frozenset(
27
+ {".git", "__pycache__", ".pytest_cache", ".venv", "venv", "node_modules", "build", "dist", ".eggs"}
28
+ )
29
+
30
+
31
+ @dataclass(frozen=True)
32
+ class CryptoFinding:
33
+ """Single detected cryptographic asset or policy violation."""
34
+
35
+ file_path: str
36
+ line_number: int
37
+ algorithm: str
38
+ primitive: str
39
+ severity: str # CRITICAL, HIGH, MEDIUM, INFO
40
+ compliant_cnsa2: bool
41
+ compliant_eo14412: bool
42
+ compliant_india_cii: bool
43
+ nist_pqc_level: int
44
+ evidence: str
45
+ remediation: str
46
+ rule_id: str
47
+
48
+
49
+ @dataclass
50
+ class CBOMReport:
51
+ """Aggregated CBOM scan results and compliance gate verdict."""
52
+
53
+ target_path: str
54
+ scanned_files: int
55
+ findings: list[CryptoFinding] = field(default_factory=list)
56
+ errors: list[str] = field(default_factory=list)
57
+
58
+ @property
59
+ def violations(self) -> list[CryptoFinding]:
60
+ return [f for f in self.findings if not f.compliant_cnsa2]
61
+
62
+ @property
63
+ def compliant_assets(self) -> list[CryptoFinding]:
64
+ return [f for f in self.findings if f.compliant_cnsa2]
65
+
66
+ @property
67
+ def exit_code(self) -> int:
68
+ return 1 if self.violations else 0
69
+
70
+ def summary_counts(self) -> dict[str, int]:
71
+ counts = {"CRITICAL": 0, "HIGH": 0, "MEDIUM": 0, "INFO": 0}
72
+ for f in self.findings:
73
+ counts[f.severity] = counts.get(f.severity, 0) + 1
74
+ return counts
75
+
76
+
77
+ def _attr_chain(node: ast.AST) -> str:
78
+ parts: list[str] = []
79
+ cur: ast.AST | None = node
80
+ while isinstance(cur, ast.Attribute):
81
+ parts.append(cur.attr)
82
+ cur = cur.value
83
+ if isinstance(cur, ast.Name):
84
+ parts.append(cur.id)
85
+ return ".".join(reversed(parts))
86
+
87
+
88
+ def _kw_int(call: ast.Call, kw_name: str, positional_idx: int | None = None) -> int | None:
89
+ for kw in call.keywords:
90
+ if kw.arg == kw_name and isinstance(kw.value, ast.Constant) and isinstance(kw.value.value, int):
91
+ return int(kw.value.value)
92
+ if positional_idx is not None and len(call.args) > positional_idx:
93
+ arg = call.args[positional_idx]
94
+ if isinstance(arg, ast.Constant) and isinstance(arg.value, int):
95
+ return int(arg.value)
96
+ return None
97
+
98
+
99
+ def _kw_bool(call: ast.Call, kw_name: str) -> bool | None:
100
+ for kw in call.keywords:
101
+ if kw.arg == kw_name and isinstance(kw.value, ast.Constant) and isinstance(kw.value.value, bool):
102
+ return bool(kw.value.value)
103
+ return None
104
+
105
+
106
+ class _PythonCryptoVisitor(ast.NodeVisitor):
107
+ """AST visitor detecting real cryptographic primitive usage in Python modules."""
108
+
109
+ def __init__(self, rel_path: str, source_lines: list[str]) -> None:
110
+ self.rel_path = rel_path
111
+ self.source_lines = source_lines
112
+ self.findings: list[CryptoFinding] = []
113
+ self.has_mlkem1024 = False
114
+ self.has_mldsa87 = False
115
+ self.aliases: dict[str, str] = {}
116
+
117
+ def _snippet(self, lineno: int) -> str:
118
+ if 1 <= lineno <= len(self.source_lines):
119
+ return self.source_lines[lineno - 1].strip()[:120]
120
+ return ""
121
+
122
+ def _add(
123
+ self,
124
+ lineno: int,
125
+ algorithm: str,
126
+ primitive: str,
127
+ severity: str,
128
+ compliant: bool,
129
+ nist_level: int,
130
+ remediation: str,
131
+ rule_id: str,
132
+ ) -> None:
133
+ self.findings.append(
134
+ CryptoFinding(
135
+ file_path=self.rel_path,
136
+ line_number=lineno,
137
+ algorithm=algorithm,
138
+ primitive=primitive,
139
+ severity=severity,
140
+ compliant_cnsa2=compliant,
141
+ compliant_eo14412=compliant,
142
+ compliant_india_cii=compliant,
143
+ nist_pqc_level=nist_level,
144
+ evidence=self._snippet(lineno),
145
+ remediation=remediation,
146
+ rule_id=rule_id,
147
+ )
148
+ )
149
+
150
+ def visit_ImportFrom(self, node: ast.ImportFrom) -> None:
151
+ mod = node.module or ""
152
+ for alias in node.names:
153
+ name = alias.asname or alias.name
154
+ self.aliases[name] = f"{mod}.{alias.name}" if mod else alias.name
155
+ self.generic_visit(node)
156
+
157
+ def visit_Import(self, node: ast.Import) -> None:
158
+ for alias in node.names:
159
+ name = alias.asname or alias.name
160
+ self.aliases[name] = alias.name
161
+ self.generic_visit(node)
162
+
163
+ def _resolve(self, chain: str) -> str:
164
+ head, *rest = chain.split(".")
165
+ if head in self.aliases:
166
+ mapped = self.aliases[head]
167
+ return ".".join([mapped] + rest) if rest else mapped
168
+ return chain
169
+
170
+ def visit_Call(self, node: ast.Call) -> None:
171
+ raw_chain = _attr_chain(node.func)
172
+ resolved = self._resolve(raw_chain)
173
+ lineno = node.lineno
174
+
175
+ # PQC compliant primitives (FIPS 203 / FIPS 204)
176
+ if "MLKEM1024PrivateKey.generate" in resolved or "MLKEM1024" in raw_chain:
177
+ self.has_mlkem1024 = True
178
+ self._add(
179
+ lineno,
180
+ "ML-KEM-1024",
181
+ "kem",
182
+ "INFO",
183
+ True,
184
+ 5,
185
+ "CNSA 2.0 compliant (FIPS 203 Category 5).",
186
+ "QG-PQC-001",
187
+ )
188
+ elif "MLKEM768PrivateKey.generate" in resolved or "MLKEM768" in raw_chain:
189
+ self._add(
190
+ lineno,
191
+ "ML-KEM-768",
192
+ "kem",
193
+ "MEDIUM",
194
+ False,
195
+ 3,
196
+ "Upgrade ML-KEM-768 to ML-KEM-1024 for strict CNSA 2.0 compliance (allowed only as commercial RFC 10024 expedient).",
197
+ "QG-CNSA-002",
198
+ )
199
+ elif "MLDSA87PrivateKey.generate" in resolved or "MLDSA87" in raw_chain:
200
+ self.has_mldsa87 = True
201
+ self._add(
202
+ lineno,
203
+ "ML-DSA-87",
204
+ "signature",
205
+ "INFO",
206
+ True,
207
+ 5,
208
+ "CNSA 2.0 compliant (FIPS 204 Category 5).",
209
+ "QG-PQC-002",
210
+ )
211
+ elif "MLDSA44" in raw_chain or "MLDSA65" in raw_chain:
212
+ self._add(
213
+ lineno,
214
+ "ML-DSA-44/65",
215
+ "signature",
216
+ "MEDIUM",
217
+ False,
218
+ 1 if "44" in raw_chain else 3,
219
+ "Upgrade to ML-DSA-87 for strict CNSA 2.0 compliance.",
220
+ "QG-CNSA-003",
221
+ )
222
+ # Classical asymmetric key generation / use
223
+ elif resolved.endswith("rsa.generate_private_key") or raw_chain.endswith("RSA.generate"):
224
+ ksize = _kw_int(node, "key_size", positional_idx=1) or _kw_int(node, "bits", positional_idx=0) or 2048
225
+ sev = "CRITICAL" if ksize < 3072 else "HIGH"
226
+ self._add(
227
+ lineno,
228
+ f"RSA-{ksize}",
229
+ "signature/key-exchange",
230
+ sev,
231
+ False,
232
+ 0,
233
+ "Replace RSA with ML-KEM-1024 (FIPS 203) / ML-DSA-87 (FIPS 204); RSA < 3072 disallowed under PP-26-4956.",
234
+ "QG-RSA-001",
235
+ )
236
+ elif resolved.endswith("dsa.generate_private_key"):
237
+ self._add(
238
+ lineno,
239
+ "DSA",
240
+ "signature",
241
+ "CRITICAL",
242
+ False,
243
+ 0,
244
+ "Legacy DSA is banned under CNSA 2.0 & PP-26-4956; migrate immediately to ML-DSA-87.",
245
+ "QG-DSA-001",
246
+ )
247
+ elif "X25519PrivateKey" in resolved or "Ed25519PrivateKey" in resolved or "X448" in resolved or "Ed448" in resolved:
248
+ alg = "X25519" if "X25519" in resolved else ("Ed25519" if "Ed25519" in resolved else "X448/Ed448")
249
+ self._add(
250
+ lineno,
251
+ alg,
252
+ "key-exchange/signature",
253
+ "CRITICAL",
254
+ False,
255
+ 0,
256
+ f"{alg} flagged by NSA PP-26-4956 Action 1; migrate to SecP384r1MLKEM1024 / ML-DSA-87.",
257
+ "QG-ECC-256",
258
+ )
259
+ elif resolved.endswith("ec.generate_private_key"):
260
+ curve_str = ast.unparse(node.args[0]) if node.args else ""
261
+ if any(c in curve_str for c in ("SECP256R1", "SECP256K1", "SECP192R1", "SECP224R1")):
262
+ self._add(
263
+ lineno,
264
+ f"EC-{curve_str}",
265
+ "key-exchange/signature",
266
+ "CRITICAL",
267
+ False,
268
+ 0,
269
+ "256-bit and smaller EC curves excluded by NSA PP-26-4956 Action 1; replace with ML-KEM-1024 / ML-DSA-87.",
270
+ "QG-ECC-256",
271
+ )
272
+ elif "SECP384R1" in curve_str:
273
+ # Evaluated post-visit: compliant if combined in hybrid SecP384r1MLKEM1024
274
+ self._add(
275
+ lineno,
276
+ "ECDH-P384",
277
+ "key-agreement",
278
+ "INFO",
279
+ True, # adjusted in finalize() if ML-KEM-1024 is absent from module
280
+ 0,
281
+ "P-384 allowed as RFC 10024 SecP384r1MLKEM1024 hybrid component or temporary PP-26-4956 stopgap.",
282
+ "QG-ECC-384",
283
+ )
284
+ # Broken hashes & symmetric ciphers
285
+ elif resolved in {"hashlib.md5", "hashlib.sha1"} or resolved.endswith(("hashes.MD5", "hashes.SHA1")):
286
+ used_for_sec = _kw_bool(node, "usedforsecurity")
287
+ if used_for_sec is not False:
288
+ alg = "MD5" if "md5" in resolved.lower() else "SHA-1"
289
+ self._add(
290
+ lineno,
291
+ alg,
292
+ "hash",
293
+ "CRITICAL",
294
+ False,
295
+ 0,
296
+ f"{alg} is cryptographically broken; migrate to SHA-384 or SHA-512 per CNSA 2.0.",
297
+ "QG-HASH-001",
298
+ )
299
+ elif resolved.endswith(("hashes.SHA384", "hashes.SHA512", "hashlib.sha384", "hashlib.sha512")):
300
+ self._add(
301
+ lineno,
302
+ "SHA-384/512",
303
+ "hash",
304
+ "INFO",
305
+ True,
306
+ 5,
307
+ "CNSA 2.0 compliant hash primitive.",
308
+ "QG-HASH-384",
309
+ )
310
+ elif resolved.endswith("AESGCM"):
311
+ self._add(
312
+ lineno,
313
+ "AES-256-GCM",
314
+ "ae",
315
+ "INFO",
316
+ True,
317
+ 5,
318
+ "CNSA 2.0 compliant symmetric AEAD (verify 256-bit key length).",
319
+ "QG-SYM-256",
320
+ )
321
+ elif any(c in resolved for c in ("TripleDES", "Blowfish", "ARC4", "CAST5")):
322
+ self._add(
323
+ lineno,
324
+ resolved.split(".")[-1],
325
+ "block-cipher",
326
+ "CRITICAL",
327
+ False,
328
+ 0,
329
+ "Legacy weak/64-bit cipher banned; migrate to AES-256-GCM.",
330
+ "QG-SYM-WEAK",
331
+ )
332
+
333
+ self.generic_visit(node)
334
+
335
+ def visit_Attribute(self, node: ast.Attribute) -> None:
336
+ chain = _attr_chain(node)
337
+ if any(bad in chain for bad in ("PROTOCOL_TLSv1", "PROTOCOL_TLSv1_1", "PROTOCOL_TLSv1_2", "TLSVersion.TLSv1_2")):
338
+ if "TLSv1_3" not in chain:
339
+ self._add(
340
+ node.lineno,
341
+ chain,
342
+ "protocol",
343
+ "HIGH",
344
+ False,
345
+ 0,
346
+ "NSA PP-26-4956 Action 2 mandates TLS 1.3 or higher; deprecate TLS <= 1.2.",
347
+ "QG-TLS-12",
348
+ )
349
+ self.generic_visit(node)
350
+
351
+ def finalize(self) -> list[CryptoFinding]:
352
+ if not self.has_mlkem1024:
353
+ adjusted: list[CryptoFinding] = []
354
+ for f in self.findings:
355
+ if f.rule_id == "QG-ECC-384":
356
+ adjusted.append(
357
+ CryptoFinding(
358
+ file_path=f.file_path,
359
+ line_number=f.line_number,
360
+ algorithm="ECDH-P384-STANDALONE",
361
+ primitive=f.primitive,
362
+ severity="HIGH",
363
+ compliant_cnsa2=False,
364
+ compliant_eo14412=False,
365
+ compliant_india_cii=False,
366
+ nist_pqc_level=0,
367
+ evidence=f.evidence,
368
+ remediation="Standalone P-384 is an interim PP-26-4956 stopgap only; pair with ML-KEM-1024 (SecP384r1MLKEM1024).",
369
+ rule_id=f.rule_id,
370
+ )
371
+ )
372
+ else:
373
+ adjusted.append(f)
374
+ return adjusted
375
+ return self.findings
376
+
377
+
378
+ @dataclass(frozen=True)
379
+ class _RegexRule:
380
+ rule_id: str
381
+ pattern: re.Pattern[str]
382
+ algorithm: str
383
+ primitive: str
384
+ severity: str
385
+ compliant: bool
386
+ nist_level: int
387
+ remediation: str
388
+ extensions: frozenset[str]
389
+
390
+
391
+ _NON_PY_RULES: tuple[_RegexRule, ...] = (
392
+ _RegexRule(
393
+ rule_id="QG-EXT-RSA",
394
+ pattern=re.compile(r"\b(RSA_generate_key|generateKeyPairSync?\(\s*['\"]rsa['\"]|openssl\s+genrsa(?:\s+\S{1,64}){0,10}\s+(?:1024|2048)|modulusLength\s*:\s*(?:1024|2048))\b", re.IGNORECASE),
395
+ algorithm="RSA<=2048",
396
+ primitive="signature/key-exchange",
397
+ severity="CRITICAL",
398
+ compliant=False,
399
+ nist_level=0,
400
+ remediation="Replace RSA <= 2048 with ML-KEM-1024 / ML-DSA-87 (CNSA 2.0).",
401
+ extensions=frozenset({".c", ".cpp", ".h", ".js", ".ts", "Dockerfile", ".yml", ".yaml", ".conf"}),
402
+ ),
403
+ _RegexRule(
404
+ rule_id="QG-EXT-ECC256",
405
+ pattern=re.compile(r"\b(NID_X9_62_prime256v1|prime256v1|secp256r1|P-256|NID_X25519|X25519|Ed25519)\b"),
406
+ algorithm="ECC-256/X25519/Ed25519",
407
+ primitive="key-exchange/signature",
408
+ severity="CRITICAL",
409
+ compliant=False,
410
+ nist_level=0,
411
+ remediation="Excluded by NSA PP-26-4956 Action 1; migrate to SecP384r1MLKEM1024 / ML-DSA-87.",
412
+ extensions=frozenset({".c", ".cpp", ".h", ".js", ".ts", "Dockerfile", ".yml", ".yaml", ".conf"}),
413
+ ),
414
+ _RegexRule(
415
+ rule_id="QG-EXT-TLS12",
416
+ pattern=re.compile(r"(?:ssl_protocols\s+[^#\n]{0,256}TLSv1(?:\.1|\.2)?|TLSv1_2_method|minVersion\s*:\s*['\"]TLSv1\.[012]['\"])", re.IGNORECASE),
417
+ algorithm="TLS<=1.2",
418
+ primitive="protocol",
419
+ severity="HIGH",
420
+ compliant=False,
421
+ nist_level=0,
422
+ remediation="NSA PP-26-4956 Action 2 requires TLS 1.3 only.",
423
+ extensions=frozenset({".c", ".cpp", ".h", ".js", ".ts", ".conf", ".yml", ".yaml"}),
424
+ ),
425
+ _RegexRule(
426
+ rule_id="QG-EXT-WEAKHASH",
427
+ pattern=re.compile(r"\b(EVP_md5|EVP_sha1|createHash\(\s*['\"](?:md5|sha1)['\"]|DES-EDE3|3DES)\b", re.IGNORECASE),
428
+ algorithm="MD5/SHA-1/3DES",
429
+ primitive="hash/cipher",
430
+ severity="CRITICAL",
431
+ compliant=False,
432
+ nist_level=0,
433
+ remediation="Replace broken MD5/SHA-1/3DES with SHA-384/512 and AES-256-GCM.",
434
+ extensions=frozenset({".c", ".cpp", ".h", ".js", ".ts", "Dockerfile", ".conf"}),
435
+ ),
436
+ )
437
+
438
+
439
+ def _scan_python_file(path: Path, rel_path: str) -> list[CryptoFinding]:
440
+ src = path.read_text(encoding="utf-8", errors="replace")
441
+ lines = src.splitlines()
442
+ tree = ast.parse(src, filename=rel_path)
443
+ visitor = _PythonCryptoVisitor(rel_path, lines)
444
+ visitor.visit(tree)
445
+ return visitor.finalize()
446
+
447
+
448
+ def _scan_non_python_file(path: Path, rel_path: str) -> list[CryptoFinding]:
449
+ findings: list[CryptoFinding] = []
450
+ ext_key = path.name if path.name in SCAN_FILENAMES else path.suffix.lower()
451
+ lines = path.read_text(encoding="utf-8", errors="replace").splitlines()
452
+ for idx, line in enumerate(lines, start=1):
453
+ bounded_line = line[:16_384]
454
+ stripped = bounded_line.strip()
455
+ if not stripped or stripped.startswith(("#", "//", "/*")):
456
+ continue
457
+ for rule in _NON_PY_RULES:
458
+ if ext_key not in rule.extensions:
459
+ continue
460
+ if rule.pattern.search(bounded_line):
461
+ findings.append(
462
+ CryptoFinding(
463
+ file_path=rel_path,
464
+ line_number=idx,
465
+ algorithm=rule.algorithm,
466
+ primitive=rule.primitive,
467
+ severity=rule.severity,
468
+ compliant_cnsa2=rule.compliant,
469
+ compliant_eo14412=rule.compliant,
470
+ compliant_india_cii=rule.compliant,
471
+ nist_pqc_level=rule.nist_level,
472
+ evidence=stripped[:120],
473
+ remediation=rule.remediation,
474
+ rule_id=rule.rule_id,
475
+ )
476
+ )
477
+ return findings
478
+
479
+
480
+ def audit_path(target: str | Path) -> CBOMReport:
481
+ """Recursively scan a file or directory and return a CBOMReport."""
482
+ root = Path(target).resolve()
483
+ files: list[Path] = []
484
+ if root.is_file():
485
+ files = [root]
486
+ base = root.parent
487
+ elif root.is_dir():
488
+ base = root
489
+ for p in sorted(root.rglob("*")):
490
+ if any(part in SKIP_DIRS for part in p.parts):
491
+ continue
492
+ if p.is_file() and (p.suffix.lower() in SCAN_EXTENSIONS or p.name in SCAN_FILENAMES):
493
+ files.append(p)
494
+ else:
495
+ raise FileNotFoundError(f"Audit target does not exist: {target}")
496
+
497
+ report = CBOMReport(target_path=str(root), scanned_files=len(files))
498
+ for fpath in files:
499
+ rel = str(fpath.relative_to(base)) if root.is_dir() else fpath.name
500
+ try:
501
+ if fpath.suffix.lower() == ".py":
502
+ report.findings.extend(_scan_python_file(fpath, rel))
503
+ else:
504
+ report.findings.extend(_scan_non_python_file(fpath, rel))
505
+ except (SyntaxError, RecursionError, ValueError) as exc:
506
+ report.errors.append(f"ParseError in {rel}: {exc}")
507
+ except Exception as exc:
508
+ report.errors.append(f"Error scanning {rel}: {exc}")
509
+ return report
510
+
511
+
512
+ def generate_cyclonedx_cbom(report: CBOMReport) -> dict[str, Any]:
513
+ """Serialize CBOMReport into CycloneDX v1.6 JSON mapped to CNSA 2.0, EO 14412 & India CII."""
514
+ components: list[dict[str, Any]] = []
515
+ for idx, f in enumerate(report.findings, start=1):
516
+ components.append(
517
+ {
518
+ "bom-ref": f"crypto-{idx:04d}-{f.rule_id}",
519
+ "type": "cryptographic-asset",
520
+ "name": f.algorithm,
521
+ "evidence": {
522
+ "occurrences": [
523
+ {
524
+ "location": f"{f.file_path}:{f.line_number}",
525
+ "line": f.line_number,
526
+ "additionalContext": f.evidence,
527
+ }
528
+ ]
529
+ },
530
+ "cryptoProperties": {
531
+ "assetType": "algorithm",
532
+ "algorithmProperties": {
533
+ "primitive": f.primitive,
534
+ "nistQuantumSecurityLevel": f.nist_pqc_level,
535
+ },
536
+ },
537
+ "properties": [
538
+ {"name": "quantumguard:rule_id", "value": f.rule_id},
539
+ {"name": "quantumguard:severity", "value": f.severity},
540
+ {"name": "quantumguard:cnsa2_compliant", "value": str(f.compliant_cnsa2).lower()},
541
+ {"name": "quantumguard:eo14412_compliant", "value": str(f.compliant_eo14412).lower()},
542
+ {"name": "quantumguard:india_cii_compliant", "value": str(f.compliant_india_cii).lower()},
543
+ {"name": "quantumguard:remediation", "value": f.remediation},
544
+ ],
545
+ }
546
+ )
547
+
548
+ violations = report.violations
549
+ return {
550
+ "bomFormat": "CycloneDX",
551
+ "specVersion": "1.6",
552
+ "serialNumber": f"urn:uuid:{uuid.uuid4()}",
553
+ "version": 1,
554
+ "metadata": {
555
+ "timestamp": datetime.now(timezone.utc).isoformat(),
556
+ "tools": [{"vendor": "Runtime-Slayers", "name": "quantumguard", "version": "0.1.0"}],
557
+ "component": {"type": "application", "name": Path(report.target_path).name},
558
+ },
559
+ "quantumguard_policy_verdict": {
560
+ "status": "FAIL" if violations else "PASS",
561
+ "exit_code": report.exit_code,
562
+ "scanned_files": report.scanned_files,
563
+ "total_crypto_assets": len(report.findings),
564
+ "violation_count": len(violations),
565
+ "compliant_asset_count": len(report.compliant_assets),
566
+ "severity_breakdown": report.summary_counts(),
567
+ "frameworks": {
568
+ "NSA_CNSA_2_0_Jan2027_PP26_4956": "FAIL" if violations else "PASS",
569
+ "US_EO_14412_Dec2030_2031": "FAIL" if violations else "PASS",
570
+ "India_CERT_In_DST_CII_FY2027_28": "FAIL" if violations else "PASS",
571
+ },
572
+ },
573
+ "components": components,
574
+ "findings_raw": [asdict(f) for f in report.findings],
575
+ }
576
+
577
+
578
+ def write_cbom_json(report: CBOMReport, output_path: str | Path) -> Path:
579
+ dest = Path(output_path)
580
+ dest.parent.mkdir(parents=True, exist_ok=True)
581
+ payload = generate_cyclonedx_cbom(report)
582
+ dest.write_text(json.dumps(payload, indent=2), encoding="utf-8")
583
+ return dest