medic-cli 0.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
medic/checks/tls.py ADDED
@@ -0,0 +1,255 @@
1
+ """TLS/SSL certificate and handshake health checks."""
2
+
3
+ import fnmatch
4
+ import socket
5
+ import ssl
6
+ import time
7
+ from datetime import datetime, timezone
8
+ from typing import Any, Dict, List, Optional
9
+
10
+ try:
11
+ from cryptography import x509
12
+ from cryptography.hazmat.backends import default_backend
13
+ from cryptography.x509.oid import NameOID
14
+ HAS_CRYPTOGRAPHY = True
15
+ except ImportError:
16
+ HAS_CRYPTOGRAPHY = False
17
+
18
+ from medic.checks.tcp import parse_host_port
19
+ from medic.core.base import BaseCheck, timed_execution
20
+ from medic.core.enums import CheckCategory, CheckStatus
21
+ from medic.core.models import CheckResult
22
+
23
+
24
+ class TLSCheck(BaseCheck):
25
+ """Checks TLS/SSL certificate validity, expiration, issuer, SANs, and protocol version."""
26
+
27
+ category = CheckCategory.TLS
28
+
29
+ def __init__(
30
+ self,
31
+ host: str,
32
+ port: int = 443,
33
+ name: Optional[str] = None,
34
+ warn_days: int = 30,
35
+ crit_days: int = 7,
36
+ sni_hostname: Optional[str] = None,
37
+ check_hostname: bool = True,
38
+ timeout: float = 8.0,
39
+ enabled: bool = True,
40
+ ) -> None:
41
+ chk_name = name or f"TLS {host}:{port}"
42
+ super().__init__(name=chk_name, timeout=timeout, enabled=enabled)
43
+ self.host = host.strip()
44
+ self.port = port
45
+ self.warn_days = warn_days
46
+ self.crit_days = crit_days
47
+ self.sni_hostname = sni_hostname or self.host
48
+ self.check_hostname = check_hostname
49
+
50
+ @classmethod
51
+ def from_target(cls, target: str, default_port: int = 443, **kwargs: Any) -> "TLSCheck":
52
+ """Factory method to instantiate from 'host:port' string."""
53
+ host, port = parse_host_port(target, default_port=default_port)
54
+ return cls(host=host, port=port, **kwargs)
55
+
56
+ def _matches_san(self, hostname: str, sans: List[str]) -> bool:
57
+ """Check if hostname matches any Subject Alternative Name."""
58
+ h_lower = hostname.lower()
59
+ for san in sans:
60
+ s_lower = san.lower()
61
+ if s_lower == h_lower:
62
+ return True
63
+ if s_lower.startswith("*."):
64
+ if fnmatch.fnmatch(h_lower, s_lower):
65
+ return True
66
+ return False
67
+
68
+ def run(self) -> CheckResult:
69
+ target_str = f"{self.host}:{self.port}"
70
+ with timed_execution() as timer:
71
+ # Create SSL Context
72
+ ctx = ssl.create_default_context()
73
+ if not self.check_hostname:
74
+ ctx.check_hostname = False
75
+ ctx.verify_mode = ssl.CERT_NONE
76
+
77
+ ssock: Optional[ssl.SSLSocket] = None
78
+
79
+ try:
80
+ raw_sock = socket.create_connection((self.host, self.port), timeout=self.timeout)
81
+ handshake_start = time.perf_counter()
82
+ ssock = ctx.wrap_socket(raw_sock, server_hostname=self.sni_hostname)
83
+ handshake_ms = (time.perf_counter() - handshake_start) * 1000.0
84
+
85
+ cipher_info = ssock.cipher()
86
+ tls_version = ssock.version()
87
+ der_cert = ssock.getpeercert(binary_form=True)
88
+ dict_cert = ssock.getpeercert(binary_form=False)
89
+
90
+ except ssl.SSLCertVerificationError as e:
91
+ return CheckResult(
92
+ name=self.name,
93
+ category=self.category,
94
+ status=CheckStatus.FAILED,
95
+ message=f"TLS certificate verification error: {e.verify_message or str(e)}",
96
+ target=target_str,
97
+ latency_ms=timer["elapsed_ms"],
98
+ remediation="Verify certificate trust chain, issuer CA, or hostname mismatch.",
99
+ )
100
+ except ssl.SSLError as e:
101
+ return CheckResult(
102
+ name=self.name,
103
+ category=self.category,
104
+ status=CheckStatus.FAILED,
105
+ message=f"TLS handshake failed: {e}",
106
+ target=target_str,
107
+ latency_ms=timer["elapsed_ms"],
108
+ remediation=f"Ensure server at {target_str} supports TLS and acceptable cipher suites.",
109
+ )
110
+ except TimeoutError:
111
+ return CheckResult(
112
+ name=self.name,
113
+ category=self.category,
114
+ status=CheckStatus.FAILED,
115
+ message=f"Connection timed out after {self.timeout:.1f}s",
116
+ target=target_str,
117
+ latency_ms=timer["elapsed_ms"],
118
+ remediation=f"Check firewall or network routing for port {self.port}.",
119
+ )
120
+ except Exception as e:
121
+ return CheckResult(
122
+ name=self.name,
123
+ category=self.category,
124
+ status=CheckStatus.FAILED,
125
+ message=f"TLS connection error: {e}",
126
+ target=target_str,
127
+ latency_ms=timer["elapsed_ms"],
128
+ )
129
+ finally:
130
+ if ssock is not None:
131
+ try:
132
+ ssock.close()
133
+ except Exception:
134
+ pass
135
+
136
+ # Extract certificate details
137
+ now_utc = datetime.now(timezone.utc)
138
+ not_after_utc: Optional[datetime] = None
139
+ not_before_utc: Optional[datetime] = None
140
+ issuer_cn = "Unknown"
141
+ subject_cn = "Unknown"
142
+ sans: List[str] = []
143
+ serial_number: Optional[str] = None
144
+
145
+ if HAS_CRYPTOGRAPHY and der_cert:
146
+ try:
147
+ cert = x509.load_der_x509_certificate(der_cert, default_backend())
148
+ try:
149
+ not_after_utc = cert.not_valid_after_utc
150
+ not_before_utc = cert.not_valid_before_utc
151
+ except AttributeError:
152
+ # Fallback for older cryptography versions
153
+ not_after_utc = cert.not_valid_after.replace(tzinfo=timezone.utc)
154
+ not_before_utc = cert.not_valid_before.replace(tzinfo=timezone.utc)
155
+
156
+ serial_number = hex(cert.serial_number)
157
+
158
+ # Issuer CN
159
+ issuers = cert.issuer.get_attributes_for_oid(NameOID.COMMON_NAME)
160
+ if issuers:
161
+ issuer_cn = str(issuers[0].value)
162
+ else:
163
+ orgs = cert.issuer.get_attributes_for_oid(NameOID.ORGANIZATION_NAME)
164
+ if orgs:
165
+ issuer_cn = str(orgs[0].value)
166
+
167
+ # Subject CN
168
+ subjects = cert.subject.get_attributes_for_oid(NameOID.COMMON_NAME)
169
+ if subjects:
170
+ subject_cn = str(subjects[0].value)
171
+
172
+ # SANs
173
+ try:
174
+ san_ext = cert.extensions.get_extension_for_class(x509.SubjectAlternativeName)
175
+ sans = [str(name) for name in san_ext.value.get_values_for_type(x509.DNSName)]
176
+ except Exception:
177
+ sans = [subject_cn] if subject_cn != "Unknown" else []
178
+ except Exception:
179
+ pass
180
+
181
+ # Fallback to ssl dict_cert if cryptography extraction was unavailable or incomplete
182
+ if not_after_utc is None and dict_cert:
183
+ na_str = dict_cert.get("notAfter")
184
+ if na_str:
185
+ try:
186
+ not_after_utc = datetime.strptime(
187
+ str(na_str), "%b %d %H:%M:%S %Y %Z"
188
+ ).replace(tzinfo=timezone.utc)
189
+ except Exception:
190
+ pass
191
+ for item in dict_cert.get("subjectAltName", []):
192
+ if item[0] == "DNS":
193
+ sans.append(str(item[1]))
194
+
195
+ # Calculate days remaining
196
+ days_remaining: Optional[int] = None
197
+ if not_after_utc:
198
+ delta = not_after_utc - now_utc
199
+ days_remaining = delta.days
200
+
201
+ # Determine check status
202
+ status = CheckStatus.PASSED
203
+ remediation = None
204
+
205
+ if days_remaining is not None:
206
+ if days_remaining < 0:
207
+ status = CheckStatus.FAILED
208
+ remediation = f"Certificate expired {abs(days_remaining)} days ago! Renew certificate immediately via certbot or ACME provider."
209
+ elif days_remaining <= self.crit_days:
210
+ status = CheckStatus.FAILED
211
+ remediation = f"Certificate expires in {days_remaining} days (critical threshold: {self.crit_days}d). Renew certificate now."
212
+ elif days_remaining <= self.warn_days:
213
+ status = CheckStatus.WARNING
214
+ remediation = f"Certificate expires in {days_remaining} days (warning threshold: {self.warn_days}d). Plan renewal soon."
215
+ else:
216
+ status = CheckStatus.WARNING
217
+ remediation = "Could not parse certificate expiration date."
218
+
219
+ # Verify SAN match
220
+ if self.check_hostname and sans and not self._matches_san(self.sni_hostname, sans):
221
+ status = CheckStatus.FAILED
222
+ remediation = f"Hostname '{self.sni_hostname}' is not covered by certificate SANs: {sans[:5]}"
223
+
224
+ cipher_name = cipher_info[0] if cipher_info else "Unknown"
225
+ days_text = f"{days_remaining} days left" if days_remaining is not None else "unknown expiry"
226
+ expiry_date_str = not_after_utc.strftime("%Y-%m-%d") if not_after_utc else "Unknown"
227
+
228
+ msg = f"TLS Valid ({days_text}, expires: {expiry_date_str}, issuer: {issuer_cn}, {tls_version})"
229
+
230
+ details: Dict[str, Any] = {
231
+ "host": self.host,
232
+ "port": self.port,
233
+ "sni_hostname": self.sni_hostname,
234
+ "tls_version": tls_version,
235
+ "cipher": cipher_name,
236
+ "issuer": issuer_cn,
237
+ "subject": subject_cn,
238
+ "days_remaining": days_remaining,
239
+ "expires_at": not_after_utc.isoformat() if not_after_utc else None,
240
+ "valid_from": not_before_utc.isoformat() if not_before_utc else None,
241
+ "sans": sans,
242
+ "serial_number": serial_number,
243
+ "handshake_ms": round(handshake_ms, 2),
244
+ }
245
+
246
+ return CheckResult(
247
+ name=self.name,
248
+ category=self.category,
249
+ status=status,
250
+ message=msg,
251
+ target=target_str,
252
+ latency_ms=handshake_ms,
253
+ details=details,
254
+ remediation=remediation,
255
+ )