driver / lint (pull_request) Successful in 15s
driver / standard (pull_request) Failing after 15s
driver / types (pull_request) Successful in 1m3s
driver / test (3.13) (pull_request) Failing after 59s
driver / test (3.12) (pull_request) Failing after 1m9s
driver / lowest (pull_request) Failing after 28s
driver / build (pull_request) Successful in 29s
driver / security (pull_request) Successful in 1m2s
CI / driver (pull_request) Failing after 2m17s
driver / publish (pull_request) Skipped
OpenSSH 9.8+ closes every connection from a source it has just penalised, before its banner, for seconds to minutes. open() now wraps netmiko's ConnectHandler in napalm-device-types' retry_refused, so the connection is tried again after 1, 3, 7 and 15 s instead of failing. Needs NAPALM/napalm-device-types#63.
116 lines
3.9 KiB
Python
116 lines
3.9 KiB
Python
"""open() hands netmiko the host key to expect, and reports the one it saw (NetOrk/netork#1167).
|
|
|
|
OpenMediaVault and QNAP open through ``LinuxDriver.open()`` and get this too.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import os
|
|
from unittest.mock import MagicMock, patch
|
|
|
|
import paramiko
|
|
import pytest
|
|
from napalm_device_types.ssh_host_keys import (
|
|
KNOWN_KEYS_ARG,
|
|
OBSERVER_ARG,
|
|
SshHostKey,
|
|
SshHostKeyMismatch,
|
|
)
|
|
from netmiko.exceptions import NetmikoTimeoutException
|
|
|
|
from napalm_linux.linux import LinuxDriver
|
|
|
|
SERVER_KEY = paramiko.ECDSAKey.generate()
|
|
OTHER_KEY = paramiko.ECDSAKey.generate()
|
|
|
|
|
|
def _device() -> MagicMock:
|
|
device = MagicMock()
|
|
device.send_command.return_value = "/usr/bin/apt"
|
|
device.remote_conn_pre.get_transport.return_value.get_remote_server_key.return_value = (
|
|
SERVER_KEY
|
|
)
|
|
return device
|
|
|
|
|
|
def _driver(seen: list, known: SshHostKey | None = None) -> LinuxDriver:
|
|
args: dict = {"port": 2222, OBSERVER_ARG: seen.append}
|
|
if known is not None:
|
|
args[KNOWN_KEYS_ARG] = {"2222": known.as_dict()}
|
|
return LinuxDriver("10.0.0.8", "admin", "s3cret", optional_args=args)
|
|
|
|
|
|
def test_first_use_lets_netmiko_accept_and_reports_the_key():
|
|
seen: list = []
|
|
with patch("napalm_linux.linux.ConnectHandler", return_value=_device()) as handler:
|
|
_driver(seen).open()
|
|
kwargs = handler.call_args.kwargs
|
|
assert kwargs["ssh_strict"] is False
|
|
assert kwargs["alt_host_keys"] is False
|
|
assert kwargs["system_host_keys"] is False
|
|
assert seen[0]["accepted"] is True
|
|
assert seen[0]["seen"]["fingerprint"] == SshHostKey.of(SERVER_KEY).fingerprint
|
|
assert (seen[0]["host"], seen[0]["port"]) == ("10.0.0.8", 2222)
|
|
|
|
|
|
def test_a_known_key_is_the_only_one_netmiko_accepts():
|
|
seen: list = []
|
|
known = SshHostKey.of(SERVER_KEY)
|
|
files: list[str] = []
|
|
|
|
def connect(**kwargs):
|
|
files.append(kwargs["alt_key_file"])
|
|
with open(kwargs["alt_key_file"]) as f:
|
|
assert f.read().strip() == known.known_hosts_line("10.0.0.8", 2222)
|
|
assert kwargs["ssh_strict"] is True and kwargs["alt_host_keys"] is True
|
|
return _device()
|
|
|
|
with patch("napalm_linux.linux.ConnectHandler", side_effect=connect):
|
|
_driver(seen, known).open()
|
|
assert not os.path.exists(files[0])
|
|
assert seen[0]["accepted"] is True
|
|
|
|
|
|
def test_a_changed_key_is_refused():
|
|
seen: list = []
|
|
|
|
def refuse(**kwargs):
|
|
try:
|
|
raise paramiko.BadHostKeyException("10.0.0.8", SERVER_KEY, OTHER_KEY)
|
|
except paramiko.SSHException as exc: # what netmiko does with it
|
|
raise NetmikoTimeoutException(f"A paramiko SSHException occurred: {exc}") from exc
|
|
|
|
driver = _driver(seen, SshHostKey.of(OTHER_KEY))
|
|
with patch("napalm_linux.linux.ConnectHandler", side_effect=refuse):
|
|
with pytest.raises(SshHostKeyMismatch):
|
|
driver.open()
|
|
assert driver._device is None
|
|
assert seen[0]["accepted"] is False
|
|
|
|
|
|
def test_a_connection_sshd_turns_away_is_tried_again(monkeypatch):
|
|
"""OpenSSH 9.8+ closes every connection from a source it has just penalised,
|
|
before its banner; the penalty ends after seconds (NetOrk/netork#1800)."""
|
|
from napalm_device_types import ssh_host_keys
|
|
|
|
slept: list[float] = []
|
|
monkeypatch.setattr(ssh_host_keys.time, "sleep", slept.append)
|
|
attempts: list[int] = []
|
|
|
|
def turned_away(**kwargs):
|
|
attempts.append(1)
|
|
if len(attempts) < 3:
|
|
try:
|
|
raise paramiko.SSHException("Error reading SSH protocol banner")
|
|
except paramiko.SSHException as exc:
|
|
raise NetmikoTimeoutException(f"A paramiko SSHException occurred: {exc}") from exc
|
|
return _device()
|
|
|
|
driver = _driver([])
|
|
with patch("napalm_linux.linux.ConnectHandler", side_effect=turned_away):
|
|
driver.open()
|
|
|
|
assert driver._device is not None
|
|
assert len(attempts) == 3
|
|
assert slept == list(ssh_host_keys.REFUSED_RETRY_WAITS[:2])
|