Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(warehouse): connect SSH tunnels to the address that was checked (#76901)

Tom Piccirello5d818faaa516
diff --git a/products/data_warehouse/backend/models/test/test_ssh_tunnel.py b/products/data_warehouse/backend/models/test/test_ssh_tunnel.py
index 8ac4c1cf1633..5edebbfae4c0 100644
--- a/products/data_warehouse/backend/models/test/test_ssh_tunnel.py
+++ b/products/data_warehouse/backend/models/test/test_ssh_tunnel.py
@@ -126,7 +126,7 @@ def test_get_tunnel_invalid_auth():
)
with pytest.raises(Exception) as e:
- ssh_tunnel.get_tunnel("host.com", 1337)
+ ssh_tunnel.get_tunnel("host.com", 1337, ssh_host="93.184.216.34")
assert "auth" in str(e.value)
@@ -143,5 +143,5 @@ def test_get_tunnel_invalid_port():
)
with pytest.raises(Exception) as e:
- ssh_tunnel.get_tunnel("host.com", 1337)
+ ssh_tunnel.get_tunnel("host.com", 1337, ssh_host="93.184.216.34")
assert "port" in str(e.value)
diff --git a/products/warehouse_sources/backend/models/ssh_tunnel.py b/products/warehouse_sources/backend/models/ssh_tunnel.py
index df600828e0ff..df84510de0ee 100644
--- a/products/warehouse_sources/backend/models/ssh_tunnel.py
+++ b/products/warehouse_sources/backend/models/ssh_tunnel.py
@@ -184,7 +184,15 @@ class SSHTunnel:
return True, ""
- def get_tunnel(self, remote_host: str, remote_port: int) -> SSHTunnelForwarder:
+ def get_tunnel(self, remote_host: str, remote_port: int, *, ssh_host: str) -> SSHTunnelForwarder:
+ """Open a forwarder to `ssh_host`, which is the address `self.host` resolved to.
+
+ `ssh_host` is required rather than defaulted to `self.host` so that a caller cannot
+ skip the SSRF check by omitting it: see `resolve_safe_host` for why the checked address
+ and the connected address have to be the same one. Passing an IP does not weaken the
+ SSH connection, because `ssh_host_key` is left unset and paramiko therefore verifies no
+ host key against the name either way.
+ """
if not self.is_auth_valid()[0]:
raise Exception("SSHTunnel auth is not valid")
@@ -193,7 +201,7 @@ class SSHTunnel:
if self.auth_type == "password":
return SSHTunnelForwarder(
- (self.host, int(self.port)),
+ (ssh_host, int(self.port)),
ssh_username=self.username,
ssh_password=self.password,
remote_bind_address=(remote_host, remote_port),
@@ -201,7 +209,7 @@ class SSHTunnel:
)
else:
return SSHTunnelForwarder(
- (self.host, int(self.port)),
+ (ssh_host, int(self.port)),
ssh_username=self.username,
ssh_pkey=self.parse_private_key(),
ssh_private_key_password=self.passphrase,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/mixins.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/mixins.py
index a544852e6a5f..f517db523d7b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/mixins.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/mixins.py
@@ -1,6 +1,7 @@
import time
import socket
import ipaddress
+import dataclasses
from collections.abc import Callable, Generator
from contextlib import _GeneratorContextManager, contextmanager
from typing import Any
@@ -39,8 +40,30 @@ def is_team_allowlisted_for_internal_hosts(team_id: int) -> bool:
return (region == "US" and team_id == 2) or (region == "EU" and team_id == 1)
[email protected](frozen=True, kw_only=True)
+class HostResolution:
+ """The outcome of `resolve_safe_host`.
+
+ `connect_host` is None exactly when the host was rejected, in which case `error` carries
+ the user-facing reason.
+ """
+
+ connect_host: str | None
+ error: str | None
+
+
def _is_host_safe(host: str, team_id: int) -> tuple[bool, str | None]:
- """Validate that a host is not an internal/private IP address.
+ """Whether a host is safe to connect to. See `resolve_safe_host` for the policy.
+
+ Callers that go on to open the connection themselves should use `resolve_safe_host` and
+ connect to the address it returns, so that the address checked is the address used.
+ """
+ resolution = resolve_safe_host(host, team_id)
+ return resolution.connect_host is not None, resolution.error
+
+
+def resolve_safe_host(host: str, team_id: int | None) -> HostResolution:
+ """Resolve a host to the address a connection should actually be made to.
Only enforced on cloud deployments — self-hosted instances are allowed
to connect to any host.
@@ -51,6 +74,13 @@ def _is_host_safe(host: str, team_id: int) -> tuple[bool, str | None]:
team whitelist: team_id 2 in US, team_id 1 in EU are allowed
to use internal IPs.
+
+ When the check applies, `connect_host` is one of the validated IPs rather than the
+ hostname that was passed in, and callers must connect to it. Handing the hostname to a
+ connection library resolves it a second time, and a record with a short TTL can answer
+ with a public address for this check and a private one for the connect, which defeats the
+ check entirely. When the check is skipped there is no resolution to pin, so the hostname
+ comes back unchanged.
"""
def _log(decision: str, stage: str, reason: str | None, resolved_ips: list[str] | None = None) -> None:
@@ -71,56 +101,66 @@ def _is_host_safe(host: str, team_id: int) -> tuple[bool, str | None]:
resolved_ips=resolved_ips,
)
+ def _allow_unpinned(stage: str) -> HostResolution:
+ _log("allow", stage, None)
+ return HostResolution(connect_host=host, error=None)
+
+ def _block(stage: str, error: str, resolved_ips: list[str] | None = None) -> HostResolution:
+ _log("block", stage, error, resolved_ips)
+ return HostResolution(connect_host=None, error=error)
+
if not is_cloud():
- _log("allow", "not_cloud", None)
- return True, None
+ return _allow_unpinned("not_cloud")
region = get_instance_region()
if region == "E2E":
- _log("allow", "e2e", None)
- return True, None
+ return _allow_unpinned("e2e")
- if is_team_allowlisted_for_internal_hosts(team_id):
- _log("allow", "team_allowlist", None)
- return True, None
+ if team_id is not None and is_team_allowlisted_for_internal_hosts(team_id):
+ return _allow_unpinned("team_allowlist")
normalized = host.lower().strip().rstrip(".")
# PostHog-managed DuckLake hosts resolve to internal IPs but are safe.
if normalized.endswith(".postwh.com"):
- _log("allow", "postwh_managed", None)
- return True, None
+ return _allow_unpinned("postwh_managed")
if normalized in {"localhost"}:
- _log("block", "localhost", _INTERNAL_IP_ERROR)
- return False, _INTERNAL_IP_ERROR
+ return _block("localhost", _INTERNAL_IP_ERROR)
try:
if not _is_safe_public_ip(host):
- _log("block", "literal_ip", _INTERNAL_IP_ERROR)
- return False, _INTERNAL_IP_ERROR
+ return _block("literal_ip", _INTERNAL_IP_ERROR)
except ValueError:
pass
+ dns_failure_error = (
+ f"Couldn't resolve the host '{host}'. Check that it's spelled correctly and reachable from the public internet."
+ )
try:
addrinfo = socket.getaddrinfo(normalized, None, proto=socket.IPPROTO_TCP)
resolved_ips = [str(sockaddr[0]) for *_meta, sockaddr in addrinfo]
- for resolved_ip in resolved_ips:
- if not _is_safe_public_ip(resolved_ip):
- _log("block", "resolved_ip", _INTERNAL_IP_ERROR, resolved_ips)
- return False, _INTERNAL_IP_ERROR
except (socket.gaierror, UnicodeError):
# getaddrinfo IDNA-encodes the host, so a malformed hostname (e.g. a DNS label over 63
# bytes) raises UnicodeError ("label too long") instead of gaierror. Either way the host
# can't be resolved — return the actionable message rather than crashing.
_log("block", "dns_failure", _DNS_FAILURE_ERROR)
- return (
- False,
- f"Couldn't resolve the host '{host}'. Check that it's spelled correctly and reachable from the public internet.",
- )
+ return HostResolution(connect_host=None, error=dns_failure_error)
+
+ for resolved_ip in resolved_ips:
+ if not _is_safe_public_ip(resolved_ip):
+ return _block("resolved_ip", _INTERNAL_IP_ERROR, resolved_ips)
+
+ if not resolved_ips:
+ _log("block", "dns_failure", _DNS_FAILURE_ERROR)
+ return HostResolution(connect_host=None, error=dns_failure_error)
_log("allow", "resolved_ip", None, resolved_ips)
- return True, None
+ # getaddrinfo returns addresses in the order the resolver prefers, which is the order a
+ # connect would try them in. Pinning the first one gives up that fallback: if it is down,
+ # nothing tries the next. Every address in the list passed the check above, so this costs
+ # availability on multi-address hosts, not safety.
+ return HostResolution(connect_host=resolved_ips[0], error=None)
def log_connection_open(
@@ -203,6 +243,21 @@ def _require_loopback(host: str) -> str:
return host
+def _pinned_ssh_host(ssh_config, team_id: int | None) -> str:
+ """Resolve the SSH host and return the address to open the tunnel to.
+
+ Enforced here, at the connect, rather than left to `ssh_tunnel_is_valid` at the API layer.
+ That validation runs when a source is created, updated, or directly queried, but the sync
+ path goes from the stored config straight to the tunnel, so a host that resolved to a
+ public address at setup is never re-checked on any later scheduled run. The SSH hop is a
+ raw socket that no egress proxy sees, which makes this check the only thing in its path.
+ """
+ resolution = resolve_safe_host(ssh_config.host, team_id)
+ if resolution.connect_host is None:
+ raise Exception(f"SSH tunnel host not allowed: {resolution.error}")
+ return resolution.connect_host
+
+
@contextmanager
def open_ssh_tunnel(config, team_id: int | None = None) -> Generator[tuple[str, int]]:
"""Yield `(host, port)` for a database connection, going through an SSH tunnel if configured."""
@@ -211,7 +266,9 @@ def open_ssh_tunnel(config, team_id: int | None = None) -> Generator[tuple[str,
if ssh_config is not None:
ssh_tunnel = SSHTunnel.from_config(ssh_config)
- with ssh_tunnel.get_tunnel(config.host, config.port) as tunnel:
+ with ssh_tunnel.get_tunnel(
+ config.host, config.port, ssh_host=_pinned_ssh_host(ssh_config, team_id)
+ ) as tunnel:
if tunnel is None:
raise Exception("Can't open tunnel to SSH server")
@@ -235,7 +292,11 @@ def make_ssh_tunnel_factory(
@contextmanager
def with_ssh_func():
with _logged_connection(config, team_id):
- with ssh_tunnel.get_tunnel(config.host, config.port) as tunnel:
+ # Resolved per reopen, not once when the factory is built, so a long-running
+ # sync that reopens the tunnel re-checks the host each time.
+ with ssh_tunnel.get_tunnel(
+ config.host, config.port, ssh_host=_pinned_ssh_host(ssh_config, team_id)
+ ) as tunnel:
if tunnel is None:
raise Exception("Can't open tunnel to SSH server")
yield _require_loopback(tunnel.local_bind_host), tunnel.local_bind_port
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test_mixins.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test_mixins.py
index 0d0fef8ba334..3eac1c632409 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test_mixins.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test_mixins.py
@@ -1,3 +1,4 @@
+import socket
from dataclasses import dataclass
import pytest
@@ -333,6 +334,51 @@ class TestTunnelYieldsLoopbackOnly(SimpleTestCase):
pass
+class TestSSHTunnelHostIsCheckedAtConnect(SimpleTestCase):
+ # The SSH hop is a raw socket that no egress proxy sees, and the sync path reaches these
+ # entry points without ever running `ssh_tunnel_is_valid`, so what they do here is the only
+ # control on where the tunnel's first connection goes.
+ @staticmethod
+ def _resolves_to(ip: str) -> list:
+ return [(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", (ip, 0))]
+
+ @staticmethod
+ def _tunnel_cm(entrypoint: str, config, team_id: int):
+ if entrypoint == "open_ssh_tunnel":
+ return open_ssh_tunnel(config, team_id)
+ return make_ssh_tunnel_factory(config, team_id)()
+
+ @parameterized.expand([("open_ssh_tunnel",), ("factory",)])
+ @override_settings(CLOUD_DEPLOYMENT="US")
+ def test_connects_to_the_resolved_ip_rather_than_the_hostname(self, entrypoint: str):
+ config = FakeConfig(ssh_tunnel=FakeSSHTunnelConfig(enabled=True, host="bastion.example.com"))
+ with (
+ patch(f"{_MIXINS_MODULE}.SSHTunnel") as mock_ssh,
+ patch(f"{_MIXINS_MODULE}.socket.getaddrinfo", return_value=self._resolves_to("93.184.216.34")),
+ patch(f"{_MIXINS_MODULE}.logger"),
+ ):
+ tunnel = mock_ssh.from_config.return_value.get_tunnel.return_value.__enter__.return_value
+ tunnel.local_bind_host, tunnel.local_bind_port = "127.0.0.1", 55555
+ with self._tunnel_cm(entrypoint, config, 999):
+ pass
+ get_tunnel = mock_ssh.from_config.return_value.get_tunnel
+ assert get_tunnel.call_args.kwargs["ssh_host"] == "93.184.216.34"
+
+ @parameterized.expand([("open_ssh_tunnel",), ("factory",)])
+ @override_settings(CLOUD_DEPLOYMENT="US")
+ def test_host_resolving_to_an_internal_ip_is_refused_before_any_connection(self, entrypoint: str):
+ config = FakeConfig(ssh_tunnel=FakeSSHTunnelConfig(enabled=True, host="bastion.example.com"))
+ with (
+ patch(f"{_MIXINS_MODULE}.SSHTunnel") as mock_ssh,
+ patch(f"{_MIXINS_MODULE}.socket.getaddrinfo", return_value=self._resolves_to("10.0.0.1")),
+ patch(f"{_MIXINS_MODULE}.logger"),
+ ):
+ with pytest.raises(Exception, match="SSH tunnel host not allowed"):
+ with self._tunnel_cm(entrypoint, config, 999):
+ pass
+ mock_ssh.from_config.return_value.get_tunnel.assert_not_called()
+
+
class TestOAuthMixinIntegrationFetchResilience(SimpleTestCase):
@parameterized.expand(
[
diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_import_data.py b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_import_data.py
index 747ad2eac01c..3182e2b9cc16 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_import_data.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_import_data.py
@@ -266,7 +266,7 @@ async def test_postgres_source_with_ssh_tunnel_enabled(activity_environment, tea
activity_inputs = await _setup(team, job_inputs)
- def mock_get_tunnel(self_class, host, port):
+ def mock_get_tunnel(self_class, host, port, *, ssh_host):
class MockedTunnel:
local_bind_host: str = "other-host.com"
local_bind_port: int = 55550