Skip to content

Commit 81c68f5

Browse files
committed
fix: guard remote media fetches with SSRF checks
1 parent d842b28 commit 81c68f5

11 files changed

Lines changed: 423 additions & 242 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ Docs: https://docs.openclaw.ai
2222

2323
### Fixes
2424

25+
- Security: guard remote media fetches with SSRF protections (block private/localhost, DNS pinning).
2526
- Plugins: validate plugin/hook install paths and reject traversal-like names.
2627
- Telegram: add download timeouts for file fetches. (#6914) Thanks @hclsys.
2728
- Telegram: enforce thread specs for DM vs forum sends. (#6833) Thanks @obviyus.

‎src/agents/tools/web-fetch.ts‎

Lines changed: 14 additions & 86 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,8 @@
1-
import type { Dispatcher } from "undici";
21
import { Type } from "@sinclair/typebox";
32
import type { OpenClawConfig } from "../../config/config.js";
43
import type { AnyAgentTool } from "./common.js";
5-
import {
6-
closeDispatcher,
7-
createPinnedDispatcher,
8-
resolvePinnedHostname,
9-
SsrFBlockedError,
10-
} from "../../infra/net/ssrf.js";
4+
import { fetchWithSsrFGuard } from "../../infra/net/fetch-guard.js";
5+
import { SsrFBlockedError } from "../../infra/net/ssrf.js";
116
import { wrapExternalContent, wrapWebContent } from "../../security/external-content.js";
127
import { stringEnum } from "../schema/typebox.js";
138
import { jsonResult, readNumberParam, readStringParam } from "./common.js";
@@ -184,79 +179,6 @@ function looksLikeHtml(value: string): boolean {
184179
return head.startsWith("<!doctype html") || head.startsWith("<html");
185180
}
186181

187-
function isRedirectStatus(status: number): boolean {
188-
return status === 301 || status === 302 || status === 303 || status === 307 || status === 308;
189-
}
190-
191-
async function fetchWithRedirects(params: {
192-
url: string;
193-
maxRedirects: number;
194-
timeoutSeconds: number;
195-
userAgent: string;
196-
}): Promise<{ response: Response; finalUrl: string; dispatcher: Dispatcher }> {
197-
const signal = withTimeout(undefined, params.timeoutSeconds * 1000);
198-
const visited = new Set<string>();
199-
let currentUrl = params.url;
200-
let redirectCount = 0;
201-
202-
while (true) {
203-
let parsedUrl: URL;
204-
try {
205-
parsedUrl = new URL(currentUrl);
206-
} catch {
207-
throw new Error("Invalid URL: must be http or https");
208-
}
209-
if (!["http:", "https:"].includes(parsedUrl.protocol)) {
210-
throw new Error("Invalid URL: must be http or https");
211-
}
212-
213-
const pinned = await resolvePinnedHostname(parsedUrl.hostname);
214-
const dispatcher = createPinnedDispatcher(pinned);
215-
let res: Response;
216-
try {
217-
res = await fetch(parsedUrl.toString(), {
218-
method: "GET",
219-
headers: {
220-
Accept: "*/*",
221-
"User-Agent": params.userAgent,
222-
"Accept-Language": "en-US,en;q=0.9",
223-
},
224-
signal,
225-
redirect: "manual",
226-
dispatcher,
227-
} as RequestInit);
228-
} catch (err) {
229-
await closeDispatcher(dispatcher);
230-
throw err;
231-
}
232-
233-
if (isRedirectStatus(res.status)) {
234-
const location = res.headers.get("location");
235-
if (!location) {
236-
await closeDispatcher(dispatcher);
237-
throw new Error(`Redirect missing location header (${res.status})`);
238-
}
239-
redirectCount += 1;
240-
if (redirectCount > params.maxRedirects) {
241-
await closeDispatcher(dispatcher);
242-
throw new Error(`Too many redirects (limit: ${params.maxRedirects})`);
243-
}
244-
const nextUrl = new URL(location, parsedUrl).toString();
245-
if (visited.has(nextUrl)) {
246-
await closeDispatcher(dispatcher);
247-
throw new Error("Redirect loop detected");
248-
}
249-
visited.add(nextUrl);
250-
void res.body?.cancel();
251-
await closeDispatcher(dispatcher);
252-
currentUrl = nextUrl;
253-
continue;
254-
}
255-
256-
return { response: res, finalUrl: currentUrl, dispatcher };
257-
}
258-
}
259-
260182
function formatWebFetchErrorDetail(params: {
261183
detail: string;
262184
contentType?: string | null;
@@ -465,18 +387,22 @@ async function runWebFetch(params: {
465387

466388
const start = Date.now();
467389
let res: Response;
468-
let dispatcher: Dispatcher | null = null;
390+
let release: (() => Promise<void>) | null = null;
469391
let finalUrl = params.url;
470392
try {
471-
const result = await fetchWithRedirects({
393+
const result = await fetchWithSsrFGuard({
472394
url: params.url,
473395
maxRedirects: params.maxRedirects,
474-
timeoutSeconds: params.timeoutSeconds,
475-
userAgent: params.userAgent,
396+
timeoutMs: params.timeoutSeconds * 1000,
397+
headers: {
398+
Accept: "*/*",
399+
"User-Agent": params.userAgent,
400+
"Accept-Language": "en-US,en;q=0.9",
401+
},
476402
});
477403
res = result.response;
478404
finalUrl = result.finalUrl;
479-
dispatcher = result.dispatcher;
405+
release = result.release;
480406
} catch (error) {
481407
if (error instanceof SsrFBlockedError) {
482408
throw error;
@@ -630,7 +556,9 @@ async function runWebFetch(params: {
630556
writeCache(FETCH_CACHE, cacheKey, payload, params.cacheTtlMs);
631557
return payload;
632558
} finally {
633-
await closeDispatcher(dispatcher);
559+
if (release) {
560+
await release();
561+
}
634562
}
635563
}
636564

‎src/infra/net/fetch-guard.ts‎

Lines changed: 170 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,170 @@
1+
import type { Dispatcher } from "undici";
2+
import {
3+
closeDispatcher,
4+
createPinnedDispatcher,
5+
resolvePinnedHostname,
6+
resolvePinnedHostnameWithPolicy,
7+
type LookupFn,
8+
type SsrFPolicy,
9+
} from "./ssrf.js";
10+
11+
type FetchLike = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
12+
13+
export type GuardedFetchOptions = {
14+
url: string;
15+
fetchImpl?: FetchLike;
16+
method?: string;
17+
headers?: HeadersInit;
18+
maxRedirects?: number;
19+
timeoutMs?: number;
20+
signal?: AbortSignal;
21+
policy?: SsrFPolicy;
22+
lookupFn?: LookupFn;
23+
};
24+
25+
export type GuardedFetchResult = {
26+
response: Response;
27+
finalUrl: string;
28+
release: () => Promise<void>;
29+
};
30+
31+
const DEFAULT_MAX_REDIRECTS = 3;
32+
33+
function isRedirectStatus(status: number): boolean {
34+
return status === 301 || status === 302 || status === 303 || status === 307 || status === 308;
35+
}
36+
37+
function buildAbortSignal(params: { timeoutMs?: number; signal?: AbortSignal }): {
38+
signal?: AbortSignal;
39+
cleanup: () => void;
40+
} {
41+
const { timeoutMs, signal } = params;
42+
if (!timeoutMs && !signal) {
43+
return { signal: undefined, cleanup: () => {} };
44+
}
45+
46+
if (!timeoutMs) {
47+
return { signal, cleanup: () => {} };
48+
}
49+
50+
const controller = new AbortController();
51+
const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
52+
const onAbort = () => controller.abort();
53+
if (signal) {
54+
if (signal.aborted) {
55+
controller.abort();
56+
} else {
57+
signal.addEventListener("abort", onAbort, { once: true });
58+
}
59+
}
60+
61+
const cleanup = () => {
62+
clearTimeout(timeoutId);
63+
if (signal) {
64+
signal.removeEventListener("abort", onAbort);
65+
}
66+
};
67+
68+
return { signal: controller.signal, cleanup };
69+
}
70+
71+
export async function fetchWithSsrFGuard(params: GuardedFetchOptions): Promise<GuardedFetchResult> {
72+
const fetcher: FetchLike | undefined = params.fetchImpl ?? globalThis.fetch;
73+
if (!fetcher) {
74+
throw new Error("fetch is not available");
75+
}
76+
77+
const maxRedirects =
78+
typeof params.maxRedirects === "number" && Number.isFinite(params.maxRedirects)
79+
? Math.max(0, Math.floor(params.maxRedirects))
80+
: DEFAULT_MAX_REDIRECTS;
81+
82+
const { signal, cleanup } = buildAbortSignal({
83+
timeoutMs: params.timeoutMs,
84+
signal: params.signal,
85+
});
86+
87+
let released = false;
88+
const release = async (dispatcher?: Dispatcher | null) => {
89+
if (released) {
90+
return;
91+
}
92+
released = true;
93+
cleanup();
94+
await closeDispatcher(dispatcher ?? undefined);
95+
};
96+
97+
const visited = new Set<string>();
98+
let currentUrl = params.url;
99+
let redirectCount = 0;
100+
101+
while (true) {
102+
let parsedUrl: URL;
103+
try {
104+
parsedUrl = new URL(currentUrl);
105+
} catch {
106+
await release();
107+
throw new Error("Invalid URL: must be http or https");
108+
}
109+
if (!["http:", "https:"].includes(parsedUrl.protocol)) {
110+
await release();
111+
throw new Error("Invalid URL: must be http or https");
112+
}
113+
114+
let dispatcher: Dispatcher | null = null;
115+
try {
116+
const usePolicy = Boolean(
117+
params.policy?.allowPrivateNetwork || params.policy?.allowedHostnames?.length,
118+
);
119+
const pinned = usePolicy
120+
? await resolvePinnedHostnameWithPolicy(parsedUrl.hostname, {
121+
lookupFn: params.lookupFn,
122+
policy: params.policy,
123+
})
124+
: await resolvePinnedHostname(parsedUrl.hostname, params.lookupFn);
125+
dispatcher = createPinnedDispatcher(pinned);
126+
127+
const init: RequestInit & { dispatcher?: Dispatcher } = {
128+
redirect: "manual",
129+
dispatcher,
130+
...(params.method ? { method: params.method } : {}),
131+
...(params.headers ? { headers: params.headers } : {}),
132+
...(signal ? { signal } : {}),
133+
};
134+
135+
const response = await fetcher(parsedUrl.toString(), init);
136+
137+
if (isRedirectStatus(response.status)) {
138+
const location = response.headers.get("location");
139+
if (!location) {
140+
await release(dispatcher);
141+
throw new Error(`Redirect missing location header (${response.status})`);
142+
}
143+
redirectCount += 1;
144+
if (redirectCount > maxRedirects) {
145+
await release(dispatcher);
146+
throw new Error(`Too many redirects (limit: ${maxRedirects})`);
147+
}
148+
const nextUrl = new URL(location, parsedUrl).toString();
149+
if (visited.has(nextUrl)) {
150+
await release(dispatcher);
151+
throw new Error("Redirect loop detected");
152+
}
153+
visited.add(nextUrl);
154+
void response.body?.cancel();
155+
await closeDispatcher(dispatcher);
156+
currentUrl = nextUrl;
157+
continue;
158+
}
159+
160+
return {
161+
response,
162+
finalUrl: currentUrl,
163+
release: async () => release(dispatcher),
164+
};
165+
} catch (err) {
166+
await release(dispatcher);
167+
throw err;
168+
}
169+
}
170+
}

0 commit comments

Comments
 (0)