Merge pull request 'fix(ssh): a refused RSA/ECDSA key is an authentication failure' (#32) from fix/pkey-not-key-filename into main
driver / lint (push) Successful in 15s
driver / standard (push) Successful in 18s
driver / types (push) Successful in 56s
driver / test (3.13) (push) Successful in 1m1s
driver / test (3.12) (push) Successful in 1m7s
driver / lowest (push) Successful in 35s
driver / build (push) Successful in 30s
driver / security (push) Successful in 1m18s
CI / driver (push) Successful in 2m37s
driver / publish (push) Skipped
driver / lint (push) Successful in 15s
driver / standard (push) Successful in 18s
driver / types (push) Successful in 56s
driver / test (3.13) (push) Successful in 1m1s
driver / test (3.12) (push) Successful in 1m7s
driver / lowest (push) Successful in 35s
driver / build (push) Successful in 30s
driver / security (push) Successful in 1m18s
CI / driver (push) Successful in 2m37s
driver / publish (push) Skipped
This commit was merged in pull request #32.
This commit is contained in:
commit
7c6c53d142
3 files changed
+160
-1
No files matched your search
@@ -58,6 +58,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||||||
3.12 venv no longer has.
|
3.12 venv no longer has.
|
||||||
|
|
||||||
### Fixed
|
### Fixed
|
||||||
|
- A host turning down an RSA or ECDSA key is an authentication failure:
|
||||||
|
`open()` raises `ConnectionException("SSH to <host> failed: Authentication failed.")`.
|
||||||
|
The key went to paramiko as `key_filename`, which tries a key file as every key type
|
||||||
|
and keeps the last error, so the refusal read "encountered RSA key, expected OPENSSH
|
||||||
|
key". The key is now loaded once as its own type and passed as `pkey`; a key file that
|
||||||
|
cannot be read raises `ConnectionException` before anything is dialled
|
||||||
|
(NetOrk/netork#2512).
|
||||||
- An OpenBSD host no longer reads as 100 % busy (#7). net-snmp on OpenBSD answers
|
- An OpenBSD host no longer reads as 100 % busy (#7). net-snmp on OpenBSD answers
|
||||||
`ssCpuIdle` with 0 on an idle machine, so `OpenBSDDriver` declares the CPU unknown
|
`ssCpuIdle` with 0 on an idle machine, so `OpenBSDDriver` declares the CPU unknown
|
||||||
in its `SNMP_HEALTH_PROFILE` (`{"cpu": {"unknown": True}}`), and the application
|
in its `SNMP_HEALTH_PROFILE` (`{"cpu": {"unknown": True}}`), and the application
|
||||||
|
|||||||
+17
-1
@@ -89,6 +89,21 @@ def render_snmpd_conf(settings: SnmpAgentSettingsDict) -> str:
|
|||||||
return "\n".join(lines) + "\n"
|
return "\n".join(lines) + "\n"
|
||||||
|
|
||||||
|
|
||||||
|
def _load_key(key_file: str | None) -> paramiko.PKey | None:
|
||||||
|
"""The private key in *key_file*, loaded as the type it is; None without one.
|
||||||
|
|
||||||
|
Handed a key file, paramiko tries it as every key type and keeps 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 (NetOrk/netork#2512).
|
||||||
|
"""
|
||||||
|
if not key_file:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
return paramiko.PKey.from_path(key_file)
|
||||||
|
except (OSError, ValueError, TypeError, paramiko.UnknownKeyType) as exc:
|
||||||
|
raise ConnectionException(f"SSH key {key_file} could not be read: {exc}") from exc
|
||||||
|
|
||||||
|
|
||||||
class BsdDriver(
|
class BsdDriver(
|
||||||
BsdScheduledJobsMixin,
|
BsdScheduledJobsMixin,
|
||||||
SnmpAgentMixin,
|
SnmpAgentMixin,
|
||||||
@@ -150,13 +165,14 @@ class BsdDriver(
|
|||||||
# -- connection --------------------------------------------------------------
|
# -- connection --------------------------------------------------------------
|
||||||
|
|
||||||
def open(self) -> None:
|
def open(self) -> None:
|
||||||
|
pkey = _load_key(self._key_file)
|
||||||
client = paramiko.SSHClient()
|
client = paramiko.SSHClient()
|
||||||
try:
|
try:
|
||||||
self._host_key.connect(
|
self._host_key.connect(
|
||||||
client,
|
client,
|
||||||
username=self.username,
|
username=self.username,
|
||||||
password=self.password or None,
|
password=self.password or None,
|
||||||
key_filename=self._key_file,
|
pkey=pkey,
|
||||||
allow_agent=self._allow_agent,
|
allow_agent=self._allow_agent,
|
||||||
look_for_keys=self._look_for_keys,
|
look_for_keys=self._look_for_keys,
|
||||||
timeout=self.timeout,
|
timeout=self.timeout,
|
||||||
|
|||||||
@@ -0,0 +1,136 @@
|
|||||||
|
"""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()
|
||||||
Reference in new issue
Block a user