Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions src/pyinfra/connectors/sshuserclient/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -370,6 +370,22 @@ def get_host_keys(filenames):
return host_keys


def _copy_host_keys(host_keys: HostKeys) -> HostKeys:
copied_host_keys = HostKeys()
for hostname in host_keys.keys():
hostname_keys = host_keys.lookup(hostname)
if hostname_keys is None:
continue
for key_type, key in hostname_keys.items():
copied_host_keys.add(hostname, key_type, key)

cert_authorities = _get_cert_authorities(host_keys)
if cert_authorities:
setattr(copied_host_keys, "_pyinfra_cert_authorities", list(cert_authorities))

return copied_host_keys


class SSHClient(ParamikoClient):
"""
An SSHClient which honors ssh_config and supports proxyjumping
Expand Down Expand Up @@ -403,6 +419,7 @@ def connect( # type: ignore[override]
ssh_config_file=_pyinfra_ssh_config_file,
strict_host_key_checking=_pyinfra_ssh_strict_host_key_checking,
)
host_key_alias = config.pop("_pyinfra_ssh_host_key_alias", None)
self.set_missing_host_key_policy(missing_host_key_policy)
proxyjump_sock = config.get("sock")
config.update(kwargs)
Expand All @@ -414,6 +431,19 @@ def connect( # type: ignore[override]

# Overwrite paramiko empty defaults with @memoize-d host keys object
self._host_keys = get_host_keys(host_keys_files)

# Honor any HostKeyAlias for the host key lookup, like ssh does. Paramiko
# looks up non-default ports as ``[host]:port``, so mirror that name on a
# per-client copy rather than mutating the shared memoized host keys.
if host_key_alias:
port = int(config.get("port", 22))
server_hostkey_name = hostname if port == 22 else f"[{hostname}]:{port}"
if self._host_keys.lookup(server_hostkey_name) is None:
alias_host_keys = self._host_keys.lookup(host_key_alias)
if alias_host_keys is not None:
self._host_keys = _copy_host_keys(self._host_keys)
for key_type, key in alias_host_keys.items():
self._host_keys.add(server_hostkey_name, key_type, key)
# Use the first file for writing new host keys
if len(host_keys_files) > 0:
self._host_keys_filename = host_keys_files[0]
Expand Down Expand Up @@ -491,6 +521,8 @@ def parse_config(
)

host_config = ssh_config.lookup(hostname)
if "hostkeyalias" in host_config:
cfg["_pyinfra_ssh_host_key_alias"] = host_config["hostkeyalias"]
forward_agent = host_config.get("forwardagent") == "yes"

# If not overridden, apply any StrictHostKeyChecking
Expand Down
58 changes: 58 additions & 0 deletions tests/test_connectors/test_ssh.py
Original file line number Diff line number Diff line change
Expand Up @@ -1507,3 +1507,61 @@ def test_ssh_connect_fail_success(self, fake_sleep, fake_ssh_client):
unresposivehost.connect(show_errors=False, raise_exceptions=True)
fake_sleep.assert_called_once()
assert fake_ssh_client().connect.call_count == 2


class TestSSHHostKeyAlias(TestCase):
def _connect_with_alias(self, port=None, include_hostname_key=False):
from io import StringIO

from paramiko import HostKeys, RSAKey

from pyinfra.connectors.sshuserclient.client import SSHClient as SSHUserClient
from pyinfra.connectors.sshuserclient.config import SSHConfig

key = RSAKey.generate(1024)
host_keys = HostKeys()
host_keys.add("rhost-alias", "ssh-rsa", key)
hostname_key = None
if include_hostname_key:
hostname_key = RSAKey.generate(1024)
host_keys.add("10.0.0.2", "ssh-rsa", hostname_key)

config_text = "Host rhost\n HostName 10.0.0.2\n HostKeyAlias rhost-alias\n"
if port is not None:
config_text += f" Port {port}\n"
ssh_config = SSHConfig()
ssh_config.parse(StringIO(config_text))

client = SSHUserClient()
connect_kwargs = {}
with (
mock.patch("pyinfra.connectors.sshuserclient.client.ParamikoClient.connect"),
mock.patch(
"pyinfra.connectors.sshuserclient.client.get_host_keys",
return_value=host_keys,
),
mock.patch(
"pyinfra.connectors.sshuserclient.client.get_ssh_config",
return_value=ssh_config,
),
):
client.connect("rhost", **connect_kwargs)
return client, host_keys, hostname_key

def test_host_key_alias_registered_under_connect_hostname(self):
client, host_keys, _ = self._connect_with_alias()
assert client._host_keys.lookup("10.0.0.2") is not None
assert host_keys.lookup("10.0.0.2") is None

def test_host_key_alias_registered_with_non_default_port(self):
client, host_keys, _ = self._connect_with_alias(port=2222)
assert client._host_keys.lookup("[10.0.0.2]:2222") is not None
assert host_keys.lookup("[10.0.0.2]:2222") is None

def test_host_key_alias_not_registered_with_default_port(self):
client, _, _ = self._connect_with_alias()
assert client._host_keys.lookup("[10.0.0.2]:22") is None

def test_host_key_alias_not_used_when_hostname_key_exists(self):
client, _, hostname_key = self._connect_with_alias(include_hostname_key=True)
assert client._host_keys.lookup("10.0.0.2")["ssh-rsa"] is hostname_key
Loading