Skip to content

DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.

fix(remote): stop trusting Cloudflare tunnel traffic on the access port as loopback (#1158)

Zuyang Liu4df5a52c5ef6
diff --git a/packages/dsh-tauri-remote/src/host/server/index.test.ts b/packages/dsh-tauri-remote/src/host/server/index.test.ts
index 82d18199..fecc14bd 100644
--- a/packages/dsh-tauri-remote/src/host/server/index.test.ts
+++ b/packages/dsh-tauri-remote/src/host/server/index.test.ts
@@ -277,6 +277,8 @@ describe('management request boundary', () => {
{ [GATEWAY_SOURCE_HEADER]: 'loopback, loopback', [GATEWAY_SESSION_HEADER]: session },
{ [GATEWAY_SOURCE_HEADER]: 'unknown', [GATEWAY_SESSION_HEADER]: session },
{ [GATEWAY_SOURCE_HEADER]: 'public', [GATEWAY_SESSION_HEADER]: 'outbound' },
+ { 'cf-ray': 'a4d155e90a5f78dd-LAX' },
+ { 'cdn-loop': 'cloudflare; loops=1; subreqs=1' },
]
for (const headers of sources) {
for (const path of PATHS.filter(path => path !== `${BASE}/session/role`)) {
diff --git a/packages/dsh-tauri-remote/src/host/service/gateway.test.ts b/packages/dsh-tauri-remote/src/host/service/gateway.test.ts
index 47459206..a2959d1c 100644
--- a/packages/dsh-tauri-remote/src/host/service/gateway.test.ts
+++ b/packages/dsh-tauri-remote/src/host/service/gateway.test.ts
@@ -21,6 +21,13 @@ const SESSION = ensureSourceSession()
const MIN_BYTES = 1024
+const CLOUDFLARE_RELAYED: IncomingHttpHeaders = {
+ 'cf-ray': 'a4d155e90a5f78dd-LAX',
+ 'cdn-loop': 'cloudflare; loops=1; subreqs=1',
+ 'cf-connecting-ip': '203.0.113.7',
+ 'x-forwarded-for': '6.6.6.6,203.0.113.7',
+}
+
interface Coded {
status: number
headers: IncomingHttpHeaders
@@ -1024,6 +1031,29 @@ describe('gateway 来源门禁判定矩阵(真实 HTTP 管线)', () => {
}
}
+ for (const mode of ['unconfigured', 'public_only', 'all'] as const) {
+ const expected = mode === 'unconfigured' ? EXPECTED.tunnel.unconfigured : mode === 'public_only' ? EXPECTED.tunnel.publicOnly : EXPECTED.tunnel.all
+ it(`【矩阵】同机 cloudflared 从回环对端转入的请求 × ${mode} 与 tunnel 一致,是 ${expected}`, async () => {
+ const auth = policyFor(mode)
+ const status = await gateway.start({
+ id: 'entry',
+ kind: 'inbound',
+ upstream: upstream.origin,
+ port: 0,
+ tokenProvider: upstream.mintUrlFor,
+ ...auth === undefined ? {} : { auth },
+ })
+ const reply = await call(status.port, '/api/ping', { headers: CLOUDFLARE_RELAYED })
+ expect(reply.status).toBe(expected)
+ })
+ }
+
+ it('同机 cloudflared 转入的 WebSocket 握手同样要先认证,不继承回环放行', async () => {
+ const status = await startEntry('inbound', upstream, { tokenProvider: upstream.mintUrlFor, auth: () => policyOf({ linkToken: 'link-token' }) })
+ await expect(upgraded(status.port, '/api/remote.mux', CLOUDFLARE_RELAYED)).rejects.toThrow('401')
+ expect(upstream.upgrades).toHaveLength(0)
+ })
+
it('把物理回环来源之外的私网来源按真实 TCP 对端地址判定', async () => {
const external = externalAddress()
if (external === undefined)
@@ -1789,6 +1819,14 @@ describe('gateway 内部来源标识', () => {
expect(upstream.calls.at(-1)?.headers[GATEWAY_SESSION_HEADER]).toBe(SESSION)
})
+ it('入站入口把同机 cloudflared 转入且已认证的请求声明为 tunnel,上游管理接口不会当成回环', async () => {
+ const status = await startEntry('inbound', upstream, { tokenProvider: upstream.mintUrlFor, auth: () => policyOf({ linkToken: 'link-token' }) })
+ const session = signSession('session-secret', Date.now()).value
+ const forwarded = await call(status.port, '/api/ping', { headers: { ...CLOUDFLARE_RELAYED, cookie: `dsh_remote_session=${session}` } })
+ expect(forwarded.status).toBe(200)
+ expect(upstream.calls.at(-1)?.headers[GATEWAY_SOURCE_HEADER]).toBe('tunnel')
+ })
+
it('注入前先剥离客户端自带的标识头,绝不追加成多值头', async () => {
const status = await gateway.start({ id: 'tunnel', kind: 'tunnel', upstream: upstream.origin, port: 0, tokenProvider: upstream.mintUrlFor, auth: () => policyOf({ linkToken: 'link-token' }) })
const session = signSession('session-secret', Date.now()).value
@@ -1872,6 +1910,32 @@ describe('gateway 限速分桶', () => {
expect(other.status).toBe(401)
})
+ it('入站入口给同机 cloudflared 转入的请求按边缘声明的客户端 IP 分桶,封禁不波及其它访客与本机回环', async () => {
+ const status = await startEntry('inbound', upstream, { auth: () => policyOf({ linkToken: 'link-token' }) })
+ const attempt = async (clientIp: string) => await call(status.port, '/', {
+ method: 'POST',
+ headers: { ...CLOUDFLARE_RELAYED, 'cf-connecting-ip': clientIp, 'content-type': 'application/x-www-form-urlencoded', ...navigation() },
+ body: 'code=wrong',
+ })
+ for (let index = 0; index < 5; index++)
+ await attempt('203.0.113.7')
+ expect((await attempt('203.0.113.7')).status).toBe(429)
+ expect((await attempt('198.51.100.9')).status).toBe(401)
+ expect((await call(status.port, '/?auth=v1.invalid', { headers: navigation() })).status).toBe(401)
+ })
+
+ it('缺少 cf-connecting-ip 时不按访客自填的 x-forwarded-for 首跳分桶,轮换首跳也绕不过封禁', async () => {
+ const status = await startEntry('inbound', upstream, { auth: () => policyOf({ linkToken: 'link-token' }) })
+ const attempt = async (hop: number) => await call(status.port, '/', {
+ method: 'POST',
+ headers: { 'cf-ray': 'a4d155e90a5f78dd-LAX', 'x-forwarded-for': `198.51.100.${hop}, 203.0.113.7`, 'content-type': 'application/x-www-form-urlencoded', ...navigation() },
+ body: 'code=wrong',
+ })
+ for (let hop = 0; hop < 5; hop++)
+ await attempt(hop)
+ expect((await attempt(5)).status).toBe(429)
+ })
+
it('非隧道来源忽略可伪造的转发头,只按 TCP 对端分桶', async () => {
const status = await startEntry('inbound', upstream, { auth: () => policyOf({ linkToken: 'link-token' }) })
const attempt = async (clientIp: string) => await call(status.port, '/', {
diff --git a/packages/dsh-tauri-remote/src/host/service/gateway.ts b/packages/dsh-tauri-remote/src/host/service/gateway.ts
index 41ee33fb..1aeddd8d 100644
--- a/packages/dsh-tauri-remote/src/host/service/gateway.ts
+++ b/packages/dsh-tauri-remote/src/host/service/gateway.ts
@@ -348,7 +348,7 @@ function sourceOf(entry: GatewayEntry, request: IncomingMessage, session: string
async function admitAuthenticated(entry: GatewayEntry, request: IncomingMessage, response: ServerResponse, source: RemoteSourceClass, policy: RemoteAuthPolicy): Promise<boolean> {
const now = Date.now()
- const bucket = rateLimitKeyOf(source, request.socket.remoteAddress, entry.kind === 'tunnel' ? tunnelClientIpOf(request.headers) : undefined)
+ const bucket = rateLimitKeyOf(source, request.socket.remoteAddress, tunnelClientIpOf(request.headers))
const url = new URL(request.url ?? '/', 'http://gateway.invalid')
const provided = request.method === 'GET' && url.pathname === '/' ? url.searchParams.get(AUTH_QUERY) ?? undefined : undefined
const pairing = url.pathname === '/' && url.searchParams.get('pair') === '1'
diff --git a/packages/dsh-tauri-remote/src/host/service/gateway.utils.test.ts b/packages/dsh-tauri-remote/src/host/service/gateway.utils.test.ts
index 29f01ccc..e5254004 100644
--- a/packages/dsh-tauri-remote/src/host/service/gateway.utils.test.ts
+++ b/packages/dsh-tauri-remote/src/host/service/gateway.utils.test.ts
@@ -359,10 +359,14 @@ describe('cookie helpers', () => {
})
describe('tunnelClientIpOf', () => {
- it('prefers the Cloudflare client address and falls back to the first forwarded hop', () => {
+ it('takes the client address set by the Cloudflare edge', () => {
expect(tunnelClientIpOf({ 'cf-connecting-ip': '203.0.113.7', 'x-forwarded-for': '198.51.100.1' })).toBe('203.0.113.7')
- expect(tunnelClientIpOf({ 'x-forwarded-for': '203.0.113.7, 10.0.0.1' })).toBe('203.0.113.7')
- expect(tunnelClientIpOf({ 'x-forwarded-for': '2001:db8::7' })).toBe('2001:db8::7')
+ expect(tunnelClientIpOf({ 'cf-connecting-ip': '2001:db8::7' })).toBe('2001:db8::7')
+ })
+
+ it('never falls back to x-forwarded-for, whose first hop the visitor writes', () => {
+ expect(tunnelClientIpOf({ 'x-forwarded-for': '6.6.6.6, 203.0.113.7' })).toBeUndefined()
+ expect(tunnelClientIpOf({ 'x-forwarded-for': '2001:db8::7' })).toBeUndefined()
})
it('reports nothing for a missing or malformed declaration', () => {
diff --git a/packages/dsh-tauri-remote/src/host/service/gateway.utils.ts b/packages/dsh-tauri-remote/src/host/service/gateway.utils.ts
index 32a43a1c..fc9d2b90 100644
--- a/packages/dsh-tauri-remote/src/host/service/gateway.utils.ts
+++ b/packages/dsh-tauri-remote/src/host/service/gateway.utils.ts
@@ -271,15 +271,11 @@ export function parseFormField(body: string, name: string): string | undefined {
return value === null || value === '' ? undefined : value
}
-/** 隧道侧声明的客户端 IP:只用于限速分桶,绝不参与放行判定(S2 §7.1)。 */
+/** 隧道侧声明的客户端 IP:只用于限速分桶,绝不参与放行判定(S2 §7.1)。只认边缘改写的 `cf-connecting-ip`:`x-forwarded-for` 首跳由访客自填,轮换即可绕过封禁。 */
export function tunnelClientIpOf(headers: IncomingHttpHeaders): string | undefined {
const direct = headers['cf-connecting-ip']
const declared = typeof direct === 'string' ? direct.trim() : undefined
- if (isIpAddress(declared))
- return declared
- const forwarded = headers['x-forwarded-for']
- const first = (typeof forwarded === 'string' ? forwarded : '').split(',')[0]?.trim()
- return isIpAddress(first) ? first : undefined
+ return isIpAddress(declared) ? declared : undefined
}
export function loginPageHtml(message?: string): string {
diff --git a/packages/dsh-tauri-remote/src/host/utils/source.test.ts b/packages/dsh-tauri-remote/src/host/utils/source.test.ts
index 17ab2456..9a5e75fe 100644
--- a/packages/dsh-tauri-remote/src/host/utils/source.test.ts
+++ b/packages/dsh-tauri-remote/src/host/utils/source.test.ts
@@ -93,6 +93,14 @@ describe('classifySource', () => {
expect(classifySource(headers(), '8.8.8.8', SESSION)).toBe('public')
})
+ it.each<IncomingHttpHeaders>([
+ { 'cf-ray': 'a4d155e90a5f78dd-LAX' },
+ { 'cdn-loop': 'cloudflare; loops=1; subreqs=1' },
+ ])('classifies the edge-relayed request %j as tunnel instead of trusting the connector peer', (relayed) => {
+ expect(classifySource(relayed, '127.0.0.1', SESSION)).toBe('tunnel')
+ expect(classifySource(relayed, '10.1.2.3', SESSION)).toBe('tunnel')
+ })
+
it('adopts the declared classification of a forwarded request whose session matches', () => {
expect(classifySource(headers('loopback', SESSION), '10.1.2.3', SESSION)).toBe('loopback')
expect(classifySource(headers('private', SESSION), '127.0.0.1', SESSION)).toBe('private')
@@ -229,6 +237,10 @@ describe('rateLimitKeyOf', () => {
expect(rateLimitKeyOf('tunnel', '127.0.0.1', '2001:db8::7')).toBe('2001:db8::7')
})
+ it('ignores the declared address of a tunnel source that did not arrive through a local connector', () => {
+ expect(rateLimitKeyOf('tunnel', '192.168.1.20', '203.0.113.7')).toBe('192.168.1.20')
+ })
+
it('ignores the declared address for every other source', () => {
expect(rateLimitKeyOf('private', '192.168.1.5', '203.0.113.7')).toBe('192.168.1.5')
expect(rateLimitKeyOf('public', '198.51.100.9', '203.0.113.7')).toBe('198.51.100.9')
diff --git a/packages/dsh-tauri-remote/src/host/utils/source.ts b/packages/dsh-tauri-remote/src/host/utils/source.ts
index d729d0c7..227bacdf 100644
--- a/packages/dsh-tauri-remote/src/host/utils/source.ts
+++ b/packages/dsh-tauri-remote/src/host/utils/source.ts
@@ -21,15 +21,16 @@ export function isLoopbackPeer(address: string | undefined): boolean {
}
/**
- * 来源分类判定:两枚内部标识头都不存在时回退 TCP 对端地址;任一枚存在则必须两枚同时有效
- * (单值 + 会话标识匹配 + 取值合法)才采用其声明,否则一律按不可信处理——网关转发到本机 DSH
- * 时对端恒为回环,回退会把伪造头变成回环权限。转发头(X-Forwarded-For 等)不参与判定。
+ * 来源分类判定:两枚内部标识头都不存在时回退 TCP 对端地址,但带 CDN 边缘标记(`cf-ray` /
+ * `cdn-loop`)的请求恒为 tunnel——同机 cloudflared 转入时对端恒为回环,回退会让公网访客拿到回环权限;
+ * 任一枚存在则必须两枚同时有效(单值 + 会话标识匹配 + 取值合法)才采用其声明,否则一律按不可信处理——
+ * 网关转发到本机 DSH 时对端恒为回环,回退会把伪造头变成回环权限。转发头(X-Forwarded-For 等)不参与判定。
*/
export function classifySource(headers: IncomingHttpHeaders, peerAddress: string | undefined, session: string): RemoteSourceClass {
const declared = headers[GATEWAY_SOURCE_HEADER]
const token = headers[GATEWAY_SESSION_HEADER]
if (declared === undefined && token === undefined)
- return classifyPeer(peerAddress)
+ return isEdgeRelayed(headers) ? 'tunnel' : classifyPeer(peerAddress)
if (typeof declared !== 'string' || typeof token !== 'string')
return 'public'
if (session === '' || !sessionMatches(token, session))
@@ -56,9 +57,9 @@ export function decideSourceAccess(source: RemoteSourceClass, policy: RemoteAuth
return 'authenticate'
}
-/** 限速分桶键:仅隧道来源(内部标识可信)允许采用隧道侧声明的客户端 IP,且只影响分桶(S2 §7.1/§7.4)。 */
+/** 限速分桶键:仅经同机连接器(回环对端)转入的隧道来源允许采用隧道侧声明的客户端 IP,且只影响分桶(S2 §7.1/§7.4);私网对端能自报边缘头,不得借此换桶。 */
export function rateLimitKeyOf(source: RemoteSourceClass, peerAddress: string | undefined, declaredClientIp: string | undefined): string {
- if (source === 'tunnel' && isIpAddress(declaredClientIp))
+ if (source === 'tunnel' && isLoopbackPeer(peerAddress) && isIpAddress(declaredClientIp))
return declaredClientIp
return peerAddress === undefined || peerAddress === '' ? 'unknown' : peerAddress
}
@@ -115,6 +116,10 @@ function octetOf(value: string | undefined): number | undefined {
return parsed <= 255 ? parsed : undefined
}
+function isEdgeRelayed(headers: IncomingHttpHeaders): boolean {
+ return headers['cf-ray'] !== undefined || headers['cdn-loop'] !== undefined
+}
+
function isSourceClass(value: string): value is RemoteSourceClass {
return (SOURCE_CLASSES as readonly string[]).includes(value)
}