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/__init__.py +41 -0
- medic/__main__.py +8 -0
- medic/checks/__init__.py +30 -0
- medic/checks/dns.py +60 -0
- medic/checks/exec.py +90 -0
- medic/checks/http.py +181 -0
- medic/checks/ping.py +226 -0
- medic/checks/ssh.py +246 -0
- medic/checks/system.py +469 -0
- medic/checks/tcp.py +184 -0
- medic/checks/tls.py +255 -0
- medic/cli.py +572 -0
- medic/completion.py +46 -0
- medic/config.py +199 -0
- medic/core/__init__.py +18 -0
- medic/core/base.py +48 -0
- medic/core/enums.py +85 -0
- medic/core/models.py +116 -0
- medic/core/runner.py +212 -0
- medic/formatters/__init__.py +48 -0
- medic/formatters/base.py +14 -0
- medic/formatters/json_formatter.py +26 -0
- medic/formatters/junit_formatter.py +52 -0
- medic/formatters/rich_formatter.py +187 -0
- medic/formatters/text_formatter.py +60 -0
- medic/py.typed +0 -0
- medic_cli-0.1.1.dist-info/METADATA +175 -0
- medic_cli-0.1.1.dist-info/RECORD +32 -0
- medic_cli-0.1.1.dist-info/WHEEL +5 -0
- medic_cli-0.1.1.dist-info/entry_points.txt +2 -0
- medic_cli-0.1.1.dist-info/licenses/LICENSE +21 -0
- medic_cli-0.1.1.dist-info/top_level.txt +1 -0
medic/checks/ssh.py
ADDED
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
"""SSH service availability, banner, protocol version, and connectivity health checks."""
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
import socket
|
|
5
|
+
import subprocess
|
|
6
|
+
import time
|
|
7
|
+
from typing import Any, Dict, Optional, Tuple
|
|
8
|
+
|
|
9
|
+
from medic.checks.tcp import parse_host_port
|
|
10
|
+
from medic.core.base import BaseCheck
|
|
11
|
+
from medic.core.enums import CheckCategory, CheckStatus
|
|
12
|
+
from medic.core.models import CheckResult
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class SSHCheck(BaseCheck):
|
|
16
|
+
"""Checks SSH daemon availability, banner exchange, protocol version, and optional auth."""
|
|
17
|
+
|
|
18
|
+
category = CheckCategory.SSH
|
|
19
|
+
|
|
20
|
+
def __init__(
|
|
21
|
+
self,
|
|
22
|
+
host: str,
|
|
23
|
+
port: int = 22,
|
|
24
|
+
name: Optional[str] = None,
|
|
25
|
+
username: Optional[str] = None,
|
|
26
|
+
key_path: Optional[str] = None,
|
|
27
|
+
check_auth: bool = False,
|
|
28
|
+
timeout: float = 6.0,
|
|
29
|
+
warn_latency_ms: float = 300.0,
|
|
30
|
+
crit_latency_ms: float = 1500.0,
|
|
31
|
+
enabled: bool = True,
|
|
32
|
+
) -> None:
|
|
33
|
+
chk_name = name or f"SSH {host}:{port}"
|
|
34
|
+
super().__init__(name=chk_name, timeout=timeout, enabled=enabled)
|
|
35
|
+
self.host = host.strip()
|
|
36
|
+
self.port = port
|
|
37
|
+
self.username = username
|
|
38
|
+
self.key_path = key_path
|
|
39
|
+
self.check_auth = check_auth
|
|
40
|
+
self.warn_latency_ms = warn_latency_ms
|
|
41
|
+
self.crit_latency_ms = crit_latency_ms
|
|
42
|
+
|
|
43
|
+
@classmethod
|
|
44
|
+
def from_target(cls, target: str, default_port: int = 22, **kwargs: Any) -> "SSHCheck":
|
|
45
|
+
"""Factory method to instantiate from 'host:port' string."""
|
|
46
|
+
host, port = parse_host_port(target, default_port=default_port)
|
|
47
|
+
return cls(host=host, port=port, **kwargs)
|
|
48
|
+
|
|
49
|
+
def _check_socket_banner(self) -> Tuple[CheckStatus, str, Optional[float], Dict[str, Any], Optional[str]]:
|
|
50
|
+
"""Connect to SSH port and read RFC 4253 protocol identification string."""
|
|
51
|
+
target_str = f"{self.host}:{self.port}"
|
|
52
|
+
start_time = time.perf_counter()
|
|
53
|
+
sock: Optional[socket.socket] = None
|
|
54
|
+
|
|
55
|
+
try:
|
|
56
|
+
sock = socket.create_connection((self.host, self.port), timeout=self.timeout)
|
|
57
|
+
sock.settimeout(min(self.timeout, 3.0))
|
|
58
|
+
|
|
59
|
+
# Read server identification banner (max 255 bytes per RFC 4253)
|
|
60
|
+
banner_bytes = bytearray()
|
|
61
|
+
while len(banner_bytes) < 255:
|
|
62
|
+
chunk = sock.recv(1)
|
|
63
|
+
if not chunk:
|
|
64
|
+
break
|
|
65
|
+
banner_bytes.extend(chunk)
|
|
66
|
+
if banner_bytes.endswith(b"\n"):
|
|
67
|
+
break
|
|
68
|
+
|
|
69
|
+
elapsed_ms = (time.perf_counter() - start_time) * 1000.0
|
|
70
|
+
banner_str = banner_bytes.decode("utf-8", errors="replace").strip()
|
|
71
|
+
|
|
72
|
+
except ConnectionRefusedError:
|
|
73
|
+
elapsed_ms = (time.perf_counter() - start_time) * 1000.0
|
|
74
|
+
return (
|
|
75
|
+
CheckStatus.FAILED,
|
|
76
|
+
f"SSH connection refused on {target_str}",
|
|
77
|
+
elapsed_ms,
|
|
78
|
+
{},
|
|
79
|
+
"Check if sshd service is running (systemctl status sshd / service ssh status).",
|
|
80
|
+
)
|
|
81
|
+
except TimeoutError:
|
|
82
|
+
elapsed_ms = (time.perf_counter() - start_time) * 1000.0
|
|
83
|
+
return (
|
|
84
|
+
CheckStatus.FAILED,
|
|
85
|
+
f"SSH connection timed out after {self.timeout:.1f}s",
|
|
86
|
+
elapsed_ms,
|
|
87
|
+
{},
|
|
88
|
+
f"Check firewall / security group allowing inbound port {self.port}.",
|
|
89
|
+
)
|
|
90
|
+
except Exception as e:
|
|
91
|
+
elapsed_ms = (time.perf_counter() - start_time) * 1000.0
|
|
92
|
+
return (
|
|
93
|
+
CheckStatus.FAILED,
|
|
94
|
+
f"SSH connection error: {e}",
|
|
95
|
+
elapsed_ms,
|
|
96
|
+
{},
|
|
97
|
+
f"Could not connect to {target_str}.",
|
|
98
|
+
)
|
|
99
|
+
finally:
|
|
100
|
+
if sock is not None:
|
|
101
|
+
try:
|
|
102
|
+
# Send client protocol identification before close
|
|
103
|
+
sock.sendall(b"SSH-2.0-MedicHealthCheck_0.1.0\r\n")
|
|
104
|
+
except Exception:
|
|
105
|
+
pass
|
|
106
|
+
try:
|
|
107
|
+
sock.close()
|
|
108
|
+
except Exception:
|
|
109
|
+
pass
|
|
110
|
+
|
|
111
|
+
if not banner_str:
|
|
112
|
+
return (
|
|
113
|
+
CheckStatus.FAILED,
|
|
114
|
+
f"Port {self.port} open but returned empty SSH banner",
|
|
115
|
+
elapsed_ms,
|
|
116
|
+
{},
|
|
117
|
+
"Ensure an SSH daemon is listening on this port.",
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
# Parse banner RFC format: SSH-protoversion-softwareversion [comments]
|
|
121
|
+
# Example: SSH-2.0-OpenSSH_9.6p1 Ubuntu-3ubuntu13.4
|
|
122
|
+
match = re.match(r"^SSH-([0-9\.]+)-(\S+)(?:\s+(.*))?$", banner_str)
|
|
123
|
+
if not match:
|
|
124
|
+
return (
|
|
125
|
+
CheckStatus.FAILED,
|
|
126
|
+
f"Invalid SSH banner received: '{banner_str[:50]}'",
|
|
127
|
+
elapsed_ms,
|
|
128
|
+
{"raw_banner": banner_str},
|
|
129
|
+
f"Port {self.port} is open but does not appear to be an SSH service.",
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
proto_version = match.group(1)
|
|
133
|
+
software_version = match.group(2)
|
|
134
|
+
comment = match.group(3) or ""
|
|
135
|
+
|
|
136
|
+
status = CheckStatus.PASSED
|
|
137
|
+
remediation = None
|
|
138
|
+
|
|
139
|
+
if proto_version.startswith("1."):
|
|
140
|
+
status = CheckStatus.FAILED
|
|
141
|
+
remediation = "Insecure legacy SSH protocol version 1.x detected. Upgrade to SSHv2."
|
|
142
|
+
elif elapsed_ms >= self.crit_latency_ms:
|
|
143
|
+
status = CheckStatus.FAILED
|
|
144
|
+
remediation = f"SSH handshake response ({elapsed_ms:.1f}ms) is critically slow."
|
|
145
|
+
elif elapsed_ms >= self.warn_latency_ms:
|
|
146
|
+
status = CheckStatus.WARNING
|
|
147
|
+
remediation = f"SSH handshake response ({elapsed_ms:.1f}ms) is slower than expected."
|
|
148
|
+
|
|
149
|
+
msg = f"SSH-2.0 ({software_version}) reachable in {elapsed_ms:.1f}ms"
|
|
150
|
+
details: Dict[str, Any] = {
|
|
151
|
+
"host": self.host,
|
|
152
|
+
"port": self.port,
|
|
153
|
+
"protocol_version": proto_version,
|
|
154
|
+
"software_version": software_version,
|
|
155
|
+
"comment": comment,
|
|
156
|
+
"raw_banner": banner_str,
|
|
157
|
+
"banner_latency_ms": round(elapsed_ms, 2),
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
return status, msg, elapsed_ms, details, remediation
|
|
161
|
+
|
|
162
|
+
def _check_ssh_auth_cli(self) -> Tuple[CheckStatus, str, Optional[float], Dict[str, Any], Optional[str]]:
|
|
163
|
+
"""Test SSH batch mode authentication using ssh CLI client."""
|
|
164
|
+
cmd = [
|
|
165
|
+
"ssh",
|
|
166
|
+
"-o", "BatchMode=yes",
|
|
167
|
+
"-o", f"ConnectTimeout={int(self.timeout)}",
|
|
168
|
+
"-o", "StrictHostKeyChecking=accept-new",
|
|
169
|
+
"-p", str(self.port),
|
|
170
|
+
]
|
|
171
|
+
if self.key_path:
|
|
172
|
+
cmd.extend(["-i", self.key_path])
|
|
173
|
+
|
|
174
|
+
target = f"{self.username}@{self.host}" if self.username else self.host
|
|
175
|
+
cmd.extend([target, "echo MEDIC_SSH_OK"])
|
|
176
|
+
|
|
177
|
+
start_time = time.perf_counter()
|
|
178
|
+
try:
|
|
179
|
+
proc = subprocess.run(
|
|
180
|
+
cmd,
|
|
181
|
+
capture_output=True,
|
|
182
|
+
text=True,
|
|
183
|
+
timeout=self.timeout + 2.0,
|
|
184
|
+
)
|
|
185
|
+
elapsed_ms = (time.perf_counter() - start_time) * 1000.0
|
|
186
|
+
|
|
187
|
+
if proc.returncode == 0 and "MEDIC_SSH_OK" in proc.stdout:
|
|
188
|
+
return (
|
|
189
|
+
CheckStatus.PASSED,
|
|
190
|
+
f"SSH authenticated successfully to {target} in {elapsed_ms:.1f}ms",
|
|
191
|
+
elapsed_ms,
|
|
192
|
+
{"authenticated": True},
|
|
193
|
+
None,
|
|
194
|
+
)
|
|
195
|
+
elif proc.returncode == 255:
|
|
196
|
+
err_msg = proc.stderr.strip() or "Permission denied (publickey)"
|
|
197
|
+
return (
|
|
198
|
+
CheckStatus.FAILED,
|
|
199
|
+
f"SSH authentication failed: {err_msg}",
|
|
200
|
+
elapsed_ms,
|
|
201
|
+
{"exit_code": proc.returncode, "stderr": proc.stderr},
|
|
202
|
+
f"Ensure public key is added to ~/.ssh/authorized_keys on {self.host}.",
|
|
203
|
+
)
|
|
204
|
+
else:
|
|
205
|
+
return (
|
|
206
|
+
CheckStatus.WARNING,
|
|
207
|
+
f"SSH command exited with code {proc.returncode}: {proc.stderr.strip()}",
|
|
208
|
+
elapsed_ms,
|
|
209
|
+
{"exit_code": proc.returncode, "stderr": proc.stderr},
|
|
210
|
+
"Check user shell and permissions.",
|
|
211
|
+
)
|
|
212
|
+
except subprocess.TimeoutExpired:
|
|
213
|
+
elapsed_ms = (time.perf_counter() - start_time) * 1000.0
|
|
214
|
+
return (
|
|
215
|
+
CheckStatus.FAILED,
|
|
216
|
+
f"SSH authentication timed out after {self.timeout:.1f}s",
|
|
217
|
+
elapsed_ms,
|
|
218
|
+
{},
|
|
219
|
+
"Check network latency or SSH banner delays.",
|
|
220
|
+
)
|
|
221
|
+
except Exception as e:
|
|
222
|
+
elapsed_ms = (time.perf_counter() - start_time) * 1000.0
|
|
223
|
+
return (
|
|
224
|
+
CheckStatus.ERROR,
|
|
225
|
+
f"Failed to execute ssh command: {e}",
|
|
226
|
+
elapsed_ms,
|
|
227
|
+
{},
|
|
228
|
+
None,
|
|
229
|
+
)
|
|
230
|
+
|
|
231
|
+
def run(self) -> CheckResult:
|
|
232
|
+
if self.check_auth and (self.username or self.key_path):
|
|
233
|
+
status, msg, latency_ms, details, remediation = self._check_ssh_auth_cli()
|
|
234
|
+
else:
|
|
235
|
+
status, msg, latency_ms, details, remediation = self._check_socket_banner()
|
|
236
|
+
|
|
237
|
+
return CheckResult(
|
|
238
|
+
name=self.name,
|
|
239
|
+
category=self.category,
|
|
240
|
+
status=status,
|
|
241
|
+
message=msg,
|
|
242
|
+
target=f"{self.host}:{self.port}",
|
|
243
|
+
latency_ms=latency_ms,
|
|
244
|
+
details=details,
|
|
245
|
+
remediation=remediation,
|
|
246
|
+
)
|