"""open() logs in with the key netOrk hands it, whatever its type (NetOrk/netork#2512). Against a real SSH server on loopback. Handed the key as ``key_filename``, paramiko tried it as every key type and kept the last error, so a host turning down an RSA or ECDSA key read "encountered RSA key, expected OPENSSH key" instead of the refusal it was. """ from __future__ import annotations import io import socket import threading from pathlib import Path from typing import Any import paramiko import pytest from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric import ed25519 from napalm.base.exceptions import ConnectionException from napalm_bsd import FreeBSDDriver KEY_KINDS = ("rsa", "ecdsa", "ed25519") def _private_key(kind: str) -> tuple[paramiko.PKey, str]: """A new key of *kind* and its text: RSA and ECDSA as PEM, Ed25519 as OpenSSH.""" if kind == "ed25519": text = ( ed25519.Ed25519PrivateKey.generate() .private_bytes( serialization.Encoding.PEM, serialization.PrivateFormat.OpenSSH, serialization.NoEncryption(), ) .decode() ) return paramiko.Ed25519Key.from_private_key(io.StringIO(text)), text key: paramiko.PKey = ( paramiko.RSAKey.generate(2048) if kind == "rsa" else paramiko.ECDSAKey.generate() ) pem = io.StringIO() key.write_private_key(pem) return key, pem.getvalue() class _SshHost(paramiko.ServerInterface): """Serves one connection on a loopback port; accepts only *accept_key*.""" def __init__(self, accept_key: paramiko.PKey | None = None) -> None: self.accept_key = accept_key self.tried: list[str] = [] self._listener = socket.create_server(("127.0.0.1", 0)) self.port = self._listener.getsockname()[1] self._thread = threading.Thread(target=self._serve, daemon=True) self._thread.start() def get_allowed_auths(self, username: str) -> str: return "publickey" def check_auth_publickey(self, username: str, key: Any) -> int: self.tried.append(key.get_name()) if self.accept_key is not None and key.get_base64() == self.accept_key.get_base64(): return paramiko.AUTH_SUCCESSFUL return paramiko.AUTH_FAILED def _serve(self) -> None: self._listener.settimeout(10) try: sock = self._listener.accept()[0] except OSError: return finally: self._listener.close() transport = paramiko.Transport(sock) transport.add_server_key(paramiko.ECDSAKey.generate()) try: transport.start_server(server=self) transport.join(10) # until the client hangs up except Exception: # noqa: BLE001 - a refused client ends the server return finally: transport.close() def join(self) -> None: self._thread.join(10) def _driver(host: _SshHost, key_file: Path) -> FreeBSDDriver: return FreeBSDDriver( "127.0.0.1", "netork", "", optional_args={"port": host.port, "key_file": str(key_file)} ) @pytest.mark.parametrize("kind", KEY_KINDS) def test_a_refused_key_is_an_authentication_failure(tmp_path: Path, kind: str) -> None: host = _SshHost() key_file = tmp_path / "key" key_file.write_text(_private_key(kind)[1]) with pytest.raises(ConnectionException, match="Authentication failed") as refused: _driver(host, key_file).open() host.join() assert "expected OPENSSH key" not in str(refused.value) assert len(host.tried) == 1 @pytest.mark.parametrize("kind", KEY_KINDS) def test_an_accepted_key_logs_in(tmp_path: Path, kind: str) -> None: key, text = _private_key(kind) host = _SshHost(accept_key=key) key_file = tmp_path / "key" key_file.write_text(text) driver = _driver(host, key_file) driver.open() try: assert driver.is_alive() == {"is_alive": True} finally: driver.close() host.join() def test_a_key_it_cannot_read_is_a_connection_failure(tmp_path: Path) -> None: """Before any connection: nothing is dialled with a key that is no key.""" key_file = tmp_path / "key" key_file.write_text( "-----BEGIN OPENSSH PRIVATE KEY-----\nabc\n-----END OPENSSH PRIVATE KEY-----\n" ) driver = FreeBSDDriver("192.0.2.1", "netork", "", optional_args={"key_file": str(key_file)}) with pytest.raises(ConnectionException, match="key"): driver.open()