refactor(ssh_server): split three functions under the standard's line limit (#65) #66
No files matched your search
@@ -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
|
||||
@@ -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,
|
||||
|
||||
Reference in new issue
Block a user