Skip to content

A local-first personal finance app

[AI] Add SSRF protection to SimpleFIN bank sync integration (#8012)

Matiss Janis Aboltinsf667b5c65672
diff --git a/packages/sync-server/src/app-cors-proxy.js b/packages/sync-server/src/app-cors-proxy.js
index d94e9283dd..916df29944 100644
--- a/packages/sync-server/src/app-cors-proxy.js
+++ b/packages/sync-server/src/app-cors-proxy.js
@@ -1,9 +1,9 @@
import express from 'express';
import rateLimit from 'express-rate-limit';
-import ipaddr from 'ipaddr.js';
import { config } from './load-config';
import { requestLoggerMiddleware } from './util/middlewares';
+import { isBlockedIp } from './util/ssrf';
import { validateSession } from './util/validate-user';
const app = express();
@@ -68,20 +68,9 @@ function isUrlAllowed(targetUrl) {
const hostname = url.hostname;
// Block private/local IP addresses
- if (ipaddr.isValid(hostname)) {
- const ip = ipaddr.parse(hostname);
- if (
- [
- 'private',
- 'loopback',
- 'linkLocal',
- 'uniqueLocal',
- 'unspecified',
- ].includes(ip.range())
- ) {
- console.warn(`Blocked request to private/localhost IP: ${hostname}`);
- return false;
- }
+ if (isBlockedIp(hostname)) {
+ console.warn(`Blocked request to private/localhost IP: ${hostname}`);
+ return false;
}
// Always allow the specific plugin-store URL
diff --git a/packages/sync-server/src/app-cors-proxy.test.js b/packages/sync-server/src/app-cors-proxy.test.js
index 4d456be689..48e0eadae3 100644
--- a/packages/sync-server/src/app-cors-proxy.test.js
+++ b/packages/sync-server/src/app-cors-proxy.test.js
@@ -1,4 +1,3 @@
-import ipaddr from 'ipaddr.js';
import request from 'supertest';
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -24,13 +23,6 @@ vi.mock('express-rate-limit', () => ({
default: vi.fn(() => (req, res, next) => next()),
}));
-vi.mock('ipaddr.js', () => ({
- default: {
- isValid: vi.fn().mockReturnValue(false),
- parse: vi.fn(),
- },
-}));
-
global.fetch = vi.fn();
describe('app-cors-proxy', () => {
@@ -166,8 +158,6 @@ describe('app-cors-proxy', () => {
beforeEach(() => {
validateSession.mockClear?.();
- ipaddr.isValid.mockClear?.();
- ipaddr.parse.mockClear?.();
validateSession.mockReturnValue({ userId: 'test-user' });
@@ -238,11 +228,6 @@ describe('app-cors-proxy', () => {
});
it('should block private IP addresses', async () => {
- ipaddr.isValid.mockReturnValueOnce(true);
- ipaddr.parse.mockReturnValueOnce({
- range: () => 'private',
- });
-
const res = await request(app)
.get('/')
.query({ url: 'http://192.168.1.1/test' });
@@ -255,11 +240,6 @@ describe('app-cors-proxy', () => {
});
it('should block loopback addresses', async () => {
- ipaddr.isValid.mockReturnValueOnce(true);
- ipaddr.parse.mockReturnValueOnce({
- range: () => 'loopback',
- });
-
const res = await request(app)
.get('/')
.query({ url: 'http://127.0.0.1/test' });
diff --git a/packages/sync-server/src/app-simplefin/app-simplefin.js b/packages/sync-server/src/app-simplefin/app-simplefin.js
index 597f35f94e..d100fdda17 100644
--- a/packages/sync-server/src/app-simplefin/app-simplefin.js
+++ b/packages/sync-server/src/app-simplefin/app-simplefin.js
@@ -8,6 +8,7 @@ import {
requestLoggerMiddleware,
validateSessionMiddleware,
} from '#util/middlewares';
+import { assertUrlAllowed } from '#util/ssrf';
const app = express();
export { app as handlers };
@@ -314,6 +315,10 @@ function parseAccessKey(accessKey) {
async function getAccessKey(base64Token) {
const token = Buffer.from(base64Token, 'base64').toString();
+ // Self-hosters may run their own SimpleFIN bridge on the local network, so
+ // private addresses are allowed here; cloud metadata and other always-blocked
+ // ranges are still rejected.
+ await assertUrlAllowed(token, { allowPrivateNetwork: true });
const options = {
method: 'POST',
port: 443,
@@ -385,11 +390,37 @@ async function getAccounts(
const url = new URL(`${sfin.baseUrl}/accounts`);
url.search = params.toString();
- const response = await fetch(url.toString(), {
- method: 'GET',
- headers,
- redirect: 'follow',
- });
+ // Follow redirects manually so every hop is re-validated against the SSRF
+ // rules; fetch's automatic 'follow' would let a 3xx response redirect to a
+ // blocked address after only the initial URL was checked. Authorization is
+ // dropped once a redirect leaves the original origin (matching fetch's
+ // default cross-origin stripping) so the bridge credentials aren't leaked.
+ const MAX_REDIRECTS = 5;
+ let currentUrl = url.toString();
+ let response;
+ for (let hop = 0; ; hop++) {
+ await assertUrlAllowed(currentUrl, { allowPrivateNetwork: true });
+
+ response = await fetch(currentUrl, {
+ method: 'GET',
+ headers,
+ redirect: 'manual',
+ });
+
+ const location = response.headers.get('location');
+ if (response.status < 300 || response.status >= 400 || !location) {
+ break;
+ }
+ if (hop >= MAX_REDIRECTS) {
+ throw new Error('Too many redirects');
+ }
+
+ const nextUrl = new URL(location, currentUrl);
+ if (nextUrl.origin !== new URL(currentUrl).origin) {
+ delete headers.Authorization;
+ }
+ currentUrl = nextUrl.toString();
+ }
if (response.status === 403) {
throw new Error('Forbidden');
diff --git a/packages/sync-server/src/util/ssrf.test.ts b/packages/sync-server/src/util/ssrf.test.ts
new file mode 100644
index 0000000000..d0ccdeeb61
--- /dev/null
+++ b/packages/sync-server/src/util/ssrf.test.ts
@@ -0,0 +1,162 @@
+import dns from 'dns';
+
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { assertUrlAllowed } from './ssrf';
+
+vi.mock('dns', () => ({
+ default: {
+ lookup: vi.fn(),
+ },
+}));
+
+type LookupCallback = (err: Error | null, addresses: unknown) => void;
+
+function setLookupImpl(handler: (callback: LookupCallback) => void) {
+ // dns.lookup has several overloads; the callback is always the last argument.
+ vi.mocked(dns.lookup).mockImplementation((...args: unknown[]) => {
+ const callback = args[args.length - 1] as LookupCallback;
+ handler(callback);
+ });
+}
+
+function mockDnsLookup(addresses: string[]) {
+ // promisify(dns.lookup) with { all: true } calls back with an array.
+ setLookupImpl(callback =>
+ callback(
+ null,
+ addresses.map(address => ({ address, family: 4 })),
+ ),
+ );
+}
+
+function mockDnsFailure() {
+ setLookupImpl(callback => callback(new Error('ENOTFOUND'), null));
+}
+
+describe('assertUrlAllowed', () => {
+ afterEach(() => {
+ vi.resetAllMocks();
+ });
+
+ it('allows a public hostname', async () => {
+ mockDnsLookup(['8.8.8.8']);
+ await expect(
+ assertUrlAllowed('https://beta-bridge.simplefin.org/claim/abc'),
+ ).resolves.toBeUndefined();
+ });
+
+ it('allows a public literal IP without a DNS lookup', async () => {
+ await expect(
+ assertUrlAllowed('https://8.8.8.8/claim'),
+ ).resolves.toBeUndefined();
+ expect(dns.lookup).not.toHaveBeenCalled();
+ });
+
+ it('blocks the cloud metadata endpoint (link-local literal IP)', async () => {
+ await expect(
+ assertUrlAllowed('http://169.254.169.254/latest/meta-data/'),
+ ).rejects.toThrow(/private\/local IP/);
+ });
+
+ it('blocks the cloud metadata endpoint even when private networks are allowed', async () => {
+ await expect(
+ assertUrlAllowed('http://169.254.169.254/latest/meta-data/', {
+ allowPrivateNetwork: true,
+ }),
+ ).rejects.toThrow(/private\/local IP/);
+ });
+
+ it('blocks reserved and broadcast ranges even when private networks are allowed', async () => {
+ await expect(
+ assertUrlAllowed('http://240.0.0.1/', { allowPrivateNetwork: true }),
+ ).rejects.toThrow();
+ await expect(
+ assertUrlAllowed('http://255.255.255.255/', {
+ allowPrivateNetwork: true,
+ }),
+ ).rejects.toThrow();
+ });
+
+ it('blocks loopback literal IPs', async () => {
+ await expect(assertUrlAllowed('https://127.0.0.1/claim')).rejects.toThrow();
+ });
+
+ it('blocks private literal IPs', async () => {
+ await expect(assertUrlAllowed('https://10.0.0.5/claim')).rejects.toThrow();
+ await expect(
+ assertUrlAllowed('https://192.168.1.1/claim'),
+ ).rejects.toThrow();
+ });
+
+ it('allows private literal IPs when private networks are allowed', async () => {
+ await expect(
+ assertUrlAllowed('https://192.168.1.50/accounts', {
+ allowPrivateNetwork: true,
+ }),
+ ).resolves.toBeUndefined();
+ await expect(
+ assertUrlAllowed('https://10.0.0.5/accounts', {
+ allowPrivateNetwork: true,
+ }),
+ ).resolves.toBeUndefined();
+ });
+
+ it('allows loopback when private networks are allowed', async () => {
+ await expect(
+ assertUrlAllowed('https://127.0.0.1/accounts', {
+ allowPrivateNetwork: true,
+ }),
+ ).resolves.toBeUndefined();
+ });
+
+ it('allows a hostname resolving to a private IP when private networks are allowed', async () => {
+ mockDnsLookup(['10.1.2.3']);
+ await expect(
+ assertUrlAllowed('https://my-simplefin.local/accounts', {
+ allowPrivateNetwork: true,
+ }),
+ ).resolves.toBeUndefined();
+ });
+
+ it('blocks IPv6 loopback', async () => {
+ await expect(assertUrlAllowed('https://[::1]/claim')).rejects.toThrow();
+ });
+
+ it('blocks IPv4-mapped IPv6 loopback', async () => {
+ await expect(
+ assertUrlAllowed('https://[::ffff:127.0.0.1]/claim'),
+ ).rejects.toThrow();
+ });
+
+ it('blocks a hostname that resolves to a private IP', async () => {
+ mockDnsLookup(['10.1.2.3']);
+ await expect(
+ assertUrlAllowed('https://internal.example.com/'),
+ ).rejects.toThrow(/resolving to private\/local IP/);
+ });
+
+ it('blocks if any resolved address is private', async () => {
+ mockDnsLookup(['8.8.8.8', '127.0.0.1']);
+ await expect(
+ assertUrlAllowed('https://rebind.example.com/'),
+ ).rejects.toThrow();
+ });
+
+ it('rejects unresolvable hostnames', async () => {
+ mockDnsFailure();
+ await expect(
+ assertUrlAllowed('https://does-not-exist.example/'),
+ ).rejects.toThrow(/Unable to resolve/);
+ });
+
+ it('rejects non-http(s) protocols', async () => {
+ await expect(assertUrlAllowed('file:///etc/passwd')).rejects.toThrow(
+ /disallowed protocol/,
+ );
+ });
+
+ it('rejects invalid URLs', async () => {
+ await expect(assertUrlAllowed('not a url')).rejects.toThrow(/Invalid URL/);
+ });
+});
diff --git a/packages/sync-server/src/util/ssrf.ts b/packages/sync-server/src/util/ssrf.ts
new file mode 100644
index 0000000000..1f02fd3679
--- /dev/null
+++ b/packages/sync-server/src/util/ssrf.ts
@@ -0,0 +1,118 @@
+import dns from 'dns';
+import { promisify } from 'util';
+
+import ipaddr from 'ipaddr.js';
+
+const dnsLookup = promisify(dns.lookup);
+
+// IP ranges (as classified by ipaddr.js) that are never a legitimate
+// destination and are the highest-risk SSRF targets, so they are blocked
+// unconditionally. linkLocal covers the cloud metadata endpoint
+// (169.254.169.254) — the credential-theft vector this protection primarily
+// guards against — and no real service is hosted on the reserved, broadcast or
+// unspecified ranges.
+const ALWAYS_BLOCKED_IP_RANGES = [
+ 'linkLocal',
+ 'unspecified',
+ 'reserved',
+ 'broadcast',
+];
+
+// Private-network ranges (LAN, loopback, IPv6 unique-local). These are blocked
+// by default, but self-hosters legitimately run services such as their own
+// SimpleFIN bridge on them, so callers that expect to reach private
+// infrastructure can opt in with { allowPrivateNetwork: true }. Trusting the
+// local network by default keeps self-hosting working out of the box; the
+// always-blocked ranges above still close the worst-case (metadata) attack.
+const PRIVATE_IP_RANGES = ['private', 'loopback', 'uniqueLocal'];
+
+type SsrfOptions = {
+ // Allow requests to private/loopback/unique-local addresses. Defaults to
+ // false (strict). Set by callers like the SimpleFIN integration whose
+ // upstream may be a self-hosted server on the local network.
+ allowPrivateNetwork?: boolean;
+};
+
+/**
+ * Return true if the given address is a literal IP in one of the blocked
+ * ranges (link-local/reserved/etc, plus private ranges unless
+ * allowPrivateNetwork is set). Non-IP strings (e.g. hostnames) return false,
+ * so callers can pass a URL hostname directly.
+ */
+export function isBlockedIp(
+ address: string,
+ { allowPrivateNetwork = false }: SsrfOptions = {},
+): boolean {
+ if (!ipaddr.isValid(address)) {
+ return false;
+ }
+
+ // process() normalizes IPv4-mapped IPv6 addresses (e.g. ::ffff:127.0.0.1)
+ // back to their IPv4 form so their range is classified correctly.
+ const range = ipaddr.process(address).range();
+
+ if (ALWAYS_BLOCKED_IP_RANGES.includes(range)) {
+ return true;
+ }
+
+ return !allowPrivateNetwork && PRIVATE_IP_RANGES.includes(range);
+}
+
+/**
+ * Validate that a URL is safe to make a server-side request to, guarding
+ * against SSRF. Only http(s) URLs are permitted, and the hostname is resolved
+ * via DNS so that hostnames pointing at private/local/link-local addresses are
+ * rejected as well as literal IPs. Throws if the URL is not allowed.
+ *
+ * Pass { allowPrivateNetwork: true } for callers (e.g. SimpleFIN) whose
+ * upstream may legitimately be a self-hosted server on the local network; the
+ * always-blocked ranges (cloud metadata, reserved, broadcast) remain blocked
+ * regardless.
+ */
+export async function assertUrlAllowed(
+ targetUrl: string,
+ options: SsrfOptions = {},
+): Promise<void> {
+ let url: URL;
+ try {
+ url = new URL(targetUrl);
+ } catch {
+ throw new Error('Invalid URL');
+ }
+
+ if (url.protocol !== 'https:' && url.protocol !== 'http:') {
+ throw new Error(`Blocked request to disallowed protocol: ${url.protocol}`);
+ }
+
+ // URL keeps the surrounding brackets on IPv6 hosts (e.g. "[::1]"); strip
+ // them so the address can be parsed and resolved.
+ const hostname = url.hostname.replace(/^\[|\]$/g, '');
+
+ // Literal IP address: check it directly without a DNS lookup.
+ if (ipaddr.isValid(hostname)) {
+ if (isBlockedIp(hostname, options)) {
+ throw new Error(`Blocked request to private/local IP: ${hostname}`);
+ }
+ return;
+ }
+
+ // Hostname: resolve every address it points to and reject if any is blocked.
+ let addresses: { address: string }[];
+ try {
+ addresses = await dnsLookup(hostname, { all: true });
+ } catch {
+ throw new Error(`Unable to resolve host: ${hostname}`);
+ }
+
+ if (addresses.length === 0) {
+ throw new Error(`Unable to resolve host: ${hostname}`);
+ }
+
+ for (const { address } of addresses) {
+ if (isBlockedIp(address, options)) {
+ throw new Error(
+ `Blocked request to host resolving to private/local IP: ${hostname} (${address})`,
+ );
+ }
+ }
+}
diff --git a/upcoming-release-notes/8012.md b/upcoming-release-notes/8012.md
new file mode 100644
index 0000000000..d81e6c8403
--- /dev/null
+++ b/upcoming-release-notes/8012.md
@@ -0,0 +1,6 @@
+---
+category: Bugfix
+authors: [MatissJanis]
+---
+
+Add SSRF protection to the SimpleFIN bank sync integration.