fix(security): add SSRF guard to Fabric/OneLake adapter's sqlEndpoint
masterplan-lock / check (push) Successful in 7s
CI (SIAX Cloud) / security (push) Successful in 19s
Security Scan (SIAX Cloud) / security (push) Successful in 27s
CI (SIAX Cloud) / quality (push) Successful in 33s
CI (SIAX Cloud) / integration (push) Successful in 46s
masterplan-lock / check (pull_request) Successful in 4s
Security Scan (SIAX Cloud) / security (pull_request) Successful in 16s
CI (SIAX Cloud) / security (pull_request) Successful in 17s
CI (SIAX Cloud) / quality (pull_request) Successful in 35s
CI (SIAX Cloud) / integration (pull_request) Successful in 1m11s
masterplan-lock / check (push) Successful in 7s
CI (SIAX Cloud) / security (push) Successful in 19s
Security Scan (SIAX Cloud) / security (push) Successful in 27s
CI (SIAX Cloud) / quality (push) Successful in 33s
CI (SIAX Cloud) / integration (push) Successful in 46s
masterplan-lock / check (pull_request) Successful in 4s
Security Scan (SIAX Cloud) / security (pull_request) Successful in 16s
CI (SIAX Cloud) / security (pull_request) Successful in 17s
CI (SIAX Cloud) / quality (pull_request) Successful in 35s
CI (SIAX Cloud) / integration (pull_request) Successful in 1m11s
connection_config.sqlEndpoint on POST /api/0pt/sources/{sourceId}/query
was passed straight from the request body to the mssql TDS driver as the
outbound connection target, with only its http(s):// scheme stripped —
no hostname allowlist or private/loopback/link-local/cloud-metadata
guard. This route already requires a Zitadel bearer token + tenant match
(P014 tenant guard), so this was not anonymously exploitable, but it is
the exact SSRF shape found and exploited-in-principle elsewhere in this
estate tonight (press0), so it's worth closing as defense-in-depth.
Adds src/lib/security/ssrf-guard.ts: resolves the endpoint's hostname
and rejects any address in a private/loopback/link-local/cloud-metadata/
unspecified range (RFC1918, 127.0.0.0/8, 169.254.0.0/16 incl. the
169.254.169.254 metadata address, ::1, fc00::/7, fe80::/10, IPv4-mapped
IPv6), failing closed on DNS resolution errors. The range-check logic is
ported 1:1 from press0's src/lib/security/ssrf-guard.ts built the same
night for the same bug class against a fetch()-based URL there; this
module's surface differs because sqlEndpoint is a bare host[:port], not
a fetchable URL. The DNS lookup is injectable (mirrors this adapter's
existing fetchImpl pattern) so tests are hermetic.
FabricOneLakeAdapter.getPool() now calls the guard before loadDriver()/
getToken()/opening the TDS pool, so a blocked target never reaches a
real outbound connection attempt or spends an AAD token exchange.
Tests: new tests/p0/fabric-onelake-ssrf-guard.test.ts unit-tests the
guard module directly (range boundaries, IPv4-mapped-IPv6 bypass
attempt, fail-closed on DNS failure/empty answer). New adapter-level
tests in tests/p0/fabric-onelake-adapter.test.ts prove (a) a
private-IP-resolving sqlEndpoint is rejected before fetch/connect is
ever called, (b) a literal loopback sqlEndpoint is rejected the same
way, and (c) a normal external Fabric hostname still passes the guard
and completes the query — the guard doesn't false-block legitimate
targets. Existing adapter tests are updated to inject a deterministic
DNS resolver so they stay hermetic instead of depending on real DNS.
Full suite: 997 passed, 0 failed, 184 skipped (self-skipping realinfra
tests with no live backend this run). typecheck and lint clean on all
touched files.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -35,8 +35,21 @@
|
||||
* Once `mssql` is added to package.json (`pnpm add mssql`), query() works
|
||||
* against a real endpoint with no code change here. Until then, `query()`
|
||||
* throws a clear, actionable error — see docs/P0_QUERY_SOURCE_FLOW.md.
|
||||
*
|
||||
* SSRF guard: `connection_config.sqlEndpoint` is caller-supplied per-request
|
||||
* (via POST /api/0pt/sources/{sourceId}/query -> source-query-service.ts)
|
||||
* and, until now, only had its scheme stripped before being handed to the
|
||||
* `mssql` driver as the outbound connection target — no hostname allowlist
|
||||
* or private/loopback/link-local/cloud-metadata check. `getPool()` now
|
||||
* resolves and validates the endpoint via
|
||||
* `src/lib/security/ssrf-guard.ts::assertConnectionHostIsSafe` *before*
|
||||
* constructing the pool, closing that gap defense-in-depth (this route
|
||||
* already requires a Zitadel bearer token + tenant match — see
|
||||
* src/http/tenant-guard.ts).
|
||||
*/
|
||||
|
||||
import { assertConnectionHostIsSafe, type DnsLookupFn } from "../lib/security/ssrf-guard";
|
||||
|
||||
const DEFAULT_SQL_SCOPE = "https://database.windows.net/.default";
|
||||
const TOKEN_REFRESH_SKEW_MS = 60_000;
|
||||
const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;
|
||||
@@ -138,6 +151,13 @@ export class FabricOneLakeAdapter {
|
||||
constructor(
|
||||
private readonly config: FabricOneLakeConnectionConfig,
|
||||
private readonly fetchImpl: typeof fetch = fetch,
|
||||
/**
|
||||
* Injectable DNS resolver for the SSRF guard (see `getPool()`).
|
||||
* Overridable for tests, same rationale as `fetchImpl`; defaults to the
|
||||
* real `node:dns` resolver in production (undefined -> ssrf-guard's own
|
||||
* default).
|
||||
*/
|
||||
private readonly dnsLookupImpl?: DnsLookupFn,
|
||||
) {}
|
||||
|
||||
private async getToken(): Promise<string> {
|
||||
@@ -171,6 +191,13 @@ export class FabricOneLakeAdapter {
|
||||
|
||||
private async getPool(): Promise<InstanceType<MssqlLike["ConnectionPool"]>> {
|
||||
if (this.pool) return this.pool;
|
||||
// SSRF guard: resolve + validate the caller-supplied sqlEndpoint before
|
||||
// doing anything else — in particular before loadDriver()/getToken(), so
|
||||
// a blocked target never gets as far as a real outbound connection
|
||||
// attempt (or spends an AAD token exchange on a request that will be
|
||||
// refused anyway). Throws SsrfBlockedHostError for a private/loopback/
|
||||
// link-local/cloud-metadata/unspecified address, or an unresolvable host.
|
||||
await assertConnectionHostIsSafe(this.config.sqlEndpoint, this.dnsLookupImpl);
|
||||
const sql = await this.loadDriver();
|
||||
const token = await this.getToken();
|
||||
const poolConfig = {
|
||||
@@ -218,6 +245,10 @@ export class FabricOneLakeAdapter {
|
||||
}
|
||||
}
|
||||
|
||||
export function createFabricOneLakeAdapter(config: FabricOneLakeConnectionConfig, fetchImpl?: typeof fetch): FabricOneLakeAdapter {
|
||||
return new FabricOneLakeAdapter(config, fetchImpl);
|
||||
export function createFabricOneLakeAdapter(
|
||||
config: FabricOneLakeConnectionConfig,
|
||||
fetchImpl?: typeof fetch,
|
||||
dnsLookupImpl?: DnsLookupFn,
|
||||
): FabricOneLakeAdapter {
|
||||
return new FabricOneLakeAdapter(config, fetchImpl, dnsLookupImpl);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
/**
|
||||
* src/lib/security/ssrf-guard.ts
|
||||
* =================================
|
||||
* SSRF guard for outbound connections this backend opens to a caller-
|
||||
* supplied host. Today's one caller: `FabricOneLakeAdapter.getPool()`
|
||||
* (src/adapters/fabric-onelake-adapter.ts), whose `connection_config.
|
||||
* sqlEndpoint` arrives via `POST /api/0pt/sources/{sourceId}/query ->
|
||||
* source-query-service.ts` — a caller-supplied value that, before this
|
||||
* guard, only had its `http(s)://` scheme stripped (see `stripScheme` in
|
||||
* fabric-onelake-adapter.ts) before being handed straight to the `mssql`
|
||||
* TDS driver as the connection target. Nothing stopped a request from
|
||||
* pointing `sqlEndpoint` at 127.0.0.1, an RFC1918 address, or the
|
||||
* cloud-metadata link-local address (169.254.169.254) and having this
|
||||
* backend open a real outbound SQL connection there. That route requires a
|
||||
* valid Zitadel bearer token + tenant match (the P014 tenant guard,
|
||||
* src/http/tenant-guard.ts) today, so this is defense-in-depth rather than
|
||||
* the only control — worth closing anyway given it is the exact SSRF shape
|
||||
* found elsewhere in this estate (press0's fulltext-ingestion fetch path).
|
||||
*
|
||||
* The range-check logic (BLOCKED_V4_RANGES / isBlockedV4 / isBlockedV6) is
|
||||
* ported 1:1 from press0's `src/lib/security/ssrf-guard.ts`, built the same
|
||||
* night for the same class of bug against a `fetch()`-based URL there. This
|
||||
* module's public surface differs because the input here is a bare
|
||||
* `host[:port]` connection endpoint, not a fetchable URL — no scheme, path
|
||||
* or query is meaningful on the wire — so `extractConnectionHostname`
|
||||
* parses that shape instead of `new URL(...)`. The safety decision itself
|
||||
* is identical: resolve the hostname, reject any resolved address in a
|
||||
* private/loopback/link-local/cloud-metadata/unspecified range, and fail
|
||||
* closed (treat as unsafe) on resolution failure. Checking the *resolved*
|
||||
* address rather than string-matching the hostname is what stops a
|
||||
* public-looking hostname whose DNS record actually points at an internal
|
||||
* address — plain hostname allowlisting doesn't catch that.
|
||||
*
|
||||
* The DNS lookup is injectable (`lookupImpl`) — the same dependency-
|
||||
* injection pattern this file's caller already uses for `fetchImpl` — so
|
||||
* tests get a deterministic resolver instead of depending on real DNS.
|
||||
*/
|
||||
|
||||
import net from "node:net";
|
||||
import { promises as dns } from "node:dns";
|
||||
|
||||
export interface DnsLookupAddress {
|
||||
address: string;
|
||||
family: number;
|
||||
}
|
||||
|
||||
/** Matches the subset of `dns.promises.lookup(host, { all: true, verbatim: true })` this module needs. */
|
||||
export type DnsLookupFn = (hostname: string) => Promise<DnsLookupAddress[]>;
|
||||
|
||||
const defaultLookup: DnsLookupFn = (hostname) => dns.lookup(hostname, { all: true, verbatim: true });
|
||||
|
||||
const BLOCKED_V4_RANGES: ReadonlyArray<readonly [string, number]> = [
|
||||
["10.0.0.0", 8], // RFC1918 private
|
||||
["172.16.0.0", 12], // RFC1918 private
|
||||
["192.168.0.0", 16], // RFC1918 private
|
||||
["127.0.0.0", 8], // loopback
|
||||
["169.254.0.0", 16], // link-local (also cloud metadata: 169.254.169.254)
|
||||
["0.0.0.0", 8], // "this network" / unspecified
|
||||
];
|
||||
|
||||
function ipv4ToInt(ip: string): number {
|
||||
return (
|
||||
ip
|
||||
.split(".")
|
||||
.reduce((acc, octet) => (acc << 8) + (Number(octet) & 0xff), 0) >>> 0
|
||||
);
|
||||
}
|
||||
|
||||
export function isBlockedV4(ip: string): boolean {
|
||||
if (!net.isIPv4(ip)) return false;
|
||||
const ipInt = ipv4ToInt(ip);
|
||||
return BLOCKED_V4_RANGES.some(([base, bits]) => {
|
||||
const mask = bits === 0 ? 0 : (0xffffffff << (32 - bits)) >>> 0;
|
||||
return (ipInt & mask) === (ipv4ToInt(base) & mask);
|
||||
});
|
||||
}
|
||||
|
||||
function firstHextet(ip: string): number | null {
|
||||
const first = ip.split(":")[0];
|
||||
if (first === undefined) return null;
|
||||
if (first === "") return 0; // address starts with "::"
|
||||
const n = parseInt(first, 16);
|
||||
return Number.isNaN(n) ? null : n;
|
||||
}
|
||||
|
||||
export function isBlockedV6(ip: string): boolean {
|
||||
if (!net.isIPv6(ip)) return false;
|
||||
const lower = ip.toLowerCase();
|
||||
if (lower === "::1" || lower === "::") return true; // loopback / unspecified
|
||||
|
||||
// IPv4-mapped IPv6 (::ffff:a.b.c.d) — unwrap and re-check as v4, since this
|
||||
// is the standard way to smuggle a blocked v4 address past a v6-literal-
|
||||
// shaped filter.
|
||||
if (lower.startsWith("::ffff:")) {
|
||||
const v4 = lower.slice("::ffff:".length);
|
||||
if (net.isIPv4(v4)) return isBlockedV4(v4);
|
||||
}
|
||||
|
||||
const h = firstHextet(lower);
|
||||
if (h === null) return false;
|
||||
if (h >= 0xfc00 && h <= 0xfdff) return true; // fc00::/7 — unique local
|
||||
if (h >= 0xfe80 && h <= 0xfebf) return true; // fe80::/10 — link-local
|
||||
return false;
|
||||
}
|
||||
|
||||
function isBlockedAddress(address: string, family: number): boolean {
|
||||
if (family === 4) return isBlockedV4(address);
|
||||
if (family === 6) return isBlockedV6(address);
|
||||
return true; // unknown family — fail closed
|
||||
}
|
||||
|
||||
export type HostSafetyResult = { ok: true } | { ok: false; reason: string };
|
||||
|
||||
/**
|
||||
* Parses the bare connection-endpoint shape `FabricOneLakeConnectionConfig
|
||||
* .sqlEndpoint` takes: an optional `scheme://` prefix (already tolerated
|
||||
* elsewhere via `stripScheme`), a hostname or bracketed IPv6 literal, an
|
||||
* optional `:port`, and — defensively, even though a SQL endpoint should
|
||||
* never carry one — a path/query/fragment, which is discarded. Returns the
|
||||
* bare hostname, ready to resolve.
|
||||
*/
|
||||
export function extractConnectionHostname(rawEndpoint: string): string {
|
||||
let value = rawEndpoint.trim().replace(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//, "");
|
||||
value = value.split(/[/?#]/)[0] ?? "";
|
||||
|
||||
// Bracketed IPv6 literal, optionally with a port: "[::1]" or "[::1]:1433".
|
||||
const ipv6Match = value.match(/^\[([^\]]+)\](?::\d+)?$/);
|
||||
if (ipv6Match) return ipv6Match[1];
|
||||
|
||||
// A bare (unbracketed) IPv6 literal has no unambiguous port form — RFC
|
||||
// 3986 requires brackets for that precisely because the address itself is
|
||||
// full of colons. If the whole remaining value already parses as a valid
|
||||
// IPv6 address, return it as-is instead of trying to strip a "port" out
|
||||
// of one of its own colons (naive last-colon-splitting would truncate
|
||||
// "fe80::1" to "fe80:").
|
||||
if (net.isIP(value) === 6) return value;
|
||||
|
||||
const portMatch = value.match(/^(.+):(\d+)$/);
|
||||
if (portMatch) return portMatch[1];
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves `hostname` and checks every returned address against the blocked
|
||||
* ranges. Fails closed: DNS resolution errors or an empty answer are
|
||||
* treated as unsafe, same as press0's `isUrlSafeToFetch`.
|
||||
*/
|
||||
export async function checkHostnameSafety(
|
||||
hostname: string,
|
||||
lookupImpl: DnsLookupFn = defaultLookup,
|
||||
): Promise<HostSafetyResult> {
|
||||
if (!hostname) return { ok: false, reason: "empty_hostname" };
|
||||
|
||||
let addresses: DnsLookupAddress[];
|
||||
try {
|
||||
addresses = await lookupImpl(hostname);
|
||||
} catch {
|
||||
return { ok: false, reason: "dns_resolution_failed" };
|
||||
}
|
||||
|
||||
if (addresses.length === 0) {
|
||||
return { ok: false, reason: "dns_resolution_failed" };
|
||||
}
|
||||
|
||||
if (addresses.some((a) => isBlockedAddress(a.address, a.family))) {
|
||||
return { ok: false, reason: "blocked_address_range" };
|
||||
}
|
||||
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
export class SsrfBlockedHostError extends Error {}
|
||||
|
||||
/**
|
||||
* Throws `SsrfBlockedHostError` if `rawEndpoint`'s hostname resolves to (or
|
||||
* literally is) a private/loopback/link-local/cloud-metadata/unspecified
|
||||
* address. Call this before opening the outbound connection — the check
|
||||
* itself never opens one.
|
||||
*/
|
||||
export async function assertConnectionHostIsSafe(rawEndpoint: string, lookupImpl?: DnsLookupFn): Promise<void> {
|
||||
const hostname = extractConnectionHostname(rawEndpoint);
|
||||
const result = await checkHostnameSafety(hostname, lookupImpl);
|
||||
if (!result.ok) {
|
||||
throw new SsrfBlockedHostError(
|
||||
`fabric_onelake_adapter: sqlEndpoint host "${hostname}" is blocked by the SSRF guard (${result.reason}) — ` +
|
||||
`refusing to open an outbound connection to a private/loopback/link-local/cloud-metadata/unspecified address`,
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user