refactor(ssh_server): split three functions under the standard's line limit (#65)
driver / standard (pull_request) Successful in 17s
driver / lint (pull_request) Successful in 15s
driver / types (pull_request) Successful in 1m18s
driver / test (3.12) (pull_request) Successful in 1m28s
driver / test (3.13) (pull_request) Successful in 1m18s
driver / lowest (pull_request) Successful in 35s
driver / build (pull_request) Successful in 33s
driver / security (pull_request) Successful in 1m9s
CI / driver (pull_request) Successful in 3m9s
driver / publish (pull_request) Skipped

harden_ssh_server (70), _apply_or_restore (51) and exempt_from_ssh_penalties
(81) had grown past the 50-line limit with #63, and `driver / standard` was
red on main. The reading and planning, the putting back, the session's
address, the reasons to leave the exemption and its write move into methods
of their own. Same behaviour, same tests; harden_ssh_server leaves the
baseline.
This commit is contained in:
christianmanivong committed 2026-11-01 08:17:27 +01:00
1 parent 1c71fe6896
commit 449a6b13ca
2 files changed
+115 -78

No files matched your search

+115 -77
View File
@@ -402,6 +402,14 @@ class SshPenaltyExemption:
message: str = ""
#: Why an algorithm stays, by :class:`Refusal` reason.
_WHYS = {
"last": "it is the last one",
"client": "netOrk could no longer connect",
"host_keys_unknown": "the host keys could not be read",
}
def _unchanged(
result: SshPenaltyExemption, message: str, say: Callable[[str], None]
) -> SshPenaltyExemption:
@@ -544,24 +552,7 @@ class OpenSshServerMixin:
:raises RuntimeError: if the current state cannot be read.
"""
say = log or (lambda _line: None)
say("Reading the algorithms sshd offers (sshd -T)")
sshd_t = self._sshd_effective_text()
host_keys: set[str] | None = None
if remove.get("hostkey"):
say("Reading which host keys the server has (ssh-keygen -l)")
host_keys = self._ssh_host_key_algorithms(sshd_t)
plan = plan_ssh_hardening(
parse_sshd_effective(sshd_t), remove, client=client, host_keys=host_keys
)
whys = {
"last": "it is the last one",
"client": "netOrk could no longer connect",
"host_keys_unknown": "the host keys could not be read",
}
for r in plan.refused:
last_key = r.reason == "last" and r.kind == "hostkey"
why = "it is the last one the host has a key for" if last_key else whys[r.reason]
say(f"Keeping {r.algorithm}: {why}")
plan = self._plan_hardening(remove, client, say)
kinds = plan.changed_classes
result = SshHardeningResult(plan=plan)
if not kinds:
@@ -575,26 +566,50 @@ class OpenSshServerMixin:
if main is None:
raise RuntimeError(f"cannot read {MAIN_CONFIG}")
restore = self._write_change(plan, main, result, say)
def ignored() -> str | None:
now = self.get_ssh_server_algorithms()
names = [SSH_ALGORITHM_CLASSES[k][1] for k in kinds if now[k] != plan.keep[k]]
if not names:
return None
return (
f"sshd does not use the new {', '.join(names)}: a setting read before"
f" {result.path} decides them"
)
return self._apply_or_restore(
result,
restore,
verify,
say,
ignored=ignored,
ignored=lambda: self._algorithms_ignored(plan, result.path),
done="The server no longer offers the selected algorithms.",
)
def _plan_hardening(
self,
remove: Mapping[str, Iterable[str]],
client: Mapping[str, Iterable[str]] | None,
say: Callable[[str], None],
) -> SshHardeningPlan:
"""Read what sshd offers and which host keys it has; plan, and say what stays."""
say("Reading the algorithms sshd offers (sshd -T)")
sshd_t = self._sshd_effective_text()
host_keys: set[str] | None = None
if remove.get("hostkey"):
say("Reading which host keys the server has (ssh-keygen -l)")
host_keys = self._ssh_host_key_algorithms(sshd_t)
plan = plan_ssh_hardening(
parse_sshd_effective(sshd_t), remove, client=client, host_keys=host_keys
)
for r in plan.refused:
last_key = r.reason == "last" and r.kind == "hostkey"
why = "it is the last one the host has a key for" if last_key else _WHYS[r.reason]
say(f"Keeping {r.algorithm}: {why}")
return plan
def _algorithms_ignored(self, plan: SshHardeningPlan, path: str | None) -> str | None:
"""Why sshd does not use the new lists; None when it does."""
now = self.get_ssh_server_algorithms()
names = [
SSH_ALGORITHM_CLASSES[k][1] for k in plan.changed_classes if now[k] != plan.keep[k]
]
if not names:
return None
return (
f"sshd does not use the new {', '.join(names)}: a setting read before"
f" {path} decides them"
)
def _write_change(
self,
plan: SshHardeningPlan,
@@ -646,19 +661,7 @@ class OpenSshServerMixin:
"""
def back(message: str, reload: bool) -> R:
say(message)
say("Putting the previous configuration back")
try:
restore()
if reload:
self._reload_ssh_server()
except Exception as exc: # noqa: BLE001 - report it, the caller must look
result.message = f"{message}; putting the previous configuration back failed: {exc}"
say(result.message)
return result
result.rolled_back = True
result.message = message
return result
return self._put_back(result, restore, say, message, reload=reload)
try:
say("Checking the configuration (sshd -t)")
@@ -681,6 +684,30 @@ class OpenSshServerMixin:
say(result.message)
return result
def _put_back[R: (SshHardeningResult, SshPenaltyExemption)](
self,
result: R,
restore: Callable[[], None],
say: Callable[[str], None],
message: str,
*,
reload: bool,
) -> R:
"""Say *message*, put the previous state back, and say whether that worked."""
say(message)
say("Putting the previous configuration back")
try:
restore()
if reload:
self._reload_ssh_server()
except Exception as exc: # noqa: BLE001 - report it, the caller must look
result.message = f"{message}; putting the previous configuration back failed: {exc}"
say(result.message)
return result
result.rolled_back = True
result.message = message
return result
# ── the penalty exemption ───────────────────────────────────────────
def exempt_from_ssh_penalties(
@@ -708,39 +735,65 @@ class OpenSshServerMixin:
``sshd -T`` or sshd_config cannot be read.
"""
say = log or (lambda _line: None)
result = SshPenaltyExemption()
address = self._session_client_address()
result = SshPenaltyExemption(address=address)
say(f"netOrk connects from {address}")
say("Reading sshd's per-source penalties (sshd -T)")
exempt = parse_penalty_exemptions(self._sshd_effective_text())
reason = self._penalty_exemption_unchanged(address, exempt)
if reason is not None or exempt is None:
return _unchanged(result, reason or "", say)
restore = self._write_penalty_dropin([*exempt, address])
result.path = PENALTY_DROPIN_PATH
say(f"Wrote {PENALTY_DROPIN_PATH}")
return self._apply_or_restore(
result,
restore,
verify,
say,
ignored=lambda: self._exemption_ignored(address),
done=f"{address} is exempt from sshd's per-source penalties.",
)
def _session_client_address(self) -> str:
"""The address the host sees this session come from (``$SSH_CONNECTION``)."""
session = self.run_command('printf %s "$SSH_CONNECTION"', privileged=False, timeout=30)
address = client_address(session.stdout)
if address is None:
raise RuntimeError("the session names no client address ($SSH_CONNECTION)")
result.address = address
say(f"netOrk connects from {address}")
say("Reading sshd's per-source penalties (sshd -T)")
exempt = parse_penalty_exemptions(self._sshd_effective_text())
return address
def _penalty_exemption_unchanged(self, address: str, exempt: list[str] | None) -> str | None:
"""Why the exemption is left as it is; None when it is to be written."""
if exempt is None:
return _unchanged(
result,
"Nothing to change: this sshd has no per-source penalties (before OpenSSH 9.8).",
say,
)
return "Nothing to change: this sshd has no per-source penalties (before OpenSSH 9.8)."
if is_exempt(address, exempt):
return _unchanged(result, f"Nothing to change: {address} is already exempt.", say)
return f"Nothing to change: {address} is already exempt."
main = self._ssh_read(MAIN_CONFIG)
if main is None:
raise RuntimeError(f"cannot read {MAIN_CONFIG}")
if not has_dropin_include(main):
return _unchanged(
result,
return (
f"Not changed: {MAIN_CONFIG} does not include {DROPIN_DIR},"
" where the exemption would go.",
say,
" where the exemption would go."
)
return None
def _exemption_ignored(self, address: str) -> str | None:
"""Why sshd does not use the new exemption; None when it does."""
if is_exempt(address, parse_penalty_exemptions(self._sshd_effective_text()) or []):
return None
return (
"sshd does not use the new PerSourcePenaltyExemptList: a setting read before"
f" {PENALTY_DROPIN_PATH} decides it"
)
def _write_penalty_dropin(self, exempt: Sequence[str]) -> Callable[[], None]:
"""Write the exemption list; return what puts the previous drop-in back."""
previous = self._ssh_read(PENALTY_DROPIN_PATH)
self._ssh_run(f"mkdir -p -- {quote(DROPIN_DIR)}")
self._ssh_write(PENALTY_DROPIN_PATH, render_penalty_dropin([*exempt, address]))
result.path = PENALTY_DROPIN_PATH
say(f"Wrote {PENALTY_DROPIN_PATH}")
self._ssh_write(PENALTY_DROPIN_PATH, render_penalty_dropin(exempt))
def restore() -> None:
if previous is None:
@@ -748,19 +801,4 @@ class OpenSshServerMixin:
else:
self._ssh_write(PENALTY_DROPIN_PATH, previous)
def ignored() -> str | None:
if is_exempt(address, parse_penalty_exemptions(self._sshd_effective_text()) or []):
return None
return (
"sshd does not use the new PerSourcePenaltyExemptList: a setting read before"
f" {PENALTY_DROPIN_PATH} decides it"
)
return self._apply_or_restore(
result,
restore,
verify,
say,
ignored=ignored,
done=f"{address} is exempt from sshd's per-source penalties.",
)
return restore
-1
View File
@@ -25,7 +25,6 @@
"napalm_device_types/firewall_rules.py::FirewallRuleMixin.diff_firewall_rules": 56,
"napalm_device_types/hypervisor.py::HypervisorDriver.create_vm_from_cloud_init": 84,
"napalm_device_types/hypervisor.py::HypervisorDriver.get_vm_config": 77,
"napalm_device_types/ssh_server.py::OpenSshServerMixin.harden_ssh_server": 52,
"napalm_device_types/ssh_server.py::plan_ssh_hardening": 60,
"napalm_device_types/storage.py::StorageDriver.get_volumes": 52,
"napalm_device_types/switch.py::SwitchDriver.get_dot1x_ports": 51,