pqscan 0.4.1__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.
pqc_scan/cbom.py ADDED
@@ -0,0 +1,199 @@
1
+ """CycloneDX Cryptographic Bill of Materials export.
2
+
3
+ ASD names the CBOM in two ISM controls:
4
+
5
+ ISM-2083 "A cryptographic bill of materials is produced and made available to consumers
6
+ of software."
7
+ ISM-2082 "If a cryptographic bill of materials is available for imported third-party
8
+ software components, it is used during software development..."
9
+
10
+ Both sit in the Guidelines for software development, so they bind an organisation as a
11
+ software PRODUCER. This exporter does something adjacent and, for a scanner, more useful: it
12
+ builds a CBOM from what endpoints were observed to actually negotiate, rather than from what
13
+ a source tree declares. Those are different claims and the document says which one it is -
14
+ every component here carries evidence of observation, not a code reference.
15
+
16
+ Format: CycloneDX 1.6 with the `cryptographic-asset` component type and the `cryptoProperties`
17
+ block. Three kinds of component are emitted: algorithms (with an `assetType` of `algorithm`),
18
+ protocols, and certificates. Certificates are deduplicated by SHA-256 fingerprint and list
19
+ every endpoint that served them, because one certificate commonly serves many.
20
+ """
21
+ from __future__ import annotations
22
+
23
+ import datetime as dt
24
+ import json
25
+ from typing import Any
26
+
27
+ from pqc_scan.models import CertificateData, Classification, HostFinding
28
+
29
+ SPEC_VERSION = "1.6"
30
+
31
+ # NIST security category per FIPS 203/204, for the parameter sets the ISM names.
32
+ NIST_CATEGORIES = {
33
+ "ML-KEM-512": 1, "ML-KEM-768": 3, "ML-KEM-1024": 5,
34
+ "ML-DSA-44": 2, "ML-DSA-65": 3, "ML-DSA-87": 5,
35
+ }
36
+
37
+ # CycloneDX primitive for each role a scanner observes.
38
+ ROLE_PRIMITIVES = {
39
+ "key_exchange": "kem",
40
+ "signature": "signature",
41
+ "cipher": "ae",
42
+ "mac": "mac",
43
+ "prf": "kdf",
44
+ }
45
+
46
+
47
+ def _bom_ref(*parts: str) -> str:
48
+ return "crypto/" + "/".join(p.replace(" ", "-") for p in parts if p)
49
+
50
+
51
+ def _algorithm_component(name: str, role: str, classification: str, in_use: bool) -> dict[str, Any]:
52
+ upper = name.upper()
53
+ category = next((v for k, v in NIST_CATEGORIES.items() if k.replace("-", "") in upper.replace("-", "").replace("_", "")), None)
54
+ properties = [
55
+ {"name": "pqscan:ism-classification", "value": classification},
56
+ # "observed" distinguishes what an endpoint actually negotiated from what it merely
57
+ # advertised. A CBOM built from a source tree cannot make that distinction at all.
58
+ {"name": "pqscan:observed", "value": "negotiated" if in_use else "offered"},
59
+ ]
60
+ crypto: dict[str, Any] = {
61
+ "assetType": "algorithm",
62
+ "algorithmProperties": {
63
+ "primitive": ROLE_PRIMITIVES.get(role, "other"),
64
+ "executionEnvironment": "unknown",
65
+ "implementationPlatform": "unknown",
66
+ "cryptoFunctions": ["keygen"] if role == "key_exchange" else ["sign"] if role == "signature" else ["encrypt"],
67
+ },
68
+ }
69
+ if category:
70
+ crypto["algorithmProperties"]["nistQuantumSecurityLevel"] = category
71
+ return {
72
+ "type": "cryptographic-asset",
73
+ "bom-ref": _bom_ref("algorithm", role, name),
74
+ "name": name,
75
+ "cryptoProperties": crypto,
76
+ "properties": properties,
77
+ }
78
+
79
+
80
+ def _protocol_component(finding: HostFinding) -> dict[str, Any] | None:
81
+ version = finding.version or finding.tls_version
82
+ if not version:
83
+ return None
84
+ family = {"tls": "tls", "ssh": "ssh", "ipsec": "ipsec"}.get(finding.service)
85
+ if not family:
86
+ return None
87
+ return {
88
+ "type": "cryptographic-asset",
89
+ "bom-ref": _bom_ref("protocol", finding.target.hostname, str(finding.target.port), version),
90
+ "name": f"{version} on {finding.target.hostname}:{finding.target.port}",
91
+ "cryptoProperties": {
92
+ "assetType": "protocol",
93
+ "protocolProperties": {"type": family, "version": version},
94
+ },
95
+ "properties": [
96
+ {"name": "pqscan:endpoint", "value": f"{finding.target.hostname}:{finding.target.port}"},
97
+ {"name": "pqscan:pq-readiness", "value": finding.pq_readiness},
98
+ {"name": "pqscan:system", "value": finding.target.system_name},
99
+ {"name": "pqscan:classification", "value": finding.target.classification},
100
+ ],
101
+ }
102
+
103
+
104
+ def _certificate_component(certificate: CertificateData) -> dict[str, Any]:
105
+ properties = [
106
+ {"name": "pqscan:signature-algorithm", "value": certificate.sig_algo or "unknown"},
107
+ {"name": "pqscan:public-key-classification", "value": _value(certificate.pub_key_classification)},
108
+ {"name": "pqscan:signature-classification", "value": _value(certificate.sig_classification)},
109
+ ]
110
+ # One certificate commonly serves many endpoints; the usage list is what makes a CBOM
111
+ # actionable, because it says what breaks when this key has to be replaced.
112
+ properties.extend({"name": "pqscan:used-by", "value": usage} for usage in certificate.usages)
113
+ return {
114
+ "type": "cryptographic-asset",
115
+ "bom-ref": _bom_ref("certificate", certificate.fingerprint_sha256),
116
+ "name": certificate.subject_cn or certificate.fingerprint_sha256[:16],
117
+ "cryptoProperties": {
118
+ "assetType": "certificate",
119
+ "certificateProperties": {
120
+ "subjectName": certificate.subject_cn or "",
121
+ "issuerName": certificate.issuer or "",
122
+ "notValidBefore": _isoformat(certificate.not_before),
123
+ "notValidAfter": _isoformat(certificate.not_after),
124
+ "signatureAlgorithmRef": _bom_ref("algorithm", "signature", certificate.sig_algo or "unknown"),
125
+ "subjectPublicKeyRef": _bom_ref("algorithm", "public-key", certificate.pub_key_algo or "unknown"),
126
+ "certificateFormat": "X.509",
127
+ },
128
+ },
129
+ "properties": properties,
130
+ }
131
+
132
+
133
+ def _value(item: Any) -> str:
134
+ return item.value if isinstance(item, Classification) else str(item)
135
+
136
+
137
+ def _isoformat(value: Any) -> str:
138
+ if value is None:
139
+ return ""
140
+ return value.isoformat() if hasattr(value, "isoformat") else str(value)
141
+
142
+
143
+ def build_cbom(
144
+ findings: list[HostFinding],
145
+ certificates: dict[str, CertificateData],
146
+ rules_version: str = "unknown",
147
+ operator: str = "unknown",
148
+ engagement: str = "unknown",
149
+ ) -> dict[str, Any]:
150
+ components: list[dict[str, Any]] = []
151
+ seen: set[str] = set()
152
+
153
+ def add(component: dict[str, Any] | None) -> None:
154
+ if component and component["bom-ref"] not in seen:
155
+ seen.add(component["bom-ref"])
156
+ components.append(component)
157
+
158
+ for finding in findings:
159
+ add(_protocol_component(finding))
160
+ for role, entries in (finding.algorithms or {}).items():
161
+ for entry in entries:
162
+ add(_algorithm_component(
163
+ entry["name"], role, entry.get("classification", "REVIEW"), entry.get("in_use", False)
164
+ ))
165
+ # The TLS path records its negotiated group and cipher outside `algorithms`, so they
166
+ # would otherwise be missing from the inventory entirely.
167
+ if finding.negotiated_group and finding.negotiated_group not in ("unknown", "n/a"):
168
+ add(_algorithm_component(finding.negotiated_group, "key_exchange", "REVIEW", True))
169
+ if finding.cipher_suite:
170
+ add(_algorithm_component(finding.cipher_suite, "cipher", "REVIEW", True))
171
+
172
+ for certificate in certificates.values():
173
+ add(_certificate_component(certificate))
174
+
175
+ return {
176
+ "bomFormat": "CycloneDX",
177
+ "specVersion": SPEC_VERSION,
178
+ "version": 1,
179
+ "metadata": {
180
+ "timestamp": dt.datetime.now(dt.UTC).isoformat(),
181
+ "tools": {"components": [{"type": "application", "name": "pqscan", "publisher": "Nayef Alharbi"}]},
182
+ "properties": [
183
+ # State the provenance of the claim. A CBOM from a source scan and a CBOM
184
+ # from observed traffic are different evidence, and a reader has to know which.
185
+ {"name": "pqscan:evidence", "value": "observed-network-negotiation"},
186
+ {"name": "pqscan:ruleset", "value": rules_version},
187
+ {"name": "pqscan:ism-controls", "value": "ISM-2082, ISM-2083"},
188
+ {"name": "pqscan:operator", "value": operator},
189
+ {"name": "pqscan:engagement", "value": engagement},
190
+ ],
191
+ },
192
+ "components": components,
193
+ }
194
+
195
+
196
+ def write_cbom(path: str, document: dict[str, Any]) -> None:
197
+ with open(path, "w", encoding="utf-8") as handle:
198
+ json.dump(document, handle, indent=2, sort_keys=False)
199
+ handle.write("\n")