Merge remote-tracking branch 'origin/main' into feat/local-accounts
driver / standard (pull_request) Failing after 18s
driver / lint (pull_request) Successful in 13s
driver / types (pull_request) Successful in 59s
driver / test (3.12) (pull_request) Successful in 1m7s
driver / lowest (pull_request) Successful in 31s
driver / test (3.13) (pull_request) Successful in 58s
driver / build (pull_request) Successful in 32s
driver / security (pull_request) Successful in 59s
CI / driver (pull_request) Failing after 2m35s
driver / publish (pull_request) Skipped

# Conflicts:
#	CHANGELOG.md
This commit is contained in:
christianmanivong committed 2026-11-01 00:45:06 +01:00
commit 9159106837
5 files changed
+701 -20

No files matched your search

+250
View File
@@ -0,0 +1,250 @@
"""Exempting the managing client from sshd's per-source penalties (NetOrk/netork#1800).
OpenSSH 9.8 penalises a source whose connections do not authenticate and then
drops every connection from it. A security scanner's probes earn the managing
client exactly that, and its next session -- a poll, an Ansible run -- is
turned away. ``exempt_from_ssh_penalties`` puts the address the host sees the
client at into ``PerSourcePenaltyExemptList``, where that directive exists.
The real outputs this is held to were taken from Debian 13 (OpenSSH 10.0p2) and
Debian 12 (OpenSSH 9.2p1, which knows no penalties and rejects the directive).
"""
from __future__ import annotations
import re
import pytest
from napalm_device_types.channel import CommandResult
from napalm_device_types.ssh_server import (
DROPIN_DIR,
MAIN_CONFIG,
PENALTY_DROPIN_PATH,
OpenSshServerMixin,
client_address,
is_exempt,
parse_penalty_exemptions,
)
#: ``sshd -T | grep -i penalt`` on Debian 13, OpenSSH 10.0p2, as installed.
DEBIAN_13 = (
"persourcepenaltyexemptlist none\n"
"persourcepenalties crash:90 authfail:5 noauth:1 grace-exceeded:10 refuseconnection:10"
" max:600 min:15 max-sources4:65536 max-sources6:65536 overflow:permissive"
" overflow6:permissive\n"
)
# ── reading ──────────────────────────────────────────────────────────────
def test_a_new_sshd_has_penalties_and_no_exemption():
assert parse_penalty_exemptions(DEBIAN_13) == []
def test_the_exemptions_sshd_uses_are_read():
text = DEBIAN_13.replace("none", "10.40.100.10,192.0.2.0/24")
assert parse_penalty_exemptions(text) == ["10.40.100.10", "192.0.2.0/24"]
def test_an_sshd_before_9_8_has_no_penalties():
"""It prints neither line -- and refuses the directive, so nothing may be written."""
assert parse_penalty_exemptions("port 22\nmacs hmac-sha2-256\n") is None
@pytest.mark.parametrize(
("value", "address"),
[
("10.40.100.10 41866 10.40.100.118 22", "10.40.100.10"),
("fd00::10 41866 fd00::118 22", "fd00::10"),
("", None),
("not-an-address 1 2 3", None),
("10.40.100.10 41866", None),
],
)
def test_the_client_address_comes_from_ssh_connection(value, address):
assert client_address(value) == address
def test_an_address_inside_an_exempt_network_is_exempt():
assert is_exempt("10.40.100.10", ["192.0.2.0/24", "10.40.100.0/24"])
assert not is_exempt("10.40.100.10", ["10.40.100.11", "bogus"])
# ── the mixin, against a fake host ───────────────────────────────────────
class PenaltyHost(OpenSshServerMixin):
"""An sshd that reads the main config and the drop-in directory, first value wins."""
def __init__(
self,
*,
main: str = f"Include {DROPIN_DIR}/*.conf\nPort 22\n",
penalties: bool = True,
client: str = "10.40.100.10 41866 10.40.100.118 22",
) -> None:
self.files: dict[str, str] = {MAIN_CONFIG: main}
self.penalties = penalties
self.client = client
self.syntax_ok = True
self.reloads = 0
self.ran: list[str] = []
def _config_lines(self) -> list[str]:
lines: list[str] = []
for line in self.files[MAIN_CONFIG].splitlines():
if re.match(r"\s*include\s", line, re.I):
for path in sorted(p for p in self.files if p.startswith(DROPIN_DIR + "/")):
lines += self.files[path].splitlines()
elif re.match(r"\s*match\s", line, re.I):
break
else:
lines.append(line)
return lines
def exempt(self) -> str:
for line in self._config_lines():
parts = line.split()
if len(parts) == 2 and parts[0].lower() == "persourcepenaltyexemptlist":
return parts[1]
return "none"
def run_command(self, command, *, privileged=False, timeout=60, stdin=None):
self.ran.append(command)
if "SSH_CONNECTION" in command:
assert not privileged, "it is the login session's, not sudo's"
return CommandResult(self.client, "", 0)
if "mktemp" in command:
path = f"/tmp/netork-ssh.{len(self.files)}"
self.files[path] = (stdin or b"").decode()
return CommandResult(path, "", 0)
assert privileged, command
m = re.search(r"install -m \"\$m\" -- '?([^' ]+)'? '?([^' ]+)'?", command)
if m:
target = re.search(r"mv -f -- '?[^' ]+'? '?([^' ;]+)'?", command).group(1)
self.files[target] = self.files.pop(m.group(1))
return CommandResult("", "", 0)
if "sshd -T" in command:
if not self.penalties:
return CommandResult("port 22\n", "", 0)
return CommandResult(DEBIAN_13.replace("none", self.exempt()), "", 0)
if "sshd -t" in command:
return CommandResult(
"", "" if self.syntax_ok else "bad line 1", 0 if self.syntax_ok else 255
)
m = re.match(r"cat -- '?([^' ]+)'?$", command)
if m:
path = m.group(1)
if path in self.files:
return CommandResult(self.files[path], "", 0)
return CommandResult("", "No such file", 1)
m = re.match(r"rm -f -- '?([^' ]+)'?$", command)
if m:
self.files.pop(m.group(1), None)
return CommandResult("", "", 0)
if "reload" in command or "HUP" in command:
self.reloads += 1
return CommandResult("", "", 0)
if command.startswith("mkdir"):
return CommandResult("", "", 0)
raise AssertionError(f"unexpected command: {command}")
def test_the_client_address_is_exempted_in_a_dropin():
host = PenaltyHost()
lines: list[str] = []
result = host.exempt_from_ssh_penalties(log=lines.append)
assert result.applied and not result.rolled_back
assert result.address == "10.40.100.10"
assert result.path == PENALTY_DROPIN_PATH
assert host.exempt() == "10.40.100.10"
assert host.reloads == 1
assert lines
def test_the_hosts_own_exemptions_stay():
host = PenaltyHost(
main=f"Include {DROPIN_DIR}/*.conf\nPerSourcePenaltyExemptList 192.0.2.0/24\n"
)
result = host.exempt_from_ssh_penalties()
assert result.applied
assert host.exempt() == "192.0.2.0/24,10.40.100.10"
def test_nothing_is_written_to_an_sshd_without_penalties():
"""OpenSSH before 9.8 does not start with the directive in its config."""
host = PenaltyHost(penalties=False)
result = host.exempt_from_ssh_penalties()
assert not result.applied and not result.rolled_back
assert PENALTY_DROPIN_PATH not in host.files
assert host.reloads == 0
assert "9.8" in result.message
def test_nothing_changes_when_the_address_is_already_exempt():
host = PenaltyHost(
main=f"Include {DROPIN_DIR}/*.conf\nPerSourcePenaltyExemptList 10.40.100.0/24\n"
)
result = host.exempt_from_ssh_penalties()
assert not result.applied
assert PENALTY_DROPIN_PATH not in host.files
assert "already" in result.message
def test_an_sshd_config_without_the_include_is_left_alone():
host = PenaltyHost(main="Port 22\n")
result = host.exempt_from_ssh_penalties()
assert not result.applied
assert host.files[MAIN_CONFIG] == "Port 22\n"
assert DROPIN_DIR in result.message
def test_a_rejected_config_is_taken_back():
host = PenaltyHost()
host.syntax_ok = False
result = host.exempt_from_ssh_penalties()
assert result.rolled_back and not result.applied
assert PENALTY_DROPIN_PATH not in host.files
def test_an_exemption_sshd_does_not_use_is_taken_back():
"""A drop-in read before ours sets the directive; ours is valid and ignored."""
host = PenaltyHost()
host.files[f"{DROPIN_DIR}/00-aaa.conf"] = "PerSourcePenaltyExemptList 192.0.2.1\n"
result = host.exempt_from_ssh_penalties()
assert result.rolled_back
assert PENALTY_DROPIN_PATH not in host.files
def test_it_is_taken_back_when_a_new_session_cannot_get_in():
host = PenaltyHost()
result = host.exempt_from_ssh_penalties(verify=lambda: False)
assert result.rolled_back
assert PENALTY_DROPIN_PATH not in host.files
assert host.reloads == 2
def test_a_session_without_a_client_address_raises():
host = PenaltyHost(client="")
with pytest.raises(RuntimeError):
host.exempt_from_ssh_penalties()
+168
View File
@@ -0,0 +1,168 @@
"""A connection sshd turns away before the SSH banner is tried again (NetOrk/netork#1800).
OpenSSH 9.8+ drops every connection from a source it has just penalised
(``PerSourcePenalties``): it accepts the TCP connection and closes it at once,
and paramiko reports "Error reading SSH protocol banner". The penalty lasts
seconds to minutes, so a connection that waits a little gets in.
"""
from __future__ import annotations
import socket
import threading
import paramiko
import pytest
from napalm.base.exceptions import ConnectionException
from napalm_device_types import ssh_host_keys
from napalm_device_types.ssh_host_keys import (
REFUSED_RETRY_WAITS,
HostKeyCheck,
refused_before_banner,
retry_refused,
)
def _banner_error() -> paramiko.SSHException:
try:
try:
raise EOFError()
except EOFError as eof:
raise paramiko.SSHException("Error reading SSH protocol banner") from eof
except paramiko.SSHException as exc:
return exc
class TestWhatCountsAsRefused:
def test_paramikos_banner_error(self):
assert refused_before_banner(_banner_error())
def test_wrapped_by_a_driver(self):
try:
try:
raise _banner_error()
except paramiko.SSHException as exc:
raise ConnectionException(f"cannot connect: {exc}") from exc
except ConnectionException as wrapped:
assert refused_before_banner(wrapped)
@pytest.mark.parametrize(
"exc",
[
paramiko.AuthenticationException("Authentication failed."),
TimeoutError("timed out"),
ConnectionRefusedError(111, "Connection refused"),
ValueError("anything else"),
],
)
def test_not_a_failed_login_a_silent_host_or_a_closed_port(self, exc):
"""Those do not end by waiting: retrying them only delays the error."""
assert not refused_before_banner(exc)
class TestRetry:
def test_it_waits_and_tries_again(self):
slept: list[float] = []
attempts = iter([_banner_error(), _banner_error(), "connected"])
def attempt():
value = next(attempts)
if isinstance(value, BaseException):
raise value
return value
assert retry_refused(attempt, sleep=slept.append) == "connected"
assert slept == list(REFUSED_RETRY_WAITS[:2])
def test_it_gives_up_with_the_last_error(self):
slept: list[float] = []
def attempt():
raise _banner_error()
with pytest.raises(paramiko.SSHException):
retry_refused(attempt, sleep=slept.append)
assert slept == list(REFUSED_RETRY_WAITS)
def test_other_errors_are_not_retried(self):
slept: list[float] = []
def attempt():
raise paramiko.AuthenticationException("Authentication failed.")
with pytest.raises(paramiko.AuthenticationException):
retry_refused(attempt, sleep=slept.append)
assert slept == []
def test_the_waits_outlast_the_penalty_seen(self):
"""16 s on a new Ubuntu 26.04 VM on .50."""
assert sum(REFUSED_RETRY_WAITS) > 16
class _PenalisingServer:
"""A TCP server that closes the first *drops* connections at once, as a penalised
source's are, and then speaks SSH with any password."""
def __init__(self, drops: int) -> None:
self.drops = drops
self.listener = socket.create_server(("127.0.0.1", 0))
self.port = self.listener.getsockname()[1]
self.key = paramiko.ECDSAKey.generate()
self._thread = threading.Thread(target=self._serve, daemon=True)
self._thread.start()
def _serve(self) -> None:
while True:
try:
conn, _ = self.listener.accept()
except OSError:
return
if self.drops:
self.drops -= 1
conn.close()
continue
transport = paramiko.Transport(conn)
transport.add_server_key(self.key)
class _Any(paramiko.ServerInterface):
def get_allowed_auths(self, username):
return "password"
def check_auth_password(self, username, password):
return paramiko.AUTH_SUCCESSFUL
try:
transport.start_server(server=_Any())
except Exception:
pass
self.transport = transport
return
def close(self) -> None:
self.listener.close()
transport = getattr(self, "transport", None)
if transport:
transport.close()
def test_host_key_check_connects_once_the_penalty_is_over(monkeypatch):
server = _PenalisingServer(drops=2)
slept: list[float] = []
monkeypatch.setattr(ssh_host_keys.time, "sleep", slept.append)
client = paramiko.SSHClient()
try:
HostKeyCheck({}, "127.0.0.1", server.port).connect(
client,
username="admin",
password="s3cret",
look_for_keys=False,
allow_agent=False,
timeout=5,
banner_timeout=5,
)
assert client.get_transport().is_authenticated()
assert slept == list(REFUSED_RETRY_WAITS[:2])
finally:
client.close()
server.close()