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.

feat(warehouse-sources): let SSH tunnels pin the server host key (#92353)

posthog[bot]545ab834fdfa
diff --git a/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx b/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx
index 8f7c702bb7c3..7b858d1e8fc6 100644
--- a/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx
+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx
@@ -141,6 +141,16 @@ export const SSH_FIELD: SourceFieldSwitchGroupConfigApi = {
},
],
},
+ {
+ name: 'host_key',
+ label: 'SSH host key (optional)',
+ type: 'textarea',
+ required: false,
+ placeholder: 'ssh-ed25519 AAAA...',
+ secret: false,
+ caption:
+ 'Paste one public host key line for the tunnel server, and PostHog verifies its identity on every connect. Get it from your server administrator, or run `ssh-keyscan -p <port> <host>` and pick one of the lines it prints, then confirm that line through a channel you trust. Leave blank to connect without verifying the server.',
+ },
{
name: 'require_tls',
label: 'Require TLS through tunnel?',
diff --git a/products/data_warehouse/frontend/shared/components/forms/SourceForm.test.tsx b/products/data_warehouse/frontend/shared/components/forms/SourceForm.test.tsx
index 131992319ab4..0362ac3b574c 100644
--- a/products/data_warehouse/frontend/shared/components/forms/SourceForm.test.tsx
+++ b/products/data_warehouse/frontend/shared/components/forms/SourceForm.test.tsx
@@ -11,6 +11,9 @@ import {
import { sourceFieldToElement } from './SourceForm'
+// The two field types that carry a caption, both routed through the same caption-to-help contract.
+type CaptionField = SourceFieldSelectConfigApi | SourceFieldInputConfigApi
+
const SELECT_FIELD: SourceFieldSelectConfigApi = {
type: 'select',
name: 'response_types',
@@ -24,6 +27,18 @@ const SELECT_FIELD: SourceFieldSelectConfigApi = {
caption: 'Changing this triggers a full refresh of the responses table.',
}
+// The SSH host-key field is a textarea with a caption. The textarea branch used to drop the
+// caption while every sibling rendered it, so a caption-carrying textarea renders no help.
+const TEXTAREA_FIELD: SourceFieldInputConfigApi = {
+ type: 'textarea',
+ name: 'host_key',
+ label: 'SSH host key (optional)',
+ required: false,
+ placeholder: '',
+ secret: false,
+ caption: 'Paste the server public host key to verify its identity on connect.',
+}
+
const SOURCE_CONFIG = { name: 'Typeform', fields: [] } as unknown as SourceConfigResponseApi
const SWITCH_GROUP_FIELD: SourceFieldSwitchGroupConfigApi = {
@@ -79,13 +94,19 @@ const connectionStringWarns = (value: string): boolean => {
describe('sourceFieldToElement', () => {
afterEach(cleanup)
- it('renders a select field caption as field help text', () => {
- const element = sourceFieldToElement(SELECT_FIELD, SOURCE_CONFIG)
+ it.each([
+ ['select', SELECT_FIELD],
+ ['textarea', TEXTAREA_FIELD],
+ ] as [string, CaptionField][])('renders a %s field caption as field help text', (_name, field) => {
+ const element = sourceFieldToElement(field, SOURCE_CONFIG)
expect(element.props.help).toBeTruthy()
})
- it('omits help when a select field has no caption', () => {
- const element = sourceFieldToElement({ ...SELECT_FIELD, caption: undefined }, SOURCE_CONFIG)
+ it.each([
+ ['select', SELECT_FIELD],
+ ['textarea', TEXTAREA_FIELD],
+ ] as [string, CaptionField][])('omits help when a %s field has no caption', (_name, field) => {
+ const element = sourceFieldToElement({ ...field, caption: undefined }, SOURCE_CONFIG)
expect(element.props.help).toBeUndefined()
})
diff --git a/products/data_warehouse/frontend/shared/components/forms/SourceForm.tsx b/products/data_warehouse/frontend/shared/components/forms/SourceForm.tsx
index 55333a8d029b..55af54dcec5f 100644
--- a/products/data_warehouse/frontend/shared/components/forms/SourceForm.tsx
+++ b/products/data_warehouse/frontend/shared/components/forms/SourceForm.tsx
@@ -324,7 +324,12 @@ export const sourceFieldToElement = (
if (field.type === 'textarea') {
return (
- <LemonField key={field.name} name={field.name} label={field.label}>
+ <LemonField
+ key={field.name}
+ name={field.name}
+ label={field.label}
+ help={field.caption ? <LemonMarkdown className="text-xs">{field.caption}</LemonMarkdown> : undefined}
+ >
{({ value, onChange }) => (
<LemonTextArea
className="ph-ignore-input"
diff --git a/products/warehouse_sources/backend/models/ssh_tunnel.py b/products/warehouse_sources/backend/models/ssh_tunnel.py
index 8564f2e28f05..85f2d52c10b3 100644
--- a/products/warehouse_sources/backend/models/ssh_tunnel.py
+++ b/products/warehouse_sources/backend/models/ssh_tunnel.py
@@ -1,3 +1,4 @@
+import base64
import typing
import dataclasses
from io import StringIO
@@ -16,6 +17,84 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
# format problem, so both the parser and the validator give the same passphrase-specific guidance.
_PASSPHRASE_ERROR_TERMS = ("checksum", "decrypt", "password", "passphrase")
+# The algorithm names paramiko can build a host key from. These are the classes `from_type_string`
+# dispatches on, so each name it accepts is listed here and no other. A pasted host key may be a
+# bare `<type> <base64>` public key or a full known_hosts line (`<host> <type> <base64>`), so we
+# match the algorithm token rather than assume its position. Certificates are excluded, because a
+# certificate is not a host key.
+_SSH_KEY_TYPES = frozenset(
+ identifier
+ for key_class in (DSSKey, RSAKey, Ed25519Key, ECDSAKey)
+ for identifier in key_class.identifiers()
+ if "-cert-v01@" not in identifier
+)
+
+_HOST_KEY_FORMAT_HELP = (
+ "Paste the server's public host key as `<type> <base64>`, for example one line of "
+ "`ssh-keyscan -p <port> <host>` output, or leave it blank to connect without verifying the server."
+)
+
+
+class HostKeyParseError(ValueError):
+ """Carries the user-facing reason a pasted host key was rejected."""
+
+
+def _host_keys_from_line(line: str) -> list[PKey]:
+ """Return every host key on one known_hosts-style line."""
+ keys: list[PKey] = []
+ tokens = line.split()
+ for index, token in enumerate(tokens):
+ if token not in _SSH_KEY_TYPES or index + 1 >= len(tokens):
+ continue
+ try:
+ key_bytes = base64.b64decode(tokens[index + 1], validate=True)
+ key = PKey.from_type_string(token, key_bytes)
+ except Exception:
+ continue
+ # paramiko zero-fills a short blob instead of raising, so a key whose base64 wrapped across
+ # lines still builds a well-formed key that can never match the server. Only a key that
+ # re-serializes to exactly the bytes pasted is the one the user meant to pin.
+ if key.asbytes() != key_bytes:
+ raise HostKeyParseError(
+ "The host key looks incomplete. Paste the whole key on one line, because a line "
+ "break inside the key data cuts it short."
+ )
+ keys.append(key)
+ return keys
+
+
+def host_key_from_string(value: str) -> PKey:
+ """Parse one pasted SSH host public key into a paramiko `PKey`.
+
+ Accepts a bare `<type> <base64>` public key or a `known_hosts` line. The returned key is what
+ paramiko compares the server's presented host key against, so a mismatch fails the handshake
+ instead of trusting whatever key the server offers.
+
+ Rejects a paste that carries more than one key. A tunnel pins exactly one key, so picking one
+ of several would verify a server the user did not choose and silently ignore the rest.
+ """
+ keys: list[PKey] = []
+ for line in value.splitlines():
+ stripped = line.strip()
+ # `ssh-keyscan` interleaves `# host:22 SSH-2.0-...` banner lines with the keys.
+ if len(stripped) == 0 or stripped.startswith("#"):
+ continue
+ if stripped.startswith("@"):
+ raise HostKeyParseError(
+ "A `@cert-authority` or `@revoked` known_hosts line is not a host key. Paste the "
+ "server's own public host key instead."
+ )
+ keys.extend(_host_keys_from_line(stripped))
+
+ if len(keys) > 1:
+ raise HostKeyParseError(
+ "Paste a single host key. `ssh-keyscan` prints one line per key type, so pick the one "
+ "you want to pin, for example the `ssh-ed25519` line."
+ )
+ if len(keys) == 0:
+ raise HostKeyParseError(f"No SSH host key found. {_HOST_KEY_FORMAT_HELP}")
+ return keys[0]
+
# Taken from https://stackoverflow.com/questions/60660919/paramiko-ssh-client-is-unable-to-unpack-ed25519-key
def from_private_key(file_obj: IO[str], passphrase: str | None = None) -> PKey:
@@ -89,6 +168,10 @@ class SSHTunnelConfig(config.Config):
auth: SSHTunnelAuthConfig = config.value(alias="auth_type", default_factory=SSHTunnelAuthConfig)
enabled: bool = config.value(converter=config.str_to_bool, default=False)
require_tls: SSHTunnelRequireTlsConfig = config.value(default_factory=SSHTunnelRequireTlsConfig)
+ # Optional pinned host key for the SSH server. When set, paramiko verifies the server presents
+ # this exact key and rejects any other. Left blank keeps the prior behavior: the tunnel is
+ # encrypted but the server's identity is not checked.
+ host_key: str | None = None
@frozen
@@ -102,6 +185,8 @@ class SSHTunnel:
password: str | None = dataclasses.field(repr=False)
private_key: str | None = dataclasses.field(repr=False)
passphrase: str | None = dataclasses.field(repr=False)
+ # Public host key, so safe to keep in repr; None means the server's identity is not verified.
+ host_key: str | None = None
@classmethod
def from_config(cls: type[typing.Self], config: SSHTunnelConfig) -> typing.Self:
@@ -124,6 +209,7 @@ class SSHTunnel:
password=config.auth.password,
private_key=config.auth.private_key,
passphrase=config.auth.passphrase,
+ host_key=config.host_key or None,
)
def parse_private_key(self) -> PKey:
@@ -136,6 +222,26 @@ class SSHTunnel:
return from_private_key(StringIO(self.private_key), passphrase)
+ def parse_host_key(self) -> PKey | None:
+ """Return the pinned host key as a paramiko `PKey`, or None when none is configured."""
+ if self.host_key is None or len(self.host_key.strip()) == 0:
+ return None
+ return host_key_from_string(self.host_key)
+
+ def is_host_key_valid(self) -> tuple[bool, str]:
+ # The host key is optional, so a blank value is valid and just leaves the server unverified.
+ if self.host_key is None or len(self.host_key.strip()) == 0:
+ return True, ""
+
+ try:
+ self.parse_host_key()
+ except HostKeyParseError as e:
+ return False, str(e)
+ except Exception:
+ return False, f"SSH host key could not be parsed. {_HOST_KEY_FORMAT_HELP}"
+
+ return True, ""
+
def is_auth_valid(self) -> tuple[bool, str]:
if self.auth_type != "password" and self.auth_type != "keypair":
return False, "Authentication type not recognised" # type: ignore
@@ -193,9 +299,9 @@ class SSHTunnel:
`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.
+ and the connected address have to be the same one. Passing an IP does not weaken host-key
+ verification: paramiko compares the pinned `ssh_host_key` against the key the server
+ presents, not against the name we dialed.
"""
if not self.is_auth_valid()[0]:
raise Exception("SSHTunnel auth is not valid")
@@ -203,11 +309,19 @@ class SSHTunnel:
if not self.has_valid_port()[0]:
raise Exception("SSHTunnel port is not valid")
+ # Parsed once rather than through `is_host_key_valid`, which would parse the same key and
+ # throw it away. None leaves the handshake unverified, exactly as before this field existed.
+ try:
+ ssh_host_key = self.parse_host_key()
+ except Exception as e:
+ raise Exception("SSHTunnel host key is not valid") from e
+
if self.auth_type == "password":
return SSHTunnelForwarder(
(ssh_host, int(self.port)),
ssh_username=self.username,
ssh_password=self.password,
+ ssh_host_key=ssh_host_key,
remote_bind_address=(remote_host, remote_port),
local_bind_address=("127.0.0.1",),
)
@@ -217,6 +331,7 @@ class SSHTunnel:
ssh_username=self.username,
ssh_pkey=self.parse_private_key(),
ssh_private_key_password=self.passphrase,
+ ssh_host_key=ssh_host_key,
remote_bind_address=(remote_host, remote_port),
local_bind_address=("127.0.0.1",),
)
diff --git a/products/warehouse_sources/backend/presentation/views/external_data_source/helpers.py b/products/warehouse_sources/backend/presentation/views/external_data_source/helpers.py
index c38720f3a091..b9331c30c691 100644
--- a/products/warehouse_sources/backend/presentation/views/external_data_source/helpers.py
+++ b/products/warehouse_sources/backend/presentation/views/external_data_source/helpers.py
@@ -315,7 +315,7 @@ def get_nonsensitive_and_sensitive_field_names(fields: list[FieldType]) -> Field
_add_name_variants(nonsensitive, field.name)
# SSH tunnel has a known nested structure not declared in the field tree.
# "auth"/"auth_type" are container keys for SSHTunnelAuthConfig.
- nonsensitive.update({"host", "port", "username", "auth", "auth_type", "require_tls"})
+ nonsensitive.update({"host", "port", "username", "auth", "auth_type", "require_tls", "host_key"})
sensitive.update({"password", "passphrase", "private_key"})
return FieldSensitivitySplit(nonsensitive=nonsensitive, sensitive=sensitive)
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 2827d8ad8238..1a8c5929069e 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
@@ -673,6 +673,10 @@ class SSHTunnelMixin:
if not is_port_valid:
return is_port_valid, port_errors
+ is_host_key_valid, host_key_errors = ssh_tunnel.is_host_key_valid()
+ if not is_host_key_valid:
+ return is_host_key_valid, host_key_errors
+
return True, None
diff --git a/products/warehouse_sources/backend/tests/test_ssh_tunnel.py b/products/warehouse_sources/backend/tests/test_ssh_tunnel.py
index 37fa7260e63e..f86f833b6c9f 100644
--- a/products/warehouse_sources/backend/tests/test_ssh_tunnel.py
+++ b/products/warehouse_sources/backend/tests/test_ssh_tunnel.py
@@ -2,10 +2,25 @@ import pytest
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import ed25519
+from paramiko import RSAKey
from products.warehouse_sources.backend.models.ssh_tunnel import SSHTunnel, SSHTunnelConfig
+def _password_tunnel(host_key: str | None) -> SSHTunnel:
+ return SSHTunnel(
+ enabled=True,
+ host="host.com",
+ port=5432,
+ auth_type="password",
+ username="user1",
+ password="password",
+ private_key=None,
+ passphrase=None,
+ host_key=host_key,
+ )
+
+
def _keypair_tunnel(private_key: str | None, passphrase: str | None) -> SSHTunnel:
return SSHTunnel(
enabled=True,
@@ -113,6 +128,95 @@ def test_is_auth_valid_wrong_passphrase_suggests_passphrase():
assert "passphrase" in error.lower()
+def _host_key_line(key_type: str) -> str:
+ if key_type == "ssh-rsa":
+ key = RSAKey.generate(2048)
+ return f"{key.get_name()} {key.get_base64()}"
+
+ public_key = ed25519.Ed25519PrivateKey.generate().public_key()
+ return public_key.public_bytes(serialization.Encoding.OpenSSH, serialization.PublicFormat.OpenSSH).decode()
+
+
[email protected]("host_key", [None, "", " \n "])
+def test_blank_host_key_leaves_server_unverified(host_key):
+ tunnel = _password_tunnel(host_key=host_key)
+
+ assert tunnel.is_host_key_valid() == (True, "")
+ assert tunnel.parse_host_key() is None
+ assert tunnel.get_tunnel("host.com", 3306, ssh_host="93.184.216.34").ssh_host_key is None
+
+
+ "host_key,expected",
+ [
+ ("not a host key", "no ssh host key found"),
+ ("@cert-authority *.example.com ssh-rsa AAAAB3NzaC1yc2E=", "not a host key"),
+ ("@revoked host.com ssh-rsa AAAAB3NzaC1yc2E=", "not a host key"),
+ ],
+)
+def test_unparseable_host_key_is_rejected(host_key, expected):
+ res, error = _password_tunnel(host_key=host_key).is_host_key_valid()
+
+ assert res is False
+ assert expected in error.lower()
+
+
[email protected]("on_one_line", [False, True])
+def test_multiple_host_keys_are_rejected(on_one_line):
+ rsa_key, ed25519_key = _host_key_line("ssh-rsa"), _host_key_line("ssh-ed25519")
+ if on_one_line:
+ paste = f"host.com {rsa_key} {ed25519_key}"
+ else:
+ paste = "\n".join(["# host.com:22 SSH-2.0-OpenSSH_9.6", f"host.com {rsa_key}", f"host.com {ed25519_key}"])
+
+ res, error = _password_tunnel(host_key=paste).is_host_key_valid()
+
+ assert res is False
+ assert "single host key" in error.lower()
+
+
+def test_a_host_key_wrapped_across_lines_is_rejected():
+ key_type, key_base64 = _host_key_line("ssh-rsa").split()
+
+ res, error = _password_tunnel(host_key=f"{key_type} {key_base64[:60]}\n{key_base64[60:]}").is_host_key_valid()
+
+ assert res is False
+ assert "incomplete" in error.lower()
+
+
+def test_a_key_advertised_under_an_sha2_name_is_accepted():
+ _, key_base64 = _host_key_line("ssh-rsa").split()
+
+ parsed = _password_tunnel(host_key=f"rsa-sha2-256 {key_base64}").parse_host_key()
+
+ assert parsed is not None
+ assert parsed.get_base64() == key_base64
+
+
+ "key_type,hostname",
+ [
+ ("ssh-rsa", None),
+ ("ssh-rsa", "host.com"),
+ ("ssh-rsa", "ssh-bastion.example.com"),
+ ("ssh-rsa", "ssh-jump.corp.net,10.0.0.5"),
+ ("ssh-ed25519", None),
+ ("ssh-ed25519", "host.com"),
+ ],
+)
+def test_get_tunnel_pins_host_key(key_type, hostname):
+ line = _host_key_line(key_type)
+ key_name, key_base64 = line.split()
+ tunnel = _password_tunnel(host_key=f"{hostname} {line}" if hostname else line)
+
+ parsed = tunnel.parse_host_key()
+
+ assert parsed is not None
+ assert (parsed.get_name(), parsed.get_base64()) == (key_name, key_base64)
+ forwarder = tunnel.get_tunnel("host.com", 3306, ssh_host="93.184.216.34")
+ assert forwarder.ssh_host_key == parsed
+
+
def test_get_tunnel_invalid_auth():
ssh_tunnel = SSHTunnel(
enabled=True,