From 7a0f37b8e92e6a9595619697f743b5e65e0a6d6c Mon Sep 17 00:00:00 2001 From: draarivpatel-ui <287273626+draarivpatel-ui@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:44:29 -0600 Subject: [PATCH 1/2] Honor HostKeyAlias from ssh_config for host key verification When an ssh_config entry sets HostKeyAlias, pyinfra verified the host key against the resolved HostName instead of the alias, so setups that reuse an internal address across hosts (for example behind ProxyJump) failed with a host key error where ssh connects. ssh stores keys for these setups under the alias in known_hosts, so register them under the hostname being connected to, plus the [hostname]:port form for non-default ports, after loading host keys. Fixes #2102. --- .../connectors/sshuserclient/client.py | 15 ++++++ tests/test_connectors/test_ssh.py | 48 +++++++++++++++++++ 2 files changed, 63 insertions(+) diff --git a/src/pyinfra/connectors/sshuserclient/client.py b/src/pyinfra/connectors/sshuserclient/client.py index 9a65acecc..26a187f65 100644 --- a/src/pyinfra/connectors/sshuserclient/client.py +++ b/src/pyinfra/connectors/sshuserclient/client.py @@ -403,6 +403,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) @@ -414,6 +415,18 @@ 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: the + # keys are stored under the alias in known_hosts, so register them + # under the hostname we connect to (and the non-default port form). + if host_key_alias: + aliased_hostnames = [hostname] + port = config.get("port") + if port is not None and int(port) != 22: + aliased_hostnames.append(f"[{hostname}]:{port}") + for key_type, key in self._host_keys.lookup(host_key_alias).items(): + for aliased_hostname in aliased_hostnames: + self._host_keys.add(aliased_hostname, 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] @@ -491,6 +504,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 diff --git a/tests/test_connectors/test_ssh.py b/tests/test_connectors/test_ssh.py index b4b79b503..86f3180c4 100644 --- a/tests/test_connectors/test_ssh.py +++ b/tests/test_connectors/test_ssh.py @@ -1507,3 +1507,51 @@ 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): + 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) + + 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 host_keys + + def test_host_key_alias_registered_under_connect_hostname(self): + host_keys = self._connect_with_alias() + assert host_keys.lookup("10.0.0.2") is not None + + def test_host_key_alias_registered_with_non_default_port(self): + host_keys = self._connect_with_alias(port=2222) + assert host_keys.lookup("[10.0.0.2]:2222") is not None + + def test_host_key_alias_not_registered_with_default_port(self): + host_keys = self._connect_with_alias() + assert host_keys.lookup("[10.0.0.2]:22") is None From 3a23252b0404fcb50f6132d18fea2ef24d79e18c Mon Sep 17 00:00:00 2001 From: draarivpatel-ui <287273626+draarivpatel-ui@users.noreply.github.com> Date: Thu, 26 Nov 2026 12:34:08 -0600 Subject: [PATCH 2/2] fix: copy host keys for HostKeyAlias lookup --- .../connectors/sshuserclient/client.py | 37 ++++++++++++++----- tests/test_connectors/test_ssh.py | 26 +++++++++---- 2 files changed, 45 insertions(+), 18 deletions(-) diff --git a/src/pyinfra/connectors/sshuserclient/client.py b/src/pyinfra/connectors/sshuserclient/client.py index 26a187f65..f0885a6c2 100644 --- a/src/pyinfra/connectors/sshuserclient/client.py +++ b/src/pyinfra/connectors/sshuserclient/client.py @@ -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 @@ -416,17 +432,18 @@ 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: the - # keys are stored under the alias in known_hosts, so register them - # under the hostname we connect to (and the non-default port form). + # 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: - aliased_hostnames = [hostname] - port = config.get("port") - if port is not None and int(port) != 22: - aliased_hostnames.append(f"[{hostname}]:{port}") - for key_type, key in self._host_keys.lookup(host_key_alias).items(): - for aliased_hostname in aliased_hostnames: - self._host_keys.add(aliased_hostname, key_type, key) + 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] diff --git a/tests/test_connectors/test_ssh.py b/tests/test_connectors/test_ssh.py index 86f3180c4..07e0d1b84 100644 --- a/tests/test_connectors/test_ssh.py +++ b/tests/test_connectors/test_ssh.py @@ -1510,7 +1510,7 @@ def test_ssh_connect_fail_success(self, fake_sleep, fake_ssh_client): class TestSSHHostKeyAlias(TestCase): - def _connect_with_alias(self, port=None): + def _connect_with_alias(self, port=None, include_hostname_key=False): from io import StringIO from paramiko import HostKeys, RSAKey @@ -1521,6 +1521,10 @@ def _connect_with_alias(self, port=None): 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: @@ -1542,16 +1546,22 @@ def _connect_with_alias(self, port=None): ), ): client.connect("rhost", **connect_kwargs) - return host_keys + return client, host_keys, hostname_key def test_host_key_alias_registered_under_connect_hostname(self): - host_keys = self._connect_with_alias() - assert host_keys.lookup("10.0.0.2") is not None + 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): - host_keys = self._connect_with_alias(port=2222) - assert host_keys.lookup("[10.0.0.2]:2222") is not None + 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): - host_keys = self._connect_with_alias() - assert host_keys.lookup("[10.0.0.2]:22") is None + 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