-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpqc_cbom.py
More file actions
2030 lines (1850 loc) · 95.7 KB
/
pqc_cbom.py
File metadata and controls
2030 lines (1850 loc) · 95.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Post-Quantum Cryptography - Cryptography Bill of Materials (PQC CBOM) Generator
Analyzes TLS/SSL configurations and generates quantum vulnerability inventory
"""
import json
import sys
from datetime import datetime, timezone
from collections import Counter, defaultdict
# Quantum vulnerability classifications
QUANTUM_VULNERABLE_KEY_EXCHANGE = {
"rsa", "dh", "dhe", "ecdh", "ecdhe", "x25519", "x448"
}
QUANTUM_VULNERABLE_SIGNATURES = {
"rsa", "ecdsa", "dsa", "ed25519", "ed448"
}
# Symmetric crypto - Grover's algorithm impact
SYMMETRIC_QUANTUM_IMPACT = {
"aes128": "weak", # 128-bit → 64-bit quantum security
"aes256": "adequate", # 256-bit → 128-bit quantum security
"chacha20": "adequate"
}
# NIST PQC Standards (2024+)
PQC_ALGORITHMS = {
"kyber": "ML-KEM (FIPS 203)", # Key Encapsulation
"dilithium": "ML-DSA (FIPS 204)", # Digital Signature
"falcon": "FN-DSA (FIPS 206)", # Digital Signature
"sphincs": "SLH-DSA (FIPS 205)" # Stateless Hash Signature
}
# PQC Hybrid Key Exchange Groups (quantum-safe)
PQC_HYBRID_GROUPS = {
"x25519mlkem768", "secp256r1mlkem768", "x25519kyber768",
"secp384r1mlkem1024", "x448mlkem1024"
}
# Legacy cipher suites with no forward secrecy or broken algorithms
# These must never be classified as PQC-ready even if no KEX vulnerability is detected
LEGACY_CIPHERS = {
# ── SHA-1 based — no forward secrecy ──────────────────────────────
"AES128-SHA", # Static RSA + SHA-1 — vpn1.flcu.org ❌
"AES256-SHA", # Static RSA + SHA-1 ❌
"AES128-SHA256", # Static RSA + SHA-256 but no FS ❌
"AES256-SHA256", # Static RSA + SHA-256 but no FS ❌
# ── DES / 3DES — weak encryption ──────────────────────────────────
"DES-CBC3-SHA", # 3DES — only 112-bit security ❌
"DES-CBC-SHA", # Single DES — completely broken ❌
"EDH-RSA-DES-CBC3-SHA", # DHE + 3DES ❌
"EDH-DSS-DES-CBC3-SHA", # DSS + 3DES ❌
# ── RC4 — stream cipher, completely broken ─────────────────────────
"RC4-SHA", # RC4 broken since 2015 ❌
"RC4-MD5", # RC4 + MD5 — doubly broken ❌
"ECDHE-RSA-RC4-SHA", # Even with ECDHE, RC4 is broken ❌
"ECDHE-ECDSA-RC4-SHA", # Same ❌
# ── NULL ciphers — no encryption at all ───────────────────────────
"NULL-SHA", # No encryption ❌
"NULL-MD5", # No encryption ❌
"NULL-SHA256", # No encryption ❌
# ── Export grade — intentionally weakened ─────────────────────────
"EXP-RC4-MD5", # Export 40-bit RC4 ❌
"EXP-DES-CBC-SHA", # Export 40-bit DES ❌
"EXP-RC2-CBC-MD5", # Export 40-bit RC2 ❌
# ── CBC mode + SHA-1 — BEAST/POODLE vulnerable ────────────────────
"ECDHE-RSA-AES128-SHA", # Good KEX but SHA-1 + CBC ❌
"ECDHE-RSA-AES256-SHA", # Good KEX but SHA-1 + CBC ❌
"ECDHE-ECDSA-AES128-SHA", # Good KEX but SHA-1 + CBC ❌
"ECDHE-ECDSA-AES256-SHA", # Good KEX but SHA-1 + CBC ❌
"DHE-RSA-AES128-SHA", # DHE but SHA-1 + CBC ❌
"DHE-RSA-AES256-SHA", # DHE but SHA-1 + CBC ❌
"DHE-DSS-AES128-SHA", # DSS + SHA-1 + CBC ❌
"DHE-DSS-AES256-SHA", # DSS + SHA-1 + CBC ❌
}
# HTTP Status Code Mapping (18 codes)
HTTP_STATUS_MAP = {
# 2xx Success - Serving content (Warning on HTTP)
200: {"type": "serving", "description": "Serving content", "severity": "warning", "color": "orange"},
201: {"type": "serving", "description": "Created (API)", "severity": "warning", "color": "orange"},
204: {"type": "serving", "description": "No content", "severity": "warning", "color": "orange"},
# 3xx Redirect - Good (redirecting to HTTPS)
301: {"type": "redirect", "description": "Redirects to HTTPS", "severity": "good", "color": "green"},
302: {"type": "redirect", "description": "Redirects to HTTPS", "severity": "good", "color": "green"},
303: {"type": "redirect", "description": "Redirects (See Other)", "severity": "good", "color": "green"},
307: {"type": "redirect", "description": "Redirects to HTTPS", "severity": "good", "color": "green"},
308: {"type": "redirect", "description": "Redirects to HTTPS", "severity": "good", "color": "green"},
# 4xx Client Errors
400: {"type": "error", "description": "Bad request", "severity": "info", "color": "gray"},
401: {"type": "auth", "description": "Auth required on HTTP!", "severity": "critical", "color": "red"},
403: {"type": "forbidden", "description": "Forbidden", "severity": "info", "color": "gray"},
404: {"type": "not_found", "description": "Not found", "severity": "info", "color": "gray"},
429: {"type": "rate_limit", "description": "Rate limited", "severity": "info", "color": "gray"},
# 5xx Server Errors
500: {"type": "error", "description": "Server error", "severity": "info", "color": "gray"},
502: {"type": "error", "description": "Bad gateway", "severity": "info", "color": "gray"},
503: {"type": "error", "description": "Unavailable", "severity": "info", "color": "gray"},
504: {"type": "error", "description": "Timeout", "severity": "info", "color": "gray"},
520: {"type": "error", "description": "Cloudflare error", "severity": "info", "color": "gray"},
}
def get_http_status_info(status_code):
"""Get HTTP status code interpretation"""
if status_code is None:
return {
"type": "no_service",
"description": "No service",
"severity": "info",
"color": "gray"
}
# Try exact match first
if status_code in HTTP_STATUS_MAP:
return HTTP_STATUS_MAP[status_code]
# Fall back to category-based matching
if 200 <= status_code < 300:
return {"type": "serving", "description": f"HTTP {status_code}", "severity": "warning", "color": "orange"}
elif 300 <= status_code < 400:
return {"type": "redirect", "description": f"Redirect ({status_code})", "severity": "good", "color": "green"}
elif 400 <= status_code < 500:
return {"type": "client_error", "description": f"Client error ({status_code})", "severity": "info", "color": "gray"}
elif 500 <= status_code < 600:
return {"type": "server_error", "description": f"Server error ({status_code})", "severity": "info", "color": "gray"}
else:
return {"type": "unknown", "description": f"HTTP {status_code}", "severity": "info", "color": "gray"}
def is_pqc_safe_curve(curve_name):
"""
Check if a key exchange curve/group is PQC-safe.
Returns True for PQC hybrid groups, False for classical curves.
"""
if not curve_name:
return False
curve_lower = curve_name.lower()
# Check for known PQC hybrid groups
if curve_lower in PQC_HYBRID_GROUPS:
return True
# Check for PQC keywords
if any(pqc in curve_lower for pqc in ['mlkem', 'kyber', 'ntru', 'saber', 'frodo']):
return True
return False
def build_certificate_curve_info(record):
"""
Build certificate curve/key information.
Shows EC curve for ECDSA certs, or RSA-{size} for RSA certs.
"""
detailed_cert = record.get("detailed_certificate") or {}
ec_curve = record.get("ec_curve") or detailed_cert.get("ec_curve")
public_key_algorithm = detailed_cert.get("public_key_algorithm") or record.get("public_key_algorithm")
signature_algorithm = detailed_cert.get("signature_algorithm") or record.get("signature_algorithm")
key_size = detailed_cert.get("key_size_bits") or record.get("key_size")
# Determine display value: EC curve or RSA-{size}
if ec_curve:
# ECDSA certificate - show the curve
display = ec_curve
elif public_key_algorithm and key_size:
# RSA or other - show algorithm + key size
alg = public_key_algorithm.lower()
if "rsa" in alg:
display = f"RSA-{key_size}"
elif "dsa" in alg:
display = f"DSA-{key_size}"
else:
display = f"{public_key_algorithm}-{key_size}"
elif key_size:
display = f"RSA-{key_size}" # Default assumption
else:
display = None
return {
"curve": ec_curve, # Original EC curve (null for RSA)
"display": display, # Human-readable: "prime256v1" or "RSA-2048"
"public_key_algorithm": public_key_algorithm,
"signature_algorithm": signature_algorithm,
"key_size": key_size,
"pqc_safe": False, # Certificate signatures are NOT PQC-safe yet
"note": "PQC certificate signatures (Dilithium/ML-DSA) not yet widely available"
}
def extract_crypto_primitives(cipher_suite):
"""Extract cryptographic primitives from cipher suite name"""
if not cipher_suite:
return {}
cipher_lower = cipher_suite.lower()
primitives = {
"key_exchange": None,
"authentication": None,
"encryption": None,
"mac": None,
"mode": None
}
# Key Exchange
if "ecdhe" in cipher_lower:
primitives["key_exchange"] = "ECDHE"
elif "dhe" in cipher_lower:
primitives["key_exchange"] = "DHE"
elif "ecdh" in cipher_lower:
primitives["key_exchange"] = "ECDH"
elif "rsa" in cipher_lower and "with" in cipher_lower:
# TLS_RSA_WITH_* means RSA key exchange
primitives["key_exchange"] = "RSA"
elif cipher_suite in LEGACY_CIPHERS:
# Static RSA ciphers like AES128-SHA have no KEX prefix
# but implicitly use Static RSA key exchange
primitives["key_exchange"] = "RSA"
# Authentication (from cipher suite or separate)
if "rsa" in cipher_lower:
primitives["authentication"] = "RSA"
elif "ecdsa" in cipher_lower:
primitives["authentication"] = "ECDSA"
elif "dss" in cipher_lower or "dsa" in cipher_lower:
primitives["authentication"] = "DSA"
# Encryption
if "aes_256" in cipher_lower or "aes256" in cipher_lower:
primitives["encryption"] = "AES-256"
elif "aes_128" in cipher_lower or "aes128" in cipher_lower:
primitives["encryption"] = "AES-128"
elif "chacha20" in cipher_lower:
primitives["encryption"] = "ChaCha20"
elif "3des" in cipher_lower:
primitives["encryption"] = "3DES"
elif "rc4" in cipher_lower:
primitives["encryption"] = "RC4"
# Mode
if "gcm" in cipher_lower:
primitives["mode"] = "GCM"
elif "ccm" in cipher_lower:
primitives["mode"] = "CCM"
elif "cbc" in cipher_lower:
primitives["mode"] = "CBC"
elif "poly1305" in cipher_lower:
primitives["mode"] = "Poly1305"
# MAC/Hash
if "sha384" in cipher_lower:
primitives["mac"] = "SHA-384"
elif "sha256" in cipher_lower:
primitives["mac"] = "SHA-256"
elif "sha1" in cipher_lower or "sha" in cipher_lower:
primitives["mac"] = "SHA-1"
elif "md5" in cipher_lower:
primitives["mac"] = "MD5"
return primitives
def assess_quantum_vulnerability(primitives, tls_version, curve_name=None):
"""Assess quantum vulnerability of cryptographic primitives"""
vulnerabilities = []
pqc_ready = True
# Check if key exchange curve is PQC-safe (hybrid PQC like X25519MLKEM768)
kex_pqc_safe = is_pqc_safe_curve(curve_name)
# TLS 1.3 special handling - key exchange is implicit
if tls_version == "tls13":
if kex_pqc_safe:
# Using hybrid PQC key exchange - session is quantum-safe
vulnerabilities.append({
"component": "Key Exchange",
"algorithm": curve_name or "Hybrid PQC",
"quantum_vulnerable": False,
"algorithm_type": "Hybrid Post-Quantum Key Exchange",
"broken_by": None,
"security_level_classical": "128-bit",
"security_level_quantum": "128-bit (PQC-safe)",
"replacement": "Already using PQC",
"nist_standard": "FIPS 203 (ML-KEM)"
})
# pqc_ready stays True
else:
vulnerabilities.append({
"component": "Key Exchange",
"algorithm": curve_name or "ECDHE (implicit in TLS 1.3)",
"quantum_vulnerable": True,
"algorithm_type": "Elliptic Curve Diffie-Hellman",
"broken_by": "Shor's Algorithm",
"security_level_classical": "128-bit",
"security_level_quantum": "0-bit (broken)",
"replacement": "ML-KEM (FIPS 203) via X25519MLKEM768",
"nist_standard": "FIPS 203"
})
pqc_ready = False
elif primitives.get("key_exchange"):
kex = primitives["key_exchange"]
if kex_pqc_safe:
# Using hybrid PQC key exchange
vulnerabilities.append({
"component": "Key Exchange",
"algorithm": curve_name or kex,
"quantum_vulnerable": False,
"algorithm_type": "Hybrid Post-Quantum Key Exchange",
"broken_by": None,
"security_level_classical": "128-bit",
"security_level_quantum": "128-bit (PQC-safe)",
"replacement": "Already using PQC",
"nist_standard": "FIPS 203 (ML-KEM)"
})
# pqc_ready stays True
elif kex.lower() in QUANTUM_VULNERABLE_KEY_EXCHANGE:
vulnerabilities.append({
"component": "Key Exchange",
"algorithm": kex,
"quantum_vulnerable": True,
"algorithm_type": get_algorithm_type(kex),
"broken_by": "Shor's Algorithm",
"security_level_classical": "128-bit" if "ecdhe" in kex.lower() else "112-bit",
"security_level_quantum": "0-bit (broken)",
"replacement": "ML-KEM (FIPS 203) via X25519MLKEM768",
"nist_standard": "FIPS 203"
})
pqc_ready = False
# Authentication/Signatures - still vulnerable even with PQC KEX
# (but we consider asset PQC-ready if KEX is safe, as that protects session data)
if primitives.get("authentication"):
auth = primitives["authentication"]
if auth.lower() in QUANTUM_VULNERABLE_SIGNATURES:
vulnerabilities.append({
"component": "Authentication/Signature",
"algorithm": auth,
"quantum_vulnerable": True,
"algorithm_type": get_algorithm_type(auth),
"broken_by": "Shor's Algorithm",
"security_level_classical": "128-bit" if "ecdsa" in auth.lower() else "112-bit",
"security_level_quantum": "0-bit (broken)",
"replacement": "ML-DSA (FIPS 204)",
"nist_standard": "FIPS 204 or FIPS 206"
})
# Note: We don't set pqc_ready = False here if KEX is PQC-safe
# because session data is protected even if signatures are classical
# Symmetric encryption - Grover's impact
if primitives.get("encryption"):
enc = primitives["encryption"]
enc_lower = enc.lower()
if "aes" in enc_lower or "chacha" in enc_lower:
quantum_impact = "adequate" if "256" in enc_lower else "weak"
vulnerabilities.append({
"component": "Symmetric Encryption",
"algorithm": enc,
"quantum_vulnerable": False, # Not broken, just weakened
"algorithm_type": "Symmetric Cipher",
"broken_by": None,
"weakened_by": "Grover's Algorithm",
"security_level_classical": "256-bit" if "256" in enc_lower else "128-bit",
"security_level_quantum": "128-bit" if "256" in enc_lower else "64-bit",
"impact": quantum_impact,
"replacement": "AES-256 (adequate) or increase to 512-bit",
"nist_standard": "Current AES-256 is acceptable"
})
return vulnerabilities, pqc_ready
def get_algorithm_type(algorithm):
"""Get human-readable algorithm type"""
alg_lower = algorithm.lower()
if "rsa" in alg_lower:
return "RSA (Integer Factorization)"
elif "ecdhe" in alg_lower or "ecdh" in alg_lower or "ecdsa" in alg_lower:
return "Elliptic Curve Cryptography"
elif "dhe" in alg_lower or "dh" in alg_lower:
return "Diffie-Hellman"
elif "dsa" in alg_lower:
return "Digital Signature Algorithm"
else:
return algorithm
def calculate_migration_priority(record, vulnerabilities, tls_version):
"""
Calculate PQC migration priority score (0-100) and priority tier.
Scoring model (NIST IR 8547 aligned):
Step 1 — TLS Version Gate (auto-CRITICAL, no scoring):
TLS 1.0 / 1.1 -> CRITICAL (classically broken + PQC impossible)
TLS 1.2 -> CRITICAL (PQC blocked — must upgrade to TLS 1.3 first)
HTTP / no TLS -> handled upstream (priority_score=0, priority=INFO)
TLS 1.3 -> proceed to quantum risk scoring
Step 2 — Quantum Risk Score (TLS 1.3 only, 0-100):
KEX not hybrid (X25519/ECDH) -> +70 (HNDL risk — highest urgency)
Sig not PQC (ECDSA/RSA) -> +30 (future quantum risk)
Priority Tiers:
80-100 -> CRITICAL 2026-2027 (both KEX + Sig vulnerable)
60-79 -> HIGH 2026-2028 (KEX vulnerable, Sig safe)
20-59 -> MEDIUM 2028-2030 (KEX safe, Sig vulnerable)
0-19 -> LOW 2030-2032 (fully PQC ready — future state)
"""
# ── Step 1: TLS Version Gate ──────────────────────────────────────────────
if tls_version in ("tls10", "tls11"):
return {
"priority": "CRITICAL",
"priority_score": 100,
"timeline": "2026-2027",
"complexity": "CRITICAL",
"effort": "Upgrade TLS version immediately — TLS 1.0/1.1 are classically broken and PQC migration is impossible"
}
if tls_version == "tls12":
return {
"priority": "CRITICAL",
"priority_score": 100,
"timeline": "2026-2027",
"complexity": "HIGH",
"effort": "Upgrade to TLS 1.3 first — TLS 1.2 cannot support PQC hybrid key exchange"
}
# ── Step 2: TLS 1.3 Quantum Risk Scoring ─────────────────────────────────
priority_score = 0
# KEX: +70 if not using PQC hybrid (HNDL risk — harvest now, decrypt later)
kex_safe = record.get("pqc_hybrid", False) or is_pqc_safe_curve(record.get("curve"))
if not kex_safe:
priority_score += 70
# Sig: +30 if certificate signature is not PQC safe (ECDSA/RSA)
# certificate_safe is always False today — ML-DSA certs not yet widely available
cert_safe = record.get("certificate_safe", False)
if not cert_safe:
priority_score += 30
# ── Step 3: Priority Tier ─────────────────────────────────────────────────
if priority_score >= 80:
priority = "CRITICAL"
timeline = "2026-2027"
elif priority_score >= 60:
priority = "HIGH"
timeline = "2026-2028"
elif priority_score >= 20:
priority = "MEDIUM"
timeline = "2028-2030"
else:
priority = "LOW"
timeline = "2030-2032"
# ── Complexity and Effort (dynamic based on actual state) ─────────────────
# Complexity reflects actual implementation effort required:
# HIGH — multiple changes needed (KEX config + certificate replacement)
# MEDIUM — single change needed (either KEX config OR certificate)
# LOW — fully PQC ready, monitoring only
if not kex_safe and not cert_safe:
complexity = "HIGH"
effort = "Deploy hybrid PQC KEX (X25519MLKEM768) + migrate certificate to ML-DSA (FIPS 204)"
elif not kex_safe and cert_safe:
complexity = "MEDIUM"
effort = "Deploy hybrid PQC KEX (X25519MLKEM768) — certificate already PQC safe"
elif kex_safe and not cert_safe:
complexity = "MEDIUM"
effort = "Migrate certificate signature to ML-DSA (FIPS 204) — KEX already PQC safe"
else:
complexity = "LOW"
effort = "Fully PQC ready — monitor for NIST standard updates"
return {
"priority": priority,
"priority_score": priority_score,
"timeline": timeline,
"complexity": complexity,
"effort": effort
}
def generate_ssh_cbom_entry(record):
"""
Generate Crypto-BOM entry for an SSH asset.
SSH entries arrive pre-classified from scan.sh's run_ssh_audit_host().
We wrap them into the standard CBOM structure the dashboard expects.
"""
host = record.get("host", "unknown")
port = record.get("port", 22)
probe_status = record.get("probe_status", "success")
timestamp = record.get("scan_timestamp") or datetime.now(timezone.utc).isoformat()
# For filtered/closed SSH — return minimal entry
if probe_status in ("filtered", "closed", "no_ssh_banner"):
migration_info = record.get("pqc_migration", {})
return {
"_host": host,
"_port": port,
"asset": {
"host": host,
"port": port,
"timestamp": timestamp
},
"host": host,
"port": port,
"probe_status": probe_status,
"tls_enabled": False,
"os": record.get("os"),
"ssh_banner": None,
"ssh_version": None,
"pqc_ready": None,
"key_exchange": {"total": 0, "pqc_safe_count": 0, "algorithms": []},
"host_keys": {"total": 0, "algorithms": []},
"encryption": {"total": 0, "algorithms": []},
"mac": {"total": 0, "algorithms": []},
"pqc_curve_assessment": {
"pqc_ready": None,
"migration_priority": "UNKNOWN"
},
"pqc_migration": migration_info if migration_info else {
"priority": "UNKNOWN",
"priority_score": 0,
"timeline": f"SSH {probe_status} — check firewall/CDN",
"complexity": "UNKNOWN",
"effort": f"SSH port {probe_status} — verify connectivity first"
},
"quantum_vulnerability": {
"pqc_ready": None,
"vulnerable_components": [],
"note": f"SSH port {probe_status}"
}
}
# For successful SSH scans — the record already has the right structure.
# Just ensure required CBOM fields exist and add quantum_vulnerability
# in the format the stats loop in main() expects.
kex = record.get("key_exchange", {})
pqc_assessment = record.get("pqc_curve_assessment", {})
pqc_ready = record.get("pqc_ready", pqc_assessment.get("pqc_ready", False))
migration = record.get("pqc_migration", {})
# Build vulnerable_components list for stats tracking
vulnerable_components = []
for alg in kex.get("algorithms", []):
if not alg.get("pqc_safe", False):
vulnerable_components.append({
"component": "Key Exchange (SSH)",
"algorithm": alg.get("algorithm", "unknown"),
"quantum_vulnerable": True,
"algorithm_type": "SSH Key Exchange",
"broken_by": "Shor's Algorithm",
"replacement": alg.get("replacement", "mlkem768x25519-sha256")
})
for hk in record.get("host_keys", {}).get("algorithms", []):
if hk.get("quantum_threat") == "shors_algorithm":
vulnerable_components.append({
"component": "Host Key (SSH)",
"algorithm": hk.get("algorithm", "unknown"),
"quantum_vulnerable": True,
"algorithm_type": "SSH Host Key",
"broken_by": "Shor's Algorithm",
"replacement": hk.get("replacement", "ML-DSA-65")
})
# Return the record as-is with CBOM-compatible fields added
entry = dict(record)
entry["_host"] = host
entry["_port"] = port
entry["tls_enabled"] = False
entry["tls_configuration"] = {"version": record.get("ssh_version", "SSH"), "cipher_suite": None}
entry["quantum_vulnerability"] = {
"pqc_ready": pqc_ready,
"vulnerable_components": vulnerable_components,
"total_vulnerable": sum(1 for v in vulnerable_components if v.get("quantum_vulnerable"))
}
# Ensure pqc_migration exists
if not entry.get("pqc_migration"):
entry["pqc_migration"] = migration if migration else {
"priority": pqc_assessment.get("migration_priority", "UNKNOWN"),
"timeline": "Assess SSH PQC readiness"
}
# Ensure standard asset wrapper exists (for consistent CBOM structure)
if "asset" not in entry:
entry["asset"] = {
"host": host,
"port": port,
"timestamp": timestamp
}
return entry
def _compute_cert_days_remaining(not_after_str):
"""
Compute days until certificate expiry.
Returns an integer (may be negative if expired), or None if unparseable.
Matches dashboard display values: 19d, 24d, 65d, 81d, 88d, 131d.
"""
if not not_after_str:
return None
formats = [
"%Y-%m-%dT%H:%M:%SZ",
"%Y-%m-%dT%H:%M:%S%z",
"%Y-%m-%d %H:%M:%S",
"%Y-%m-%d",
"%b %d, %Y",
"%b %d %H:%M:%S %Y GMT",
]
for fmt in formats:
try:
dt = datetime.strptime(not_after_str, fmt)
if dt.tzinfo is None:
dt = dt.replace(tzinfo=timezone.utc)
now = datetime.now(timezone.utc)
return (dt - now).days
except ValueError:
continue
return None
def generate_cbom_entry(record):
"""Generate Crypto-BOM entry for a single asset"""
# ═══ SSH ASSET DETECTION ═══
# SSH entries come pre-formatted from scan.sh's run_ssh_audit_host() with
# fields like ssh_banner, ssh_version, key_exchange.algorithms[], host_keys, etc.
# Also detect filtered/closed SSH entries (SSH ports with no TLS data).
ssh_ports = {22, 2222, 2200, 22222, 8022, 222, 3022, 4022, 8222, 10022}
is_ssh = (
record.get("ssh_banner") or record.get("ssh_version") or
(isinstance(record.get("key_exchange"), dict) and record.get("key_exchange", {}).get("algorithms")) or
(record.get("port") in ssh_ports and record.get("tls_enabled") in (False, None)
and record.get("probe_status") in ("filtered", "closed", "no_ssh_banner"))
)
if is_ssh:
return generate_ssh_cbom_entry(record)
# FIELD NAME COMPATIBILITY: Support both field name formats
# tlsx uses "subject_cn", normalize_tls.py uses "cert_subject_cn"
if "subject_cn" in record and not record.get("cert_subject_cn"):
record["cert_subject_cn"] = record.get("subject_cn")
if "subject_an" in record and not record.get("cert_subject_an"):
record["cert_subject_an"] = record.get("subject_an", [])
if "issuer_cn" in record and not record.get("cert_issuer_cn"):
record["cert_issuer_cn"] = record.get("issuer_cn")
if "not_before" in record and not record.get("cert_not_before"):
record["cert_not_before"] = record.get("not_before")
if "not_after" in record and not record.get("cert_not_after"):
record["cert_not_after"] = record.get("not_after")
host = record.get("host")
port = record.get("port", 443)
tls_version = record.get("tls_version", "").lower().replace("tlsv", "tls").replace("tls ", "tls").replace(".", "").replace("_", "")
if tls_version == "tls1":
tls_version = "tls10"
cipher = record.get("cipher", "")
# Extract cryptographic primitives
primitives = extract_crypto_primitives(cipher)
# Check for OpenSSL curve information (enhanced data)
curve_info = record.get("curve_information", {})
curve_name = None
if curve_info and curve_info.get("curve_details"):
curve_details = curve_info["curve_details"]
# Add curve details to primitives
curve_name = curve_details.get("name", "unknown")
primitives["curve"] = curve_name
primitives["curve_bits"] = curve_details.get("bits") # May be None for PQC hybrid
primitives["pqc_hybrid"] = curve_details.get("type") == "hybrid_pqc"
# Also check direct curve field in record
if not curve_name:
curve_name = record.get("curve") or record.get("server_temp_key_curve")
# If cipher did not reveal authentication (e.g. AES128-SHA has no RSA/ECDSA prefix)
# fall back to the certificate's public key algorithm
if not primitives.get("authentication"):
pubkey_alg = (record.get("public_key_algorithm") or
(record.get("detailed_certificate") or {}).get("public_key_algorithm") or "")
pubkey_lower = pubkey_alg.lower()
if "rsa" in pubkey_lower:
primitives["authentication"] = "RSA"
elif "ec" in pubkey_lower or "ecdsa" in pubkey_lower:
primitives["authentication"] = "ECDSA"
# Assess quantum vulnerability (pass curve_name for PQC-safe check)
vulnerabilities, pqc_ready = assess_quantum_vulnerability(primitives, tls_version, curve_name)
# Override pqc_ready for legacy cipher suites
# e.g. AES128-SHA (Static RSA) has no KEX to flag but is NOT PQC-safe
if cipher and cipher in LEGACY_CIPHERS:
pqc_ready = False
# Add curve vulnerability if present (only if NOT using PQC hybrid)
if curve_info and curve_info.get("curve_details"):
curve_details = curve_info["curve_details"]
is_pqc_hybrid = curve_details.get("type") == "hybrid_pqc" or curve_info.get("pqc_hybrid", False)
is_quantum_vulnerable = curve_details.get("quantum_vulnerable", True)
curve_alg = curve_details.get("name", "unknown")
# Check if assess_quantum_vulnerability() already added an entry for this curve
already_covered = any(
v.get("algorithm") == curve_alg
for v in vulnerabilities
)
if is_pqc_hybrid or already_covered:
# Already handled — skip to avoid duplicate
pass
elif not is_quantum_vulnerable:
vulnerabilities.append({
"component": "Key Exchange",
"algorithm": curve_alg,
"quantum_vulnerable": False,
"algorithm_type": "Post-Quantum Hybrid Key Exchange",
"broken_by": None,
"security_level_classical": curve_details.get("security_level", "N/A"),
"security_level_quantum": curve_details.get("security_level", "128-bit quantum-safe"),
"replacement": "Already using PQC",
"nist_standard": "FIPS 203 (ML-KEM)",
"details": f"Hybrid: {curve_details.get('classical_component', 'classical')} + {curve_details.get('pqc_component', 'PQC')}"
})
else:
# Classic elliptic curve not yet listed — add it
bits_str = f"{curve_details['bits']}-bit" if curve_details.get('bits') else "unknown size"
also_known = curve_details.get('also_known_as', 'N/A')
vulnerabilities.append({
"component": "Elliptic Curve",
"algorithm": curve_alg,
"quantum_vulnerable": True,
"algorithm_type": "Elliptic Curve Cryptography",
"broken_by": "Shor's Algorithm",
"security_level_classical": curve_details.get("security_level_classical", "N/A"),
"security_level_quantum": "0-bit (broken)",
"replacement": curve_details.get("nist_replacement", "ML-KEM (FIPS 203) via X25519MLKEM768"),
"nist_standard": "FIPS 203",
"details": f"{bits_str} curve, also known as: {also_known}"
})
pqc_ready = False
# Check for certificate issues
cert_issues = []
# Check hostname mismatch
subject_cn = record.get("cert_subject_cn")
subject_an = record.get("cert_subject_an", [])
if subject_cn or subject_an:
valid_names = [subject_cn] + subject_an if subject_cn else subject_an
valid_names = [n for n in valid_names if n]
# Check if host matches
matches = False
for name in valid_names:
if name.startswith("*."):
domain = name[2:]
if host.endswith("." + domain) or host == domain:
matches = True
break
elif name == host:
matches = True
break
if not matches and valid_names:
cert_issues.append({
"issue": "hostname_mismatch",
"severity": "high",
"description": f"Certificate issued for {valid_names} but accessed as {host}",
"expected": valid_names,
"actual": host,
"impact": "Browser warnings, connection failures, trust issues",
"remediation": "Update certificate to include this hostname or update DNS"
})
# Check if self-signed
# Guard against false positives: CA intermediates (e.g. "R3/R3") share CN.
# Only flag as self-signed if the CN looks like a real hostname/IP AND has no SANs.
issuer_cn = record.get("cert_issuer_cn")
def _is_ip(s):
parts = s.split('.')
return len(parts) == 4 and all(p.isdigit() and 0 <= int(p) <= 255 for p in parts)
cn_looks_like_hostname = bool(subject_cn and ('.' in subject_cn or _is_ip(subject_cn)))
san_has_real_names = bool([n for n in (subject_an or []) if n and '.' in n])
if subject_cn and issuer_cn and subject_cn == issuer_cn and cn_looks_like_hostname and not san_has_real_names:
cert_issues.append({
"issue": "self_signed",
"severity": "high",
"description": "Certificate is self-signed",
"impact": "Not trusted by browsers, security warnings",
"remediation": "Obtain certificate from trusted CA (e.g., Let's Encrypt)"
})
# Check expiration
not_after = record.get("cert_not_after")
cert_valid = record.get("cert_valid")
if cert_valid == False:
cert_issues.append({
"issue": "expired",
"severity": "critical",
"description": "Certificate has expired",
"expiry_date": not_after,
"impact": "Service inaccessible, browsers block connection",
"remediation": "Renew certificate immediately"
})
# Calculate migration priority (including cert issues)
migration = calculate_migration_priority(record, vulnerabilities, tls_version)
# Increase priority if certificate has issues
if cert_issues:
if any(issue['severity'] == 'critical' for issue in cert_issues):
migration['priority'] = 'CRITICAL'
elif migration['priority'] not in ['CRITICAL'] and any(issue['severity'] == 'high' for issue in cert_issues):
migration['priority'] = 'HIGH'
# Update complexity
migration['certificate_issues'] = len(cert_issues)
migration['effort'] = migration['effort'] + " + Fix certificate issues first"
# Helper function to clean NULL-like values
def clean_value(value):
if value is None:
return None
if isinstance(value, str):
if value.strip() in ['', '<NULL>', '(NONE)', 'NONE', 'NULL', 'null', 'none', '0000']:
return None
return value
# Check if TLS is enabled
tls_enabled = record.get("tls_enabled", True)
probe_status = record.get("probe_status", "success")
probe_errors = record.get("probe_errors", [])
is_http_only = "http_only" in probe_errors if probe_errors else False
# HTTP service info with interpretation
http_status = record.get("http_status")
http_title = record.get("http_title", "")
http_server = record.get("http_server", "")
http_service_running = http_status is not None and (isinstance(http_status, int) and http_status > 0)
# Get HTTP status interpretation
http_status_info = get_http_status_info(http_status)
if not tls_enabled or probe_status == "no_tls" or is_http_only:
# For non-TLS ports (including HTTP-only), return minimal entry
if http_service_running:
note = f"HTTP {http_status} - {http_status_info['description']}"
service_status = http_status_info["type"]
else:
note = "No service detected"
service_status = "no_service"
return {
"_host": host,
"_port": port,
"asset": {
"host": host,
"port": port,
"timestamp": datetime.now(timezone.utc).isoformat()
},
"tls_enabled": False,
"probe_status": service_status,
"os": record.get("os"),
"http_service": {
"running": http_service_running,
"status_code": http_status,
"status_type": http_status_info["type"],
"status_description": http_status_info["description"],
"status_color": http_status_info["color"],
"status_severity": http_status_info["severity"],
"title": http_title if http_title else None,
"server": http_server if http_server else None
},
"tls_configuration": {
"version": "NO_TLS",
"cipher_suite": None,
"has_forward_secrecy": None
},
"cryptographic_primitives": {},
"key_exchange": {
"curve": None,
"pqc_safe": None,
"note": note
},
"certificate_curve": {
"curve": None,
"display": None,
"pqc_safe": None,
"note": note
},
"quantum_vulnerability": {
"pqc_ready": None,
"key_exchange_safe": None,
"certificate_safe": None,
"vulnerable_components": [],
"note": f"Cannot assess - {note.lower()}"
},
"certificate": {
"subject": None,
"issuer": None,
"valid": None,
"has_issues": None,
"note": note
},
"pqc_migration": {
"priority": "INFO",
"priority_score": 0,
"timeline": "N/A",
"complexity": "LOW",
"effort": "Enable TLS/HTTPS first",
"note": "Enable TLS first before PQC migration"
},
"recommendations": [{
"action": "Enable TLS/HTTPS",
"priority": "HIGH" if http_service_running else "MEDIUM",
"reason": f"This port is running unencrypted HTTP ({note})" if http_service_running else "No HTTP service detected on this port"
}]
}
# Check for incomplete scan (has TLS but missing cipher/curve)
if probe_status == "incomplete":
return {
"_host": host,
"_port": port,
"asset": {
"host": host,
"port": port,
"timestamp": datetime.now(timezone.utc).isoformat()
},
"tls_enabled": True,
"probe_status": "incomplete",
"tls_configuration": {
"version": tls_version.upper() if tls_version else "UNKNOWN",
"cipher_suite": None,
"has_forward_secrecy": None
},
"cryptographic_primitives": {},
"key_exchange": {
"curve": None,
"pqc_safe": None,
"note": "Incomplete scan - could not retrieve key exchange info"
},
"certificate_curve": {
"curve": None,
"display": None,
"pqc_safe": None,
"note": "Incomplete scan - could not retrieve certificate info"
},
"quantum_vulnerability": {
"pqc_ready": None,
"key_exchange_safe": None,
"certificate_safe": None,
"vulnerable_components": [],
"note": "Cannot assess - incomplete scan data"
},
"certificate": {
"subject": clean_value(record.get("cert_subject_cn")),
"issuer": clean_value(record.get("cert_issuer_cn")),
"valid": record.get("cert_valid"),
"has_issues": None,
"note": "Incomplete scan"
},
"pqc_migration": {
"priority": "UNKNOWN",
"priority_score": 0,
"timeline": "N/A",
"complexity": "UNKNOWN",
"effort": "Rescan needed for complete assessment",
"note": "Rescan needed for complete assessment"
},
"recommendations": [{
"action": "Rescan this host",
"priority": "MEDIUM",
"reason": "TLS detected but could not retrieve cipher/certificate details"
}]
}
# Build CBOM entry
cbom_entry = {
"_host": host,
"_port": port,
"probe_status": probe_status,
"asset": {
"host": host,
"port": port,
"timestamp": datetime.now(timezone.utc).isoformat()
},
"tls_enabled": True,
"os": record.get("os"),
"tls_configuration": {
"version": tls_version.upper(),
"cipher_suite": cipher,
"has_forward_secrecy": record.get("has_forward_secrecy",
tls_version == "tls13" if tls_version else False)