pqc-compass 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.
- pqc_compass/__init__.py +5 -0
- pqc_compass/cli.py +161 -0
- pqc_compass/model.py +53 -0
- pqc_compass/output/__init__.py +188 -0
- pqc_compass/probes/__init__.py +2 -0
- pqc_compass/probes/certs.py +184 -0
- pqc_compass/probes/configs.py +202 -0
- pqc_compass/probes/ssh.py +122 -0
- pqc_compass/probes/tls.py +334 -0
- pqc_compass/rules/__init__.py +117 -0
- pqc_compass/rules/default.yaml +186 -0
- pqc_compass-0.1.0.dist-info/METADATA +180 -0
- pqc_compass-0.1.0.dist-info/RECORD +17 -0
- pqc_compass-0.1.0.dist-info/WHEEL +5 -0
- pqc_compass-0.1.0.dist-info/entry_points.txt +2 -0
- pqc_compass-0.1.0.dist-info/licenses/LICENSE +661 -0
- pqc_compass-0.1.0.dist-info/top_level.txt +1 -0
pqc_compass/__init__.py
ADDED
pqc_compass/cli.py
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
# SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
# Copyright (c) 2026 Forex Robotics Co., Ltd.
|
|
3
|
+
"""Command line interface.
|
|
4
|
+
|
|
5
|
+
pqc-compass scan example.com tls://mail.example.com:465 ssh://10.0.0.5:22
|
|
6
|
+
pqc-compass local # this host's sshd / nginx / apache / openssl config
|
|
7
|
+
pqc-compass files /etc/letsencrypt # certificate files
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import argparse
|
|
13
|
+
import sys
|
|
14
|
+
import time
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
from . import __version__
|
|
18
|
+
from .model import LEVEL_ORDER, Observation
|
|
19
|
+
from .output import to_cbom, to_json, to_markdown
|
|
20
|
+
from .probes import configs, ssh, tls
|
|
21
|
+
from .probes.certs import scan_cert_files
|
|
22
|
+
from .rules import RuleSet, posture
|
|
23
|
+
|
|
24
|
+
SSH_PORTS = {22, 2222, 22222}
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def parse_target(spec: str) -> tuple[str, str, int]:
|
|
28
|
+
"""Return (scheme, host, port). Accepts tls://h:p, ssh://h:p, h:p, h, [v6]:p."""
|
|
29
|
+
scheme = None
|
|
30
|
+
if "://" in spec:
|
|
31
|
+
scheme, spec = spec.split("://", 1)
|
|
32
|
+
scheme = scheme.lower()
|
|
33
|
+
if scheme in ("https",):
|
|
34
|
+
scheme = "tls"
|
|
35
|
+
spec = spec.rstrip("/")
|
|
36
|
+
if spec.startswith("["):
|
|
37
|
+
host, _, rest = spec[1:].partition("]")
|
|
38
|
+
port = int(rest[1:]) if rest.startswith(":") else None
|
|
39
|
+
elif spec.count(":") == 1:
|
|
40
|
+
host, p = spec.split(":")
|
|
41
|
+
port = int(p)
|
|
42
|
+
else:
|
|
43
|
+
host, port = spec, None
|
|
44
|
+
if scheme is None:
|
|
45
|
+
scheme = "ssh" if port in SSH_PORTS else "tls"
|
|
46
|
+
if port is None:
|
|
47
|
+
port = 22 if scheme == "ssh" else 443
|
|
48
|
+
if scheme not in ("tls", "ssh"):
|
|
49
|
+
raise ValueError(f"unsupported scheme: {scheme}")
|
|
50
|
+
return scheme, host, port
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _collect_network(targets: list[str], args) -> tuple[list[Observation], list[str]]:
|
|
54
|
+
obs: list[Observation] = []
|
|
55
|
+
errors: list[str] = []
|
|
56
|
+
for i, spec in enumerate(targets):
|
|
57
|
+
if i:
|
|
58
|
+
time.sleep(args.delay)
|
|
59
|
+
try:
|
|
60
|
+
scheme, host, port = parse_target(spec)
|
|
61
|
+
except ValueError as e:
|
|
62
|
+
errors.append(f"{spec}: {e}")
|
|
63
|
+
continue
|
|
64
|
+
if not args.quiet:
|
|
65
|
+
print(f"[*] {scheme}://{host}:{port}", file=sys.stderr)
|
|
66
|
+
if scheme == "tls":
|
|
67
|
+
rep = tls.probe_tls(host, port, timeout=args.timeout, delay=args.delay)
|
|
68
|
+
obs += tls.observations(rep)
|
|
69
|
+
errors += [f"{rep.target}: {e}" for e in rep.errors]
|
|
70
|
+
else:
|
|
71
|
+
rep = ssh.probe_ssh(host, port, timeout=args.timeout)
|
|
72
|
+
obs += ssh.observations(rep)
|
|
73
|
+
errors += [f"{rep.target}: {e}" for e in rep.errors]
|
|
74
|
+
return obs, errors
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _threshold_hit(findings, post, threshold: str) -> bool:
|
|
78
|
+
limit = LEVEL_ORDER[threshold]
|
|
79
|
+
levels = [p["overall"] for p in post.values() if p["overall"]]
|
|
80
|
+
levels += [f.level for f in findings
|
|
81
|
+
if f.observation.role in ("negotiated", "in-use", "configured", "installed")
|
|
82
|
+
or f.level == "L0"]
|
|
83
|
+
return any(lv in LEVEL_ORDER and LEVEL_ORDER[lv] <= limit for lv in levels if lv != "INFO")
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def main(argv: list[str] | None = None) -> int:
|
|
87
|
+
ap = argparse.ArgumentParser(prog="pqc-compass",
|
|
88
|
+
description="Post-quantum crypto inventory scanner (PQC Compass)")
|
|
89
|
+
ap.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
|
|
90
|
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
91
|
+
|
|
92
|
+
common = argparse.ArgumentParser(add_help=False)
|
|
93
|
+
common.add_argument("-f", "--format", choices=["md", "json", "cbom"], default="md")
|
|
94
|
+
common.add_argument("-o", "--output", help="write to file instead of stdout")
|
|
95
|
+
common.add_argument("--lang", choices=["ja", "en"], default="ja")
|
|
96
|
+
common.add_argument("--rules", help="custom rules YAML (default: bundled rules)")
|
|
97
|
+
common.add_argument("--fail-on", choices=["L0", "L1", "L2"],
|
|
98
|
+
help="exit with status 2 if anything at or below this level is in use")
|
|
99
|
+
common.add_argument("--exposure", choices=["internet", "internal"])
|
|
100
|
+
common.add_argument("--data-lifetime", choices=["long", "short"])
|
|
101
|
+
common.add_argument("--replaceability", choices=["hard", "normal"])
|
|
102
|
+
common.add_argument("-q", "--quiet", action="store_true")
|
|
103
|
+
|
|
104
|
+
s = sub.add_parser("scan", parents=[common], help="probe TLS/SSH endpoints over the network")
|
|
105
|
+
s.add_argument("targets", nargs="*", help="host, host:port, tls://host:port, ssh://host:port")
|
|
106
|
+
s.add_argument("-T", "--targets-file", help="file with one target per line")
|
|
107
|
+
s.add_argument("--timeout", type=float, default=5.0)
|
|
108
|
+
s.add_argument("--delay", type=float, default=0.2, help="seconds between probes (rate limit)")
|
|
109
|
+
|
|
110
|
+
lo = sub.add_parser("local", parents=[common], help="scan this host's crypto configuration")
|
|
111
|
+
lo.add_argument("--root", default="", help="treat this directory as / (for images or mounts)")
|
|
112
|
+
lo.add_argument("--no-libraries", action="store_true", help="skip openssl/ssh version checks")
|
|
113
|
+
|
|
114
|
+
fi = sub.add_parser("files", parents=[common], help="scan certificate files or directories")
|
|
115
|
+
fi.add_argument("paths", nargs="+")
|
|
116
|
+
|
|
117
|
+
args = ap.parse_args(argv)
|
|
118
|
+
|
|
119
|
+
errors: list[str] = []
|
|
120
|
+
if args.cmd == "scan":
|
|
121
|
+
targets = list(args.targets)
|
|
122
|
+
if args.targets_file:
|
|
123
|
+
targets += [ln.strip() for ln in Path(args.targets_file).read_text().splitlines()
|
|
124
|
+
if ln.strip() and not ln.lstrip().startswith("#")]
|
|
125
|
+
if not targets:
|
|
126
|
+
ap.error("no targets given")
|
|
127
|
+
obs, errors = _collect_network(targets, args)
|
|
128
|
+
elif args.cmd == "local":
|
|
129
|
+
obs = configs.scan_local(args.root, include_libraries=not args.no_libraries and not args.root)
|
|
130
|
+
else:
|
|
131
|
+
obs = []
|
|
132
|
+
for p in args.paths:
|
|
133
|
+
obs += scan_cert_files(Path(p))
|
|
134
|
+
|
|
135
|
+
context = {k: v for k, v in (("exposure", args.exposure), ("data_lifetime", args.data_lifetime),
|
|
136
|
+
("replaceability", args.replaceability)) if v}
|
|
137
|
+
rules = RuleSet.load(args.rules)
|
|
138
|
+
findings = rules.evaluate(obs, lang=args.lang, context=context)
|
|
139
|
+
post = posture(findings)
|
|
140
|
+
|
|
141
|
+
if args.format == "json":
|
|
142
|
+
text = to_json(findings, post, errors)
|
|
143
|
+
elif args.format == "cbom":
|
|
144
|
+
text = to_cbom(findings)
|
|
145
|
+
else:
|
|
146
|
+
text = to_markdown(findings, post, errors, lang=args.lang)
|
|
147
|
+
|
|
148
|
+
if args.output:
|
|
149
|
+
Path(args.output).write_text(text, encoding="utf-8")
|
|
150
|
+
if not args.quiet:
|
|
151
|
+
print(f"[+] wrote {args.output}", file=sys.stderr)
|
|
152
|
+
else:
|
|
153
|
+
sys.stdout.write(text)
|
|
154
|
+
|
|
155
|
+
if args.fail_on and _threshold_hit(findings, post, args.fail_on):
|
|
156
|
+
return 2
|
|
157
|
+
return 0
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
if __name__ == "__main__":
|
|
161
|
+
sys.exit(main())
|
pqc_compass/model.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
# SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
# Copyright (c) 2026 Forex Robotics Co., Ltd.
|
|
3
|
+
"""Common data model: every collector emits Observations, the rules engine turns them into Findings."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from dataclasses import asdict, dataclass, field
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
# Asset categories
|
|
11
|
+
KEX = "key-exchange"
|
|
12
|
+
SIGNATURE = "signature"
|
|
13
|
+
HOSTKEY = "host-key"
|
|
14
|
+
CERTIFICATE = "certificate"
|
|
15
|
+
PROTOCOL = "protocol-version"
|
|
16
|
+
CIPHER = "cipher"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass
|
|
20
|
+
class Observation:
|
|
21
|
+
"""A single piece of crypto observed on a target, before judgement."""
|
|
22
|
+
|
|
23
|
+
target: str # e.g. "tls://example.com:443"
|
|
24
|
+
protocol: str # "tls", "ssh", "file"
|
|
25
|
+
category: str # one of the category constants above
|
|
26
|
+
algorithm: str # canonical name, e.g. "X25519MLKEM768", "ecdsa-sha2-nistp256"
|
|
27
|
+
role: str = "supported" # "negotiated" (what a modern client gets), "supported", "offered", "in-use"
|
|
28
|
+
detail: dict[str, Any] = field(default_factory=dict)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass
|
|
32
|
+
class Finding:
|
|
33
|
+
observation: Observation
|
|
34
|
+
level: str # "L0" .. "L3", or "INFO" for non-public-key items
|
|
35
|
+
family: str # classic / lattice / hash / code / hybrid-lattice / symmetric / unknown
|
|
36
|
+
score: float # priority score, higher = fix first
|
|
37
|
+
note: str = ""
|
|
38
|
+
recommendation: str = ""
|
|
39
|
+
|
|
40
|
+
def to_dict(self) -> dict[str, Any]:
|
|
41
|
+
d = asdict(self)
|
|
42
|
+
d.update(d.pop("observation"))
|
|
43
|
+
return d
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
LEVEL_ORDER = {"L0": 0, "L1": 1, "L2": 2, "L3": 3, "INFO": 4}
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def worst_level(levels: list[str]) -> str | None:
|
|
50
|
+
real = [lv for lv in levels if lv in ("L0", "L1", "L2", "L3")]
|
|
51
|
+
if not real:
|
|
52
|
+
return None
|
|
53
|
+
return min(real, key=lambda lv: LEVEL_ORDER[lv])
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
# SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
# Copyright (c) 2026 Forex Robotics Co., Ltd.
|
|
3
|
+
"""Output writers: JSON, CycloneDX 1.6 CBOM, Markdown report (ja/en)."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import json
|
|
8
|
+
import uuid
|
|
9
|
+
from collections import Counter
|
|
10
|
+
from datetime import datetime, timezone
|
|
11
|
+
|
|
12
|
+
from .. import __version__
|
|
13
|
+
from ..model import CERTIFICATE, KEX, PROTOCOL, Finding
|
|
14
|
+
|
|
15
|
+
LEVELS = ["L0", "L1", "L2", "L3", "INFO"]
|
|
16
|
+
|
|
17
|
+
# Bump only on a breaking change to the JSON output (see docs/json-schema.md).
|
|
18
|
+
JSON_SCHEMA_VERSION = 1
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _now() -> str:
|
|
22
|
+
return datetime.now(timezone.utc).isoformat(timespec="seconds")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
# --- JSON ---------------------------------------------------------------------
|
|
26
|
+
|
|
27
|
+
def to_json(findings: list[Finding], posture: dict, errors: list[str]) -> str:
|
|
28
|
+
return json.dumps({
|
|
29
|
+
"schema_version": JSON_SCHEMA_VERSION,
|
|
30
|
+
"tool": {"name": "pqc-compass", "version": __version__},
|
|
31
|
+
"generated": _now(),
|
|
32
|
+
"summary": dict(Counter(f.level for f in findings)),
|
|
33
|
+
"posture": posture,
|
|
34
|
+
"findings": [f.to_dict() for f in findings],
|
|
35
|
+
"errors": errors,
|
|
36
|
+
}, ensure_ascii=False, indent=2)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
# --- CycloneDX CBOM -------------------------------------------------------------
|
|
40
|
+
|
|
41
|
+
_NIST_LEVEL = {
|
|
42
|
+
"MLKEM512": 1, "ML-KEM-512": 1, "MLKEM768": 3, "ML-KEM-768": 3, "MLKEM1024": 5, "ML-KEM-1024": 5,
|
|
43
|
+
"X25519MLKEM768": 3, "SecP256r1MLKEM768": 3, "SecP384r1MLKEM1024": 5, "mlkem768x25519-sha256": 3,
|
|
44
|
+
"ML-DSA-44": 2, "ML-DSA-65": 3, "ML-DSA-87": 5,
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _primitive(f: Finding) -> str:
|
|
49
|
+
cat, fam = f.observation.category, f.family
|
|
50
|
+
if cat == KEX:
|
|
51
|
+
return "kem" if "lattice" in fam or fam in ("code", "hybrid-code") else "key-agree"
|
|
52
|
+
if cat in ("signature", "host-key", CERTIFICATE):
|
|
53
|
+
return "signature"
|
|
54
|
+
if cat == "cipher":
|
|
55
|
+
return "ae" if "gcm" in f.observation.algorithm.lower() or "poly1305" in f.observation.algorithm else "block-cipher"
|
|
56
|
+
return "other"
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _quantum_level(f: Finding) -> int:
|
|
60
|
+
alg = f.observation.algorithm
|
|
61
|
+
if alg in _NIST_LEVEL:
|
|
62
|
+
return _NIST_LEVEL[alg]
|
|
63
|
+
if alg.startswith("SLH-DSA"):
|
|
64
|
+
return {"128": 1, "192": 3, "256": 5}.get(alg.split("-")[-1][:3], 1)
|
|
65
|
+
return 0 if f.family == "classic" else 1 if f.level in ("L2", "L3") else 0
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def to_cbom(findings: list[Finding]) -> str:
|
|
69
|
+
groups: dict[tuple[str, str], list[Finding]] = {}
|
|
70
|
+
for f in findings:
|
|
71
|
+
if f.observation.category in ("note",):
|
|
72
|
+
continue
|
|
73
|
+
groups.setdefault((f.observation.category, f.observation.algorithm), []).append(f)
|
|
74
|
+
|
|
75
|
+
components = []
|
|
76
|
+
for (cat, alg), fs in sorted(groups.items()):
|
|
77
|
+
top = max(fs, key=lambda x: x.score)
|
|
78
|
+
ref = f"crypto/{cat}/{alg}"
|
|
79
|
+
comp: dict = {"type": "cryptographic-asset", "bom-ref": ref, "name": alg}
|
|
80
|
+
if cat == PROTOCOL:
|
|
81
|
+
proto, _, ver = alg.partition("TLS")
|
|
82
|
+
comp["cryptoProperties"] = {"assetType": "protocol",
|
|
83
|
+
"protocolProperties": {"type": "tls", "version": ver or alg}}
|
|
84
|
+
elif cat == CERTIFICATE:
|
|
85
|
+
d = top.observation.detail
|
|
86
|
+
comp["cryptoProperties"] = {"assetType": "certificate", "certificateProperties": {
|
|
87
|
+
"subjectName": d.get("subject", ""), "issuerName": d.get("issuer", ""),
|
|
88
|
+
"notValidAfter": d.get("not_after", ""), "certificateFormat": "X.509"}}
|
|
89
|
+
elif cat == "library":
|
|
90
|
+
comp["type"] = "library"
|
|
91
|
+
name, _, ver = alg.partition("-")
|
|
92
|
+
comp["name"], comp["version"] = name, ver
|
|
93
|
+
else:
|
|
94
|
+
comp["cryptoProperties"] = {"assetType": "algorithm", "algorithmProperties": {
|
|
95
|
+
"primitive": _primitive(top),
|
|
96
|
+
"nistQuantumSecurityLevel": _quantum_level(top)}}
|
|
97
|
+
comp["evidence"] = {"occurrences": [
|
|
98
|
+
{"location": f.observation.target,
|
|
99
|
+
"additionalContext": f.observation.role}
|
|
100
|
+
for f in fs]}
|
|
101
|
+
comp["properties"] = [
|
|
102
|
+
{"name": "pqc-compass:level", "value": top.level},
|
|
103
|
+
{"name": "pqc-compass:family", "value": top.family},
|
|
104
|
+
{"name": "pqc-compass:score", "value": str(top.score)},
|
|
105
|
+
{"name": "pqc-compass:category", "value": cat},
|
|
106
|
+
]
|
|
107
|
+
components.append(comp)
|
|
108
|
+
|
|
109
|
+
return json.dumps({
|
|
110
|
+
"bomFormat": "CycloneDX",
|
|
111
|
+
"specVersion": "1.6",
|
|
112
|
+
"serialNumber": f"urn:uuid:{uuid.uuid4()}",
|
|
113
|
+
"version": 1,
|
|
114
|
+
"metadata": {
|
|
115
|
+
"timestamp": _now(),
|
|
116
|
+
"tools": {"components": [{"type": "application", "name": "pqc-compass",
|
|
117
|
+
"version": __version__}]},
|
|
118
|
+
},
|
|
119
|
+
"components": components,
|
|
120
|
+
}, ensure_ascii=False, indent=2)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
# --- Markdown report -------------------------------------------------------------
|
|
124
|
+
|
|
125
|
+
_T = {
|
|
126
|
+
"ja": {
|
|
127
|
+
"title": "PQC Compass 暗号棚卸しレポート",
|
|
128
|
+
"generated": "作成日時", "summary": "サマリー", "level": "レベル", "count": "件数",
|
|
129
|
+
"posture": "対象ごとの状態(最新クライアントで接続した場合)",
|
|
130
|
+
"target": "対象", "kex": "鍵交換", "auth": "認証", "overall": "総合", "weak": "弱い設定",
|
|
131
|
+
"top": "優先して対応すべき項目", "alg": "方式", "cat": "分類", "role": "状態",
|
|
132
|
+
"score": "優先度", "note": "説明", "rec": "推奨", "all": "全検出結果", "errors": "エラー",
|
|
133
|
+
"legend": "L0:古典暗号としても弱い/L1:古典暗号のみ(量子に弱い)/"
|
|
134
|
+
"L2:PQ対応だがPQ側は格子のみ/L3:格子以外のPQを含む",
|
|
135
|
+
"none": "なし",
|
|
136
|
+
},
|
|
137
|
+
"en": {
|
|
138
|
+
"title": "PQC Compass crypto inventory report",
|
|
139
|
+
"generated": "Generated", "summary": "Summary", "level": "Level", "count": "Count",
|
|
140
|
+
"posture": "Posture per target (as seen by a modern client)",
|
|
141
|
+
"target": "Target", "kex": "Key exchange", "auth": "Authentication", "overall": "Overall",
|
|
142
|
+
"weak": "Weak options", "top": "Fix first", "alg": "Algorithm", "cat": "Category",
|
|
143
|
+
"role": "Role", "score": "Score", "note": "Note", "rec": "Recommendation",
|
|
144
|
+
"all": "All findings", "errors": "Errors",
|
|
145
|
+
"legend": "L0: weak even classically / L1: classical only (quantum-vulnerable) / "
|
|
146
|
+
"L2: PQ, lattice-only / L3: includes non-lattice PQ",
|
|
147
|
+
"none": "none",
|
|
148
|
+
},
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _esc(s: str) -> str:
|
|
153
|
+
return str(s).replace("|", "\\|")
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def to_markdown(findings: list[Finding], posture: dict, errors: list[str], lang: str = "ja") -> str:
|
|
157
|
+
t = _T.get(lang, _T["en"])
|
|
158
|
+
c = Counter(f.level for f in findings)
|
|
159
|
+
out = [f"# {t['title']}", "", f"{t['generated']}: {_now()}", "", f"> {t['legend']}", "",
|
|
160
|
+
f"## {t['summary']}", "", f"| {t['level']} | {t['count']} |", "| --- | --- |"]
|
|
161
|
+
out += [f"| {lv} | {c.get(lv, 0)} |" for lv in LEVELS]
|
|
162
|
+
out += ["", f"## {t['posture']}", "",
|
|
163
|
+
f"| {t['target']} | {t['kex']} | {t['auth']} | {t['overall']} | {t['weak']} |",
|
|
164
|
+
"| --- | --- | --- | --- | --- |"]
|
|
165
|
+
for target, p in sorted(posture.items(), key=lambda kv: (kv[1]["overall"] or "Z", kv[0])):
|
|
166
|
+
out.append(f"| {_esc(target)} | {p['key_exchange'] or '-'} | {p['authentication'] or '-'} | "
|
|
167
|
+
f"**{p['overall'] or '-'}** | {_esc(', '.join(p['weak_options'])) or '-'} |")
|
|
168
|
+
top = [f for f in findings if f.score > 0][:10]
|
|
169
|
+
out += ["", f"## {t['top']}", ""]
|
|
170
|
+
if top:
|
|
171
|
+
out += [f"| # | {t['score']} | {t['level']} | {t['target']} | {t['alg']} | {t['rec']} |",
|
|
172
|
+
"| --- | --- | --- | --- | --- | --- |"]
|
|
173
|
+
for i, f in enumerate(top, 1):
|
|
174
|
+
o = f.observation
|
|
175
|
+
out.append(f"| {i} | {f.score} | {f.level} | {_esc(o.target)} | {_esc(o.algorithm)} "
|
|
176
|
+
f"({o.category}, {o.role}) | {_esc(f.recommendation or f.note)} |")
|
|
177
|
+
else:
|
|
178
|
+
out.append(t["none"])
|
|
179
|
+
out += ["", f"## {t['all']}", "",
|
|
180
|
+
f"| {t['level']} | {t['score']} | {t['target']} | {t['cat']} | {t['alg']} | {t['role']} | {t['note']} |",
|
|
181
|
+
"| --- | --- | --- | --- | --- | --- | --- |"]
|
|
182
|
+
for f in findings:
|
|
183
|
+
o = f.observation
|
|
184
|
+
out.append(f"| {f.level} | {f.score} | {_esc(o.target)} | {o.category} | {_esc(o.algorithm)} | "
|
|
185
|
+
f"{o.role} | {_esc(f.note)} |")
|
|
186
|
+
if errors:
|
|
187
|
+
out += ["", f"## {t['errors']}", ""] + [f"- {_esc(e)}" for e in errors]
|
|
188
|
+
return "\n".join(out) + "\n"
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
# SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
# Copyright (c) 2026 Forex Robotics Co., Ltd.
|
|
3
|
+
"""Certificate and key description (never outputs key material)."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import hashlib
|
|
8
|
+
import re
|
|
9
|
+
from datetime import timezone
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
from cryptography import x509
|
|
13
|
+
from cryptography.hazmat.primitives.asymmetric import dsa, ec, ed448, ed25519, rsa
|
|
14
|
+
from cryptography.hazmat.primitives.serialization import Encoding
|
|
15
|
+
|
|
16
|
+
from ..model import CERTIFICATE, Observation
|
|
17
|
+
|
|
18
|
+
# Signature / key OIDs not (yet) named by every cryptography build.
|
|
19
|
+
OID_NAMES = {
|
|
20
|
+
"2.16.840.1.101.3.4.3.17": "ML-DSA-44",
|
|
21
|
+
"2.16.840.1.101.3.4.3.18": "ML-DSA-65",
|
|
22
|
+
"2.16.840.1.101.3.4.3.19": "ML-DSA-87",
|
|
23
|
+
"2.16.840.1.101.3.4.4.1": "ML-KEM-512",
|
|
24
|
+
"2.16.840.1.101.3.4.4.2": "ML-KEM-768",
|
|
25
|
+
"2.16.840.1.101.3.4.4.3": "ML-KEM-1024",
|
|
26
|
+
"1.2.840.113549.1.9.16.3.17": "HSS-LMS",
|
|
27
|
+
# SLH-DSA: 2.16.840.1.101.3.4.3.20 .. 31
|
|
28
|
+
**{f"2.16.840.1.101.3.4.3.{n}": f"SLH-DSA-{name}" for n, name in zip(
|
|
29
|
+
range(20, 32),
|
|
30
|
+
["SHA2-128s", "SHA2-128f", "SHA2-192s", "SHA2-192f", "SHA2-256s", "SHA2-256f",
|
|
31
|
+
"SHAKE-128s", "SHAKE-128f", "SHAKE-192s", "SHAKE-192f", "SHAKE-256s", "SHAKE-256f"], strict=False)},
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
SIG_OID_NAMES = {
|
|
35
|
+
"1.2.840.113549.1.1.11": "sha256WithRSAEncryption",
|
|
36
|
+
"1.2.840.113549.1.1.12": "sha384WithRSAEncryption",
|
|
37
|
+
"1.2.840.113549.1.1.13": "sha512WithRSAEncryption",
|
|
38
|
+
"1.2.840.113549.1.1.5": "sha1WithRSAEncryption",
|
|
39
|
+
"1.2.840.113549.1.1.4": "md5WithRSAEncryption",
|
|
40
|
+
"1.2.840.113549.1.1.10": "rsassa-pss",
|
|
41
|
+
"1.2.840.10045.4.3.2": "ecdsa-with-SHA256",
|
|
42
|
+
"1.2.840.10045.4.3.3": "ecdsa-with-SHA384",
|
|
43
|
+
"1.2.840.10045.4.3.4": "ecdsa-with-SHA512",
|
|
44
|
+
"1.2.840.10045.4.1": "ecdsa-with-SHA1",
|
|
45
|
+
"1.3.101.112": "Ed25519",
|
|
46
|
+
"1.3.101.113": "Ed448",
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
# Distro-packaged `cryptography` can be old (Ubuntu 22.04: 3.4, Debian 12: 38),
|
|
51
|
+
# so avoid APIs newer than 3.4 or fall back when they are missing.
|
|
52
|
+
_PEM_CERT = re.compile(rb"-----BEGIN CERTIFICATE-----.+?-----END CERTIFICATE-----", re.S)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _spki_oid(cert: x509.Certificate) -> str:
|
|
56
|
+
oid = getattr(cert, "public_key_algorithm_oid", None)
|
|
57
|
+
if oid is not None:
|
|
58
|
+
return oid.dotted_string
|
|
59
|
+
# Older cryptography: read the SubjectPublicKeyInfo algorithm OID from the DER.
|
|
60
|
+
return _der_spki_oid(cert.public_bytes(Encoding.DER)) or "unknown"
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _not_after(cert: x509.Certificate) -> str:
|
|
64
|
+
dt = getattr(cert, "not_valid_after_utc", None)
|
|
65
|
+
if dt is None:
|
|
66
|
+
dt = cert.not_valid_after.replace(tzinfo=timezone.utc)
|
|
67
|
+
return dt.isoformat()
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _der_read(buf: bytes, pos: int) -> tuple[int, int, int]:
|
|
71
|
+
"""Return (tag, content_start, content_end) of the DER element at pos."""
|
|
72
|
+
tag = buf[pos]
|
|
73
|
+
length = buf[pos + 1]
|
|
74
|
+
start = pos + 2
|
|
75
|
+
if length & 0x80:
|
|
76
|
+
n = length & 0x7F
|
|
77
|
+
length = int.from_bytes(buf[start:start + n], "big")
|
|
78
|
+
start += n
|
|
79
|
+
return tag, start, start + length
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _der_spki_oid(der: bytes) -> str | None:
|
|
83
|
+
try:
|
|
84
|
+
_, cs, _ = _der_read(der, 0) # Certificate
|
|
85
|
+
_, ts, te = _der_read(der, cs) # TBSCertificate
|
|
86
|
+
pos = ts
|
|
87
|
+
fields = []
|
|
88
|
+
while pos < te:
|
|
89
|
+
tag, s, e = _der_read(der, pos)
|
|
90
|
+
fields.append((tag, s, e))
|
|
91
|
+
pos = e
|
|
92
|
+
if fields and fields[0][0] == 0xA0: # explicit [0] version present
|
|
93
|
+
fields = fields[1:]
|
|
94
|
+
_, ss, _ = fields[5] # subjectPublicKeyInfo
|
|
95
|
+
_, as_, _ = _der_read(der, ss) # AlgorithmIdentifier
|
|
96
|
+
tag, os_, oe = _der_read(der, as_) # OID
|
|
97
|
+
if tag != 0x06:
|
|
98
|
+
return None
|
|
99
|
+
return _decode_oid(der[os_:oe])
|
|
100
|
+
except (IndexError, ValueError):
|
|
101
|
+
return None
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _decode_oid(b: bytes) -> str:
|
|
105
|
+
first = b[0]
|
|
106
|
+
parts = [str(first // 40), str(first % 40)]
|
|
107
|
+
val = 0
|
|
108
|
+
for byte in b[1:]:
|
|
109
|
+
val = (val << 7) | (byte & 0x7F)
|
|
110
|
+
if not byte & 0x80:
|
|
111
|
+
parts.append(str(val))
|
|
112
|
+
val = 0
|
|
113
|
+
return ".".join(parts)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _key_name(cert: x509.Certificate) -> tuple[str, int | None]:
|
|
117
|
+
try:
|
|
118
|
+
pk = cert.public_key()
|
|
119
|
+
except Exception: # unknown key type (e.g. PQ on an older build)
|
|
120
|
+
oid = _spki_oid(cert)
|
|
121
|
+
return OID_NAMES.get(oid, f"oid:{oid}"), None
|
|
122
|
+
if isinstance(pk, rsa.RSAPublicKey):
|
|
123
|
+
return f"RSA-{pk.key_size}", pk.key_size
|
|
124
|
+
if isinstance(pk, ec.EllipticCurvePublicKey):
|
|
125
|
+
return f"ECDSA-{pk.curve.name}", pk.curve.key_size
|
|
126
|
+
if isinstance(pk, ed25519.Ed25519PublicKey):
|
|
127
|
+
return "Ed25519", 256
|
|
128
|
+
if isinstance(pk, ed448.Ed448PublicKey):
|
|
129
|
+
return "Ed448", 448
|
|
130
|
+
if isinstance(pk, dsa.DSAPublicKey):
|
|
131
|
+
return f"DSA-{pk.key_size}", pk.key_size
|
|
132
|
+
oid = _spki_oid(cert)
|
|
133
|
+
return OID_NAMES.get(oid, type(pk).__name__), None
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def describe_certificate(der: bytes) -> dict:
|
|
137
|
+
cert = x509.load_der_x509_certificate(der)
|
|
138
|
+
key, bits = _key_name(cert)
|
|
139
|
+
sig_oid = cert.signature_algorithm_oid.dotted_string
|
|
140
|
+
sig = SIG_OID_NAMES.get(sig_oid) or OID_NAMES.get(sig_oid) or sig_oid
|
|
141
|
+
return {
|
|
142
|
+
"public_key": key,
|
|
143
|
+
"key_bits": bits,
|
|
144
|
+
"signature_algorithm": sig,
|
|
145
|
+
"subject": cert.subject.rfc4514_string(),
|
|
146
|
+
"issuer": cert.issuer.rfc4514_string(),
|
|
147
|
+
"not_after": _not_after(cert),
|
|
148
|
+
"sha256_fingerprint": hashlib.sha256(der).hexdigest(),
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _load_certs(data: bytes) -> list[bytes]:
|
|
153
|
+
if b"-----BEGIN CERTIFICATE-----" in data:
|
|
154
|
+
return [x509.load_pem_x509_certificate(block).public_bytes(Encoding.DER)
|
|
155
|
+
for block in _PEM_CERT.findall(data)]
|
|
156
|
+
try:
|
|
157
|
+
x509.load_der_x509_certificate(data)
|
|
158
|
+
return [data]
|
|
159
|
+
except ValueError:
|
|
160
|
+
return []
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
CERT_SUFFIXES = {".pem", ".crt", ".cer", ".der"}
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def scan_cert_files(root: Path, max_bytes: int = 1_000_000) -> list[Observation]:
|
|
167
|
+
obs: list[Observation] = []
|
|
168
|
+
paths = [root] if root.is_file() else [p for p in root.rglob("*") if p.suffix.lower() in CERT_SUFFIXES]
|
|
169
|
+
for p in sorted(paths):
|
|
170
|
+
try:
|
|
171
|
+
if not p.is_file() or p.stat().st_size > max_bytes:
|
|
172
|
+
continue
|
|
173
|
+
ders = _load_certs(p.read_bytes())
|
|
174
|
+
except (OSError, ValueError):
|
|
175
|
+
continue
|
|
176
|
+
for i, der in enumerate(ders):
|
|
177
|
+
d = describe_certificate(der)
|
|
178
|
+
d["path"] = str(p)
|
|
179
|
+
d["index_in_file"] = i
|
|
180
|
+
t = f"file://{p}"
|
|
181
|
+
obs.append(Observation(t, "file", CERTIFICATE, d["public_key"], "in-use", d))
|
|
182
|
+
obs.append(Observation(t, "file", "signature", d["signature_algorithm"], "in-use",
|
|
183
|
+
{"subject": d["subject"], "path": str(p)}))
|
|
184
|
+
return obs
|