orbit-security 1.2.5__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.
Files changed (95) hide show
  1. orbit_security/__init__.py +51 -0
  2. orbit_security/_runtime_paths.py +52 -0
  3. orbit_security/agency_retainer.py +803 -0
  4. orbit_security/agency_teardown_publisher.py +170 -0
  5. orbit_security/agent_perimeter_sentinel.py +144 -0
  6. orbit_security/ast_sentinel.py +661 -0
  7. orbit_security/baseline_diff.py +494 -0
  8. orbit_security/billing/__init__.py +79 -0
  9. orbit_security/billing/catalog.py +275 -0
  10. orbit_security/billing/fulfillment.py +359 -0
  11. orbit_security/billing/onboarding.py +497 -0
  12. orbit_security/billing/stripe_client.py +316 -0
  13. orbit_security/billing/webhooks.py +372 -0
  14. orbit_security/billing_onboarding.py +52 -0
  15. orbit_security/blackboard.py +940 -0
  16. orbit_security/cert_transparency.py +710 -0
  17. orbit_security/cisa_kev.py +432 -0
  18. orbit_security/cli.py +236 -0
  19. orbit_security/cli_handlers/__init__.py +37 -0
  20. orbit_security/cli_handlers/commands.py +310 -0
  21. orbit_security/cli_handlers/diff_cmd.py +100 -0
  22. orbit_security/cli_handlers/scan_cmd.py +265 -0
  23. orbit_security/client_bundle_exporter.py +1436 -0
  24. orbit_security/cloud_sentinels.py +1405 -0
  25. orbit_security/core_affinity.py +101 -0
  26. orbit_security/deal_desk.py +660 -0
  27. orbit_security/dns_cache.py +462 -0
  28. orbit_security/egress_guard.py +349 -0
  29. orbit_security/epss.py +359 -0
  30. orbit_security/event_shuttle.py +434 -0
  31. orbit_security/fleet.py +549 -0
  32. orbit_security/gemini_cli_bridge.py +590 -0
  33. orbit_security/geo_panel.py +455 -0
  34. orbit_security/ghost_dns.py +407 -0
  35. orbit_security/github_sentinel.py +466 -0
  36. orbit_security/ground_truth_gate.py +175 -0
  37. orbit_security/inbox_agent.py +1271 -0
  38. orbit_security/inbox_guardrail.py +278 -0
  39. orbit_security/inbox_triage_bridge.py +166 -0
  40. orbit_security/input_sanitizer.py +130 -0
  41. orbit_security/mailer.py +194 -0
  42. orbit_security/models.py +80 -0
  43. orbit_security/network_bonding.py +331 -0
  44. orbit_security/notifications.py +671 -0
  45. orbit_security/opencode_remediation.py +488 -0
  46. orbit_security/osint_verifier.py +586 -0
  47. orbit_security/perimeter/__init__.py +88 -0
  48. orbit_security/perimeter/_hooks.py +11 -0
  49. orbit_security/perimeter/cms_kev.py +659 -0
  50. orbit_security/perimeter/dns_auth.py +407 -0
  51. orbit_security/perimeter/exposures.py +341 -0
  52. orbit_security/perimeter/http_surface.py +536 -0
  53. orbit_security/perimeter/probes.py +134 -0
  54. orbit_security/perimeter/safety.py +209 -0
  55. orbit_security/perimeter/takeover.py +258 -0
  56. orbit_security/perimeter/tls_monitor.py +670 -0
  57. orbit_security/playtest_guard.py +424 -0
  58. orbit_security/private_alerting.py +415 -0
  59. orbit_security/public_apis_osint.py +134 -0
  60. orbit_security/py.typed +0 -0
  61. orbit_security/radar_lead_enricher.py +645 -0
  62. orbit_security/radar_proposal_stager.py +553 -0
  63. orbit_security/radar_telemetry.py +2088 -0
  64. orbit_security/recon.py +849 -0
  65. orbit_security/recon_harvester.py +463 -0
  66. orbit_security/remediation.py +843 -0
  67. orbit_security/report_verifier.py +421 -0
  68. orbit_security/reporter.py +854 -0
  69. orbit_security/reporting/__init__.py +15 -0
  70. orbit_security/reporting/client_portal.py +691 -0
  71. orbit_security/scanner.py +337 -0
  72. orbit_security/scoring.py +573 -0
  73. orbit_security/sherlock_osint.py +276 -0
  74. orbit_security/signatures.py +454 -0
  75. orbit_security/stripe_checkout.py +489 -0
  76. orbit_security/stripe_webhook.py +226 -0
  77. orbit_security/threat_radar.py +513 -0
  78. orbit_security/tools/__init__.py +193 -0
  79. orbit_security/tools/adhx_client.py +392 -0
  80. orbit_security/tools/attack_tree.py +603 -0
  81. orbit_security/tools/compact_radar_feed.py +209 -0
  82. orbit_security/tools/deploy_oracle_sentinel.py +281 -0
  83. orbit_security/tools/duckdb_analytics.py +302 -0
  84. orbit_security/tools/embedding_search.py +460 -0
  85. orbit_security/tools/everything_search.py +468 -0
  86. orbit_security/tools/ffmpeg_renderer.py +484 -0
  87. orbit_security/tools/gemini_multimodal.py +387 -0
  88. orbit_security/tools/koa_gemma_router.py +367 -0
  89. orbit_security/tools/secret_harvester.py +103 -0
  90. orbit_security/tools/xh_probe.py +546 -0
  91. orbit_security/tools/yt_threat_harvester.py +410 -0
  92. orbit_security-1.2.5.dist-info/METADATA +369 -0
  93. orbit_security-1.2.5.dist-info/RECORD +95 -0
  94. orbit_security-1.2.5.dist-info/WHEEL +4 -0
  95. orbit_security-1.2.5.dist-info/entry_points.txt +5 -0
@@ -0,0 +1,670 @@
1
+ """Passive TLS Certificate Expiry, Protocol Hygiene & Certificate Transparency Delta Monitor (Slice 5.1).
2
+
3
+ Performs read-only TLS handshake inspection and passive Certificate Transparency
4
+ (crt.sh) log diffing under strict SSRF IP guards and tight batch timeouts.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import asyncio
10
+ import datetime
11
+ import socket
12
+ import ssl
13
+ from dataclasses import dataclass, field
14
+ from typing import Any, Dict, Iterable, List, Optional, Sequence, Set
15
+
16
+ import httpx
17
+
18
+ from orbit_security.egress_guard import create_guarded_async_httpx_client, enforce_egress_or_raise
19
+ from orbit_security.models import Finding, Severity
20
+ from orbit_security.perimeter.safety import PublicHostOnlyRoE, async_is_safe_host, is_safe_host
21
+
22
+ WEAK_TLS_PROTOCOLS = frozenset({"SSLv2", "SSLv3", "TLSv1", "TLSv1.0", "TLSv1.1"})
23
+ WEAK_CIPHER_TOKENS = ("RC4", "DES", "3DES", "NULL", "EXPORT", "MD5", "ANON")
24
+
25
+ TLS_CT_SARIF_RULES: List[Dict[str, Any]] = [
26
+ {
27
+ "id": "ORBIT-TLS-EXPIRY",
28
+ "name": "TlsCertificateExpiry",
29
+ "shortDescription": {"text": "SSL/TLS certificate expired or approaching expiration."},
30
+ "defaultConfiguration": {"level": "error"},
31
+ },
32
+ {
33
+ "id": "ORBIT-TLS-CHAIN",
34
+ "name": "TlsCertificateChainFailure",
35
+ "shortDescription": {"text": "TLS certificate chain validation or handshake failed."},
36
+ "defaultConfiguration": {"level": "error"},
37
+ },
38
+ {
39
+ "id": "ORBIT-TLS-PROTOCOL",
40
+ "name": "DeprecatedTlsProtocol",
41
+ "shortDescription": {"text": "Deprecated SSL/TLS protocol version negotiated."},
42
+ "defaultConfiguration": {"level": "error"},
43
+ },
44
+ {
45
+ "id": "ORBIT-TLS-CIPHER",
46
+ "name": "WeakTlsCipherSuite",
47
+ "shortDescription": {"text": "Weak or legacy TLS cipher suite negotiated."},
48
+ "defaultConfiguration": {"level": "warning"},
49
+ },
50
+ {
51
+ "id": "ORBIT-CT-WILDCARD",
52
+ "name": "UnexpectedWildcardCertificate",
53
+ "shortDescription": {"text": "Unexpected wildcard certificate observed in CT logs."},
54
+ "defaultConfiguration": {"level": "error"},
55
+ },
56
+ {
57
+ "id": "ORBIT-CT-DELTA",
58
+ "name": "UnexpectedSubdomainCertificate",
59
+ "shortDescription": {"text": "New or shadow subdomain certificate observed in CT logs."},
60
+ "defaultConfiguration": {"level": "warning"},
61
+ },
62
+ {
63
+ "id": "ORBIT-CT-ISSUER",
64
+ "name": "UnauthorizedCertificateIssuer",
65
+ "shortDescription": {"text": "Certificate issued by CA outside allowed agency issuer list."},
66
+ "defaultConfiguration": {"level": "error"},
67
+ },
68
+ {
69
+ "id": "ORBIT-TLS-GENERAL",
70
+ "name": "TlsPerimeterFinding",
71
+ "shortDescription": {"text": "General TLS or Certificate Transparency perimeter finding."},
72
+ "defaultConfiguration": {"level": "warning"},
73
+ },
74
+ ]
75
+
76
+ _SARIF_RULE_INDEX = {rule["id"]: idx for idx, rule in enumerate(TLS_CT_SARIF_RULES)}
77
+
78
+
79
+ @dataclass
80
+ class TlsCertificateSnapshot:
81
+ """Point-in-time passive TLS handshake observation."""
82
+
83
+ domain: str
84
+ port: int = 443
85
+ subject_cn: str = ""
86
+ issuer_cn: str = ""
87
+ san_dns_names: List[str] = field(default_factory=list)
88
+ not_before: Optional[datetime.datetime] = None
89
+ not_after: Optional[datetime.datetime] = None
90
+ days_remaining: Optional[int] = None
91
+ protocol_version: str = ""
92
+ cipher_suite: str = ""
93
+ chain_valid: bool = True
94
+ error: str = ""
95
+
96
+
97
+ @dataclass
98
+ class CtIssuanceRecord:
99
+ """Normalized Certificate Transparency (crt.sh) log issuance entry."""
100
+
101
+ common_name: str
102
+ name_values: List[str] = field(default_factory=list)
103
+ issuer_name: str = ""
104
+ not_before: str = ""
105
+ not_after: str = ""
106
+ entry_timestamp: str = ""
107
+ serial_number: str = ""
108
+
109
+
110
+ @dataclass
111
+ class CtDeltaReport:
112
+ """Diff between observed CT log issuances and expected domain/CA baselines."""
113
+
114
+ domain: str
115
+ total_records: int
116
+ discovered_subdomains: List[str] = field(default_factory=list)
117
+ baseline_subdomains: List[str] = field(default_factory=list)
118
+ new_subdomains: List[str] = field(default_factory=list)
119
+ unexpected_wildcards: List[str] = field(default_factory=list)
120
+ unexpected_issuers: List[str] = field(default_factory=list)
121
+
122
+
123
+ def _extract_x509_attr(entries: Sequence[Any], target_key: str) -> str:
124
+ for rdn in entries or ():
125
+ for pair in rdn:
126
+ if len(pair) == 2 and pair[0] == target_key:
127
+ return str(pair[1])
128
+ return ""
129
+
130
+
131
+ def _parse_cert_time(raw: Optional[str]) -> Optional[datetime.datetime]:
132
+ if not raw:
133
+ return None
134
+ for fmt in ("%b %d %H:%M:%S %Y %Z", "%b %d %H:%M:%S %Y GMT"):
135
+ try:
136
+ dt = datetime.datetime.strptime(raw.strip(), fmt)
137
+ return dt.replace(tzinfo=datetime.timezone.utc)
138
+ except ValueError:
139
+ continue
140
+ return None
141
+
142
+
143
+ def evaluate_tls_snapshot(
144
+ snapshot: TlsCertificateSnapshot,
145
+ *,
146
+ expiry_warn_days: int = 30,
147
+ expiry_high_days: int = 14,
148
+ ) -> List[Finding]:
149
+ """Convert a TlsCertificateSnapshot into prioritized Orbit Security Findings."""
150
+ findings: List[Finding] = []
151
+ target = f"{snapshot.domain}:{snapshot.port}" if snapshot.port != 443 else snapshot.domain
152
+
153
+ if not snapshot.chain_valid:
154
+ err_lower = snapshot.error.lower()
155
+ if "ssrf" in err_lower or "disallowed" in err_lower:
156
+ return [
157
+ Finding(
158
+ title="Target Disallowed (SSRF / Internal Target)",
159
+ severity=Severity.HIGH,
160
+ category="Transport Security",
161
+ description=f"TLS inspection blocked for internal, loopback, or metadata target '{snapshot.domain}'.",
162
+ remediation="Provide a public Internet FQDN for passive TLS monitoring.",
163
+ target=target,
164
+ evidence=snapshot.error or f"Blocked host: {snapshot.domain}",
165
+ )
166
+ ]
167
+ if "timed out" in err_lower or "timeout" in err_lower:
168
+ return [
169
+ Finding(
170
+ title="TLS Handshake Timeout",
171
+ severity=Severity.MEDIUM,
172
+ category="Transport Security",
173
+ description=f"Passive TLS handshake to {target} exceeded the strict batch timeout.",
174
+ remediation="Verify HTTPS port 443 reachability and edge firewall responsiveness.",
175
+ target=target,
176
+ evidence=snapshot.error,
177
+ )
178
+ ]
179
+ findings.append(
180
+ Finding(
181
+ title="TLS Certificate Chain Validation Failure",
182
+ severity=Severity.HIGH,
183
+ category="Transport Security",
184
+ description=f"TLS certificate verification failed for {target}: {snapshot.error or 'untrusted chain'}.",
185
+ remediation="Deploy a valid, CA-signed TLS certificate chain with matching SAN entries and intermediate certificates.",
186
+ target=target,
187
+ evidence=snapshot.error or "chain_valid=False",
188
+ )
189
+ )
190
+ return findings
191
+
192
+ if snapshot.days_remaining is not None:
193
+ if snapshot.days_remaining <= 0:
194
+ findings.append(
195
+ Finding(
196
+ title="SSL/TLS Certificate Expired",
197
+ severity=Severity.CRITICAL,
198
+ category="Transport Security",
199
+ description=(
200
+ f"The TLS certificate for {target} expired {abs(snapshot.days_remaining)} day(s) ago. "
201
+ "Browsers block visitors with full-screen security errors."
202
+ ),
203
+ remediation="Renew and deploy a valid TLS certificate immediately and verify automated ACME/Certbot renewal.",
204
+ target=target,
205
+ evidence=f"Expired ({snapshot.days_remaining}d remaining); issuer={snapshot.issuer_cn or 'unknown'}",
206
+ )
207
+ )
208
+ elif snapshot.days_remaining <= expiry_high_days:
209
+ findings.append(
210
+ Finding(
211
+ title=f"SSL/TLS Certificate Expiring Soon ({snapshot.days_remaining} days left)",
212
+ severity=Severity.HIGH,
213
+ category="Transport Security",
214
+ description=f"The TLS certificate for {target} expires in {snapshot.days_remaining} day(s).",
215
+ remediation="Trigger immediate certificate renewal and verify automated renewal hooks before outage occurs.",
216
+ target=target,
217
+ evidence=f"{snapshot.days_remaining} days remaining; issuer={snapshot.issuer_cn or 'unknown'}",
218
+ )
219
+ )
220
+ elif snapshot.days_remaining <= expiry_warn_days:
221
+ findings.append(
222
+ Finding(
223
+ title=f"SSL/TLS Certificate Renewal Window ({snapshot.days_remaining} days left)",
224
+ severity=Severity.MEDIUM,
225
+ category="Transport Security",
226
+ description=f"The TLS certificate for {target} enters its 30-day renewal window ({snapshot.days_remaining} day(s) left).",
227
+ remediation="Confirm automated certificate renewal (Let's Encrypt / Cloudflare / ACM) is scheduled cleanly.",
228
+ target=target,
229
+ evidence=f"{snapshot.days_remaining} days remaining; issuer={snapshot.issuer_cn or 'unknown'}",
230
+ )
231
+ )
232
+
233
+ proto = (snapshot.protocol_version or "").strip()
234
+ if proto in WEAK_TLS_PROTOCOLS:
235
+ findings.append(
236
+ Finding(
237
+ title=f"Deprecated TLS Protocol Negotiated ({proto})",
238
+ severity=Severity.HIGH,
239
+ category="Transport Security",
240
+ description=f"Server negotiated deprecated protocol {proto} on {target}, exposing sessions to downgrade attacks.",
241
+ remediation="Disable SSLv3, TLS 1.0, and TLS 1.1; enforce TLS 1.2+ with TLS 1.3 preferred.",
242
+ target=target,
243
+ evidence=f"Negotiated protocol: {proto}",
244
+ )
245
+ )
246
+
247
+ cipher = (snapshot.cipher_suite or "").strip()
248
+ if cipher and any(tok in cipher.upper() for tok in WEAK_CIPHER_TOKENS):
249
+ findings.append(
250
+ Finding(
251
+ title=f"Weak TLS Cipher Suite Negotiated ({cipher})",
252
+ severity=Severity.MEDIUM,
253
+ category="Transport Security",
254
+ description=f"Server negotiated weak legacy cipher suite '{cipher}' on {target}.",
255
+ remediation="Configure modern AEAD cipher suites (ECDHE + AES-GCM / ChaCha20-Poly1305) and disable legacy ciphers.",
256
+ target=target,
257
+ evidence=f"Negotiated cipher: {cipher}",
258
+ )
259
+ )
260
+
261
+ return findings
262
+
263
+
264
+ def parse_crtsh_entries(raw_entries: Sequence[Dict[str, Any]], domain: str) -> List[CtIssuanceRecord]:
265
+ """Normalize raw crt.sh JSON entries scoped to *domain*."""
266
+ clean_domain = (domain or "").strip().lower().rstrip(".")
267
+ records: List[CtIssuanceRecord] = []
268
+ seen_keys: Set[tuple[str, str, str]] = set()
269
+
270
+ for entry in raw_entries or ():
271
+ if not isinstance(entry, dict):
272
+ continue
273
+ raw_names = str(entry.get("name_value") or entry.get("common_name") or "")
274
+ names: List[str] = []
275
+ for item in raw_names.splitlines():
276
+ candidate = item.strip().lower().rstrip(".")
277
+ if not candidate:
278
+ continue
279
+ bare = candidate[2:] if candidate.startswith("*.") else candidate
280
+ if bare == clean_domain or bare.endswith(f".{clean_domain}"):
281
+ if candidate not in names:
282
+ names.append(candidate)
283
+ if not names:
284
+ continue
285
+
286
+ cn = str(entry.get("common_name") or names[0]).strip().lower().rstrip(".")
287
+ issuer = str(entry.get("issuer_name") or "").strip()
288
+ serial = str(entry.get("serial_number") or "").strip()
289
+ dedup_key = (cn, serial, ",".join(sorted(names)))
290
+ if dedup_key in seen_keys:
291
+ continue
292
+ seen_keys.add(dedup_key)
293
+
294
+ records.append(
295
+ CtIssuanceRecord(
296
+ common_name=cn,
297
+ name_values=names,
298
+ issuer_name=issuer,
299
+ not_before=str(entry.get("not_before") or ""),
300
+ not_after=str(entry.get("not_after") or ""),
301
+ entry_timestamp=str(entry.get("entry_timestamp") or ""),
302
+ serial_number=serial,
303
+ )
304
+ )
305
+
306
+ return records
307
+
308
+
309
+ def detect_ct_delta(
310
+ domain: str,
311
+ records: Sequence[CtIssuanceRecord],
312
+ *,
313
+ known_subdomains: Optional[Iterable[str]] = None,
314
+ allowed_issuers: Optional[Iterable[str]] = None,
315
+ ) -> CtDeltaReport:
316
+ """Compare observed CT log issuances against known subdomain & CA baselines."""
317
+ clean_domain = (domain or "").strip().lower().rstrip(".")
318
+ baseline_set = {
319
+ s.strip().lower().rstrip(".")
320
+ for s in (known_subdomains or ())
321
+ if s and s.strip()
322
+ }
323
+ allowed_issuer_tokens = [a.strip().lower() for a in (allowed_issuers or ()) if a and a.strip()]
324
+
325
+ discovered: Set[str] = set()
326
+ unexpected_wildcards: Set[str] = set()
327
+ unexpected_issuers: Set[str] = set()
328
+
329
+ for rec in records:
330
+ for raw_name in rec.name_values:
331
+ clean_name = raw_name.strip().lower().rstrip(".")
332
+ if clean_name.startswith("*."):
333
+ if baseline_set and clean_name not in baseline_set:
334
+ unexpected_wildcards.add(clean_name)
335
+ bare = clean_name[2:]
336
+ else:
337
+ bare = clean_name
338
+ if bare == clean_domain or bare.endswith(f".{clean_domain}"):
339
+ discovered.add(bare)
340
+
341
+ if allowed_issuer_tokens and rec.issuer_name:
342
+ issuer_lower = rec.issuer_name.lower()
343
+ if not any(tok in issuer_lower for tok in allowed_issuer_tokens):
344
+ unexpected_issuers.add(rec.issuer_name)
345
+
346
+ baseline_bare = {b[2:] if b.startswith("*.") else b for b in baseline_set}
347
+ new_subdomains = sorted(discovered - baseline_bare) if baseline_bare else []
348
+
349
+ return CtDeltaReport(
350
+ domain=clean_domain,
351
+ total_records=len(records),
352
+ discovered_subdomains=sorted(discovered),
353
+ baseline_subdomains=sorted(baseline_bare),
354
+ new_subdomains=new_subdomains,
355
+ unexpected_wildcards=sorted(unexpected_wildcards),
356
+ unexpected_issuers=sorted(unexpected_issuers),
357
+ )
358
+
359
+
360
+ def evaluate_ct_delta(report: CtDeltaReport) -> List[Finding]:
361
+ """Convert CT delta anomalies into actionable Orbit Security Findings."""
362
+ findings: List[Finding] = []
363
+
364
+ if report.unexpected_wildcards:
365
+ findings.append(
366
+ Finding(
367
+ title="Unexpected Wildcard Certificate in CT Logs",
368
+ severity=Severity.HIGH,
369
+ category="Certificate Transparency",
370
+ description=(
371
+ f"Certificate Transparency logs recorded {len(report.unexpected_wildcards)} wildcard certificate(s) "
372
+ f"for {report.domain} outside the approved baseline."
373
+ ),
374
+ remediation="Verify wildcard certificate ownership immediately, revoke unauthorized certificates, and enforce DNS CAA records.",
375
+ target=report.domain,
376
+ evidence="Wildcards: " + ", ".join(report.unexpected_wildcards[:10]),
377
+ )
378
+ )
379
+
380
+ if report.new_subdomains:
381
+ findings.append(
382
+ Finding(
383
+ title="Unexpected Subdomain Certificate Issued in CT Logs",
384
+ severity=Severity.MEDIUM,
385
+ category="Certificate Transparency",
386
+ description=(
387
+ f"Detected {len(report.new_subdomains)} newly issued subdomain certificate(s) for {report.domain} "
388
+ "not present in the known domain baseline (potential shadow IT or rogue issuance)."
389
+ ),
390
+ remediation="Inventory newly issued subdomains, add legitimate hosts to the fleet baseline, or revoke unauthorized certs.",
391
+ target=report.domain,
392
+ evidence="New CT subdomains: " + ", ".join(report.new_subdomains[:15]),
393
+ )
394
+ )
395
+
396
+ if report.unexpected_issuers:
397
+ findings.append(
398
+ Finding(
399
+ title="Unauthorized Certificate Authority Issuance in CT Logs",
400
+ severity=Severity.HIGH,
401
+ category="Certificate Transparency",
402
+ description=(
403
+ f"Certificate Transparency logs show certificate(s) for {report.domain} issued by CA(s) "
404
+ "not listed in the agency's allowed issuer policy."
405
+ ),
406
+ remediation="Audit unexpected CA issuances and publish strict RFC 8659 DNS CAA issue/issuewild records.",
407
+ target=report.domain,
408
+ evidence="Unexpected CAs: " + " | ".join(report.unexpected_issuers[:5]),
409
+ )
410
+ )
411
+
412
+ return findings
413
+
414
+
415
+ def _sarif_rule_for_finding(finding: Finding) -> str:
416
+ title = finding.title.lower()
417
+ if "wildcard" in title:
418
+ return "ORBIT-CT-WILDCARD"
419
+ if "certificate authority" in title or "issuer" in title:
420
+ return "ORBIT-CT-ISSUER"
421
+ if "ct log" in title or "certificate transparency" in finding.category.lower():
422
+ return "ORBIT-CT-DELTA"
423
+ if "expired" in title or "expiring" in title or "renewal window" in title:
424
+ return "ORBIT-TLS-EXPIRY"
425
+ if "protocol" in title:
426
+ return "ORBIT-TLS-PROTOCOL"
427
+ if "cipher" in title:
428
+ return "ORBIT-TLS-CIPHER"
429
+ if "chain" in title or "timeout" in title or "ssrf" in title:
430
+ return "ORBIT-TLS-CHAIN"
431
+ return "ORBIT-TLS-GENERAL"
432
+
433
+
434
+ def _sarif_level(severity: Severity) -> str:
435
+ if severity in (Severity.CRITICAL, Severity.HIGH):
436
+ return "error"
437
+ if severity == Severity.MEDIUM:
438
+ return "warning"
439
+ return "note"
440
+
441
+
442
+ def findings_to_sarif(findings: Sequence[Finding], domain: str) -> Dict[str, Any]:
443
+ """Serialize TLS & CT monitor findings into a GitHub Code Scanning SARIF 2.1.0 report."""
444
+ results: List[Dict[str, Any]] = []
445
+ for f in findings:
446
+ rule_id = _sarif_rule_for_finding(f)
447
+ results.append(
448
+ {
449
+ "ruleId": rule_id,
450
+ "ruleIndex": _SARIF_RULE_INDEX[rule_id],
451
+ "level": _sarif_level(f.severity),
452
+ "message": {
453
+ "text": f"[{f.severity.value}] {f.title} ({f.target or domain}): {f.description} Evidence: {f.evidence}"
454
+ },
455
+ "locations": [
456
+ {
457
+ "physicalLocation": {
458
+ "artifactLocation": {
459
+ "uri": f"perimeter/{(f.target or domain).replace(':', '_')}",
460
+ "uriBaseId": "%SRCROOT%",
461
+ },
462
+ "region": {"startLine": 1, "startColumn": 1},
463
+ }
464
+ }
465
+ ],
466
+ "properties": {
467
+ "category": f.category,
468
+ "remediation": f.remediation,
469
+ "severity": f.severity.value,
470
+ },
471
+ }
472
+ )
473
+
474
+ return {
475
+ "$schema": "https://json.schemastore.org/sarif-2.1.0.json",
476
+ "version": "2.1.0",
477
+ "runs": [
478
+ {
479
+ "tool": {
480
+ "driver": {
481
+ "name": "Orbit Security TLS & CT Monitor",
482
+ "version": "1.3.0-dev",
483
+ "informationUri": "https://cmfh009.github.io/Orbit-Security/",
484
+ "rules": TLS_CT_SARIF_RULES,
485
+ }
486
+ },
487
+ "results": results,
488
+ }
489
+ ],
490
+ }
491
+
492
+
493
+ class TlsCertificateMonitor:
494
+ """Passive TLS certificate inspector and CT delta monitor with SSRF guards."""
495
+
496
+ def __init__(self, timeout: float = 4.0):
497
+ self.timeout = max(0.5, min(float(timeout), 15.0))
498
+
499
+ def inspect_tls(
500
+ self,
501
+ domain: str,
502
+ port: int = 443,
503
+ *,
504
+ now: Optional[datetime.datetime] = None,
505
+ ) -> TlsCertificateSnapshot:
506
+ """Perform a passive verified TLS handshake and extract certificate metadata."""
507
+ clean_domain = (domain or "").strip().lower().rstrip(".")
508
+ if not is_safe_host(clean_domain):
509
+ return TlsCertificateSnapshot(
510
+ domain=clean_domain or str(domain),
511
+ port=port,
512
+ chain_valid=False,
513
+ error=f"SSRF disallowed: '{domain}' resolves to private, loopback, or metadata space.",
514
+ )
515
+
516
+ try:
517
+ enforce_egress_or_raise(f"https://{clean_domain}:{port}", PublicHostOnlyRoE())
518
+ ctx = ssl.create_default_context()
519
+ with socket.create_connection((clean_domain, port), timeout=self.timeout) as sock: # roe-exempt: passive TLS X.509 handshake gated by enforce_egress_or_raise
520
+ with ctx.wrap_socket(sock, server_hostname=clean_domain) as ssock:
521
+ cert = ssock.getpeercert() or {}
522
+ proto = ssock.version() or ""
523
+ cipher_info = ssock.cipher()
524
+ cipher_name = str(cipher_info[0]) if cipher_info else ""
525
+
526
+ not_before = _parse_cert_time(cert.get("notBefore"))
527
+ not_after = _parse_cert_time(cert.get("notAfter"))
528
+ ref_now = now or datetime.datetime.now(datetime.timezone.utc)
529
+ if ref_now.tzinfo is None:
530
+ ref_now = ref_now.replace(tzinfo=datetime.timezone.utc)
531
+ days_left = (not_after - ref_now).days if not_after is not None else None
532
+
533
+ sans = [
534
+ str(val).lower()
535
+ for kind, val in (cert.get("subjectAltName") or ())
536
+ if kind == "DNS"
537
+ ]
538
+ return TlsCertificateSnapshot(
539
+ domain=clean_domain,
540
+ port=port,
541
+ subject_cn=_extract_x509_attr(cert.get("subject", ()), "commonName"),
542
+ issuer_cn=_extract_x509_attr(cert.get("issuer", ()), "commonName"),
543
+ san_dns_names=sans,
544
+ not_before=not_before,
545
+ not_after=not_after,
546
+ days_remaining=days_left,
547
+ protocol_version=proto,
548
+ cipher_suite=cipher_name,
549
+ chain_valid=True,
550
+ error="",
551
+ )
552
+ except ssl.SSLCertVerificationError as exc:
553
+ return TlsCertificateSnapshot(
554
+ domain=clean_domain,
555
+ port=port,
556
+ chain_valid=False,
557
+ error=str(exc),
558
+ )
559
+ except (socket.timeout, TimeoutError) as exc:
560
+ return TlsCertificateSnapshot(
561
+ domain=clean_domain,
562
+ port=port,
563
+ chain_valid=False,
564
+ error=f"TLS handshake timed out after {self.timeout:.1f}s: {exc}",
565
+ )
566
+ except Exception as exc:
567
+ return TlsCertificateSnapshot(
568
+ domain=clean_domain,
569
+ port=port,
570
+ chain_valid=False,
571
+ error=str(exc),
572
+ )
573
+
574
+ def audit_tls(
575
+ self,
576
+ domain: str,
577
+ port: int = 443,
578
+ *,
579
+ expiry_warn_days: int = 30,
580
+ expiry_high_days: int = 14,
581
+ ) -> List[Finding]:
582
+ snap = self.inspect_tls(domain, port=port)
583
+ return evaluate_tls_snapshot(
584
+ snap,
585
+ expiry_warn_days=expiry_warn_days,
586
+ expiry_high_days=expiry_high_days,
587
+ )
588
+
589
+ async def audit_tls_batch(
590
+ self,
591
+ domains: Sequence[str],
592
+ *,
593
+ port: int = 443,
594
+ concurrency: int = 8,
595
+ per_host_timeout: Optional[float] = None,
596
+ ) -> Dict[str, List[Finding]]:
597
+ """Audit multiple domains concurrently with strict per-host timeouts."""
598
+ budget = float(per_host_timeout if per_host_timeout is not None else self.timeout)
599
+ sem = asyncio.Semaphore(max(1, concurrency))
600
+ out: Dict[str, List[Finding]] = {}
601
+
602
+ async def _check_one(dom: str) -> None:
603
+ async with sem:
604
+ try:
605
+ snap = await asyncio.wait_for(
606
+ asyncio.to_thread(self.inspect_tls, dom, port),
607
+ timeout=budget,
608
+ )
609
+ out[dom] = evaluate_tls_snapshot(snap)
610
+ except asyncio.TimeoutError:
611
+ out[dom] = evaluate_tls_snapshot(
612
+ TlsCertificateSnapshot(
613
+ domain=dom,
614
+ port=port,
615
+ chain_valid=False,
616
+ error=f"TLS handshake timed out after {budget:.2f}s.",
617
+ )
618
+ )
619
+
620
+ await asyncio.gather(*(_check_one(d) for d in domains))
621
+ return out
622
+
623
+ async def fetch_ct_records(
624
+ self,
625
+ domain: str,
626
+ client: Optional[httpx.AsyncClient] = None,
627
+ ) -> List[CtIssuanceRecord]:
628
+ """Fetch passive Certificate Transparency records from crt.sh under SSRF guards."""
629
+ clean_domain = (domain or "").strip().lower().rstrip(".")
630
+ if not await async_is_safe_host(clean_domain):
631
+ return []
632
+
633
+ url = f"https://crt.sh/?q=%.{clean_domain}&output=json"
634
+ should_close = False
635
+ if client is None:
636
+ client = create_guarded_async_httpx_client(
637
+ roe_engine=PublicHostOnlyRoE(),
638
+ timeout=self.timeout,
639
+ )
640
+ should_close = True
641
+
642
+ try:
643
+ resp = await client.get(url)
644
+ if resp.status_code == 200:
645
+ payload = resp.json()
646
+ if isinstance(payload, list):
647
+ return parse_crtsh_entries(payload, clean_domain)
648
+ except Exception:
649
+ return []
650
+ finally:
651
+ if should_close:
652
+ await client.aclose()
653
+ return []
654
+
655
+ async def audit_ct_delta(
656
+ self,
657
+ domain: str,
658
+ *,
659
+ known_subdomains: Optional[Iterable[str]] = None,
660
+ allowed_issuers: Optional[Iterable[str]] = None,
661
+ client: Optional[httpx.AsyncClient] = None,
662
+ ) -> List[Finding]:
663
+ records = await self.fetch_ct_records(domain, client=client)
664
+ report = detect_ct_delta(
665
+ domain,
666
+ records,
667
+ known_subdomains=known_subdomains,
668
+ allowed_issuers=allowed_issuers,
669
+ )
670
+ return evaluate_ct_delta(report)