Skip to content

Commit e4c6ee8

Browse files
lsr911claudesteipete
authored
fix(agents): prevent ReDoS in MCP glob-to-regex wildcard matching (#100330)
* fix(agents): prevent ReDoS in MCP glob-to-regex wildcard matching Collapse consecutive '*' wildcards into a single '*' before building the regex in globMatches(). Without this, a glob like '**********-x' tested against a non-matching string causes catastrophic backtracking (238s for a single call with 10 stars vs 0.4ms after fix). Affected functions: - src/agents/agent-bundle-mcp-runtime.ts: globMatches (MCP tool name filter) - src/agents/agent-bundle-mcp-materialize.ts: globMatches (MCP operation filter) Co-Authored-By: Claude <[email protected]> * fix(agents): make MCP filter matching linear * style(mcp): satisfy filter lint --------- Co-authored-by: Claude <[email protected]> Co-authored-by: Peter Steinberger <[email protected]>
1 parent 92af54b commit e4c6ee8

5 files changed

Lines changed: 111 additions & 34 deletions
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import { describe, expect, it } from "vitest";
2+
import { matchesMcpToolFilterPattern } from "./agent-bundle-mcp-filter.js";
3+
4+
describe("matchesMcpToolFilterPattern", () => {
5+
it.each([
6+
["", "tool", false],
7+
["search_docs", "search_docs", true],
8+
["search_docs", "read_docs", false],
9+
["*_docs", "search_docs", true],
10+
["resources_*", "resources_read", true],
11+
["a**b***c", "axbyc", true],
12+
["a*b*c", "acb", false],
13+
])("matches %j against %j", (pattern, value, expected) => {
14+
expect(matchesMcpToolFilterPattern(pattern, value)).toBe(expected);
15+
});
16+
17+
it("rejects adversarial separated wildcards without regex backtracking", () => {
18+
const pattern = `${"*a".repeat(128)}*b`;
19+
const value = `${"a".repeat(10_000)}c`;
20+
expect(matchesMcpToolFilterPattern(pattern, value)).toBe(false);
21+
});
22+
});
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/** Match the documented MCP tool-filter glob syntax: exact text plus `*`. */
2+
export function matchesMcpToolFilterPattern(pattern: string, value: string): boolean {
3+
const trimmed = pattern.trim();
4+
if (!trimmed) {
5+
return false;
6+
}
7+
if (!trimmed.includes("*")) {
8+
return trimmed === value;
9+
}
10+
11+
const parts = trimmed.split("*");
12+
const first = parts[0] ?? "";
13+
const last = parts.at(-1) ?? "";
14+
let cursor = 0;
15+
if (first) {
16+
if (!value.startsWith(first)) {
17+
return false;
18+
}
19+
cursor = first.length;
20+
}
21+
const endBound = last ? value.length - last.length : value.length;
22+
if (last && (!value.endsWith(last) || endBound < cursor)) {
23+
return false;
24+
}
25+
26+
for (const part of parts.slice(1, -1)) {
27+
if (!part) {
28+
continue;
29+
}
30+
const index = value.indexOf(part, cursor);
31+
if (index === -1 || index + part.length > endBound) {
32+
return false;
33+
}
34+
cursor = index + part.length;
35+
}
36+
return true;
37+
}

‎src/agents/agent-bundle-mcp-materialize.ts‎

Lines changed: 6 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { normalizeLowercaseStringOrEmpty } from "@openclaw/normalization-core/st
66
import type { OpenClawConfig } from "../config/types.openclaw.js";
77
import { logWarn } from "../logger.js";
88
import { setPluginToolMeta, type PluginToolMcpMeta } from "../plugins/tools.js";
9+
import { matchesMcpToolFilterPattern } from "./agent-bundle-mcp-filter.js";
910
import {
1011
buildSafeToolName,
1112
normalizeReservedToolNames,
@@ -154,31 +155,19 @@ function optionalStringRecordArg(input: unknown, key: string): Record<string, st
154155
return entries.length > 0 ? Object.fromEntries(entries) : undefined;
155156
}
156157

157-
function escapeRegex(value: string): string {
158-
return value.replace(/[\\^$+?.()|[\]{}]/g, "\\$&");
159-
}
160-
161-
function globMatches(pattern: string, value: string): boolean {
162-
const trimmed = pattern.trim();
163-
if (!trimmed) {
164-
return false;
165-
}
166-
if (!trimmed.includes("*")) {
167-
return trimmed === value;
168-
}
169-
return new RegExp(`^${trimmed.split("*").map(escapeRegex).join(".*")}$`).test(value);
170-
}
171-
172158
function serverAllowsUtilityTool(
173159
server: McpToolCatalog["servers"][string],
174160
operation: string,
175161
): boolean {
176162
const include = server.toolFilter?.include ?? [];
177163
const exclude = server.toolFilter?.exclude ?? [];
178-
if (include.length > 0 && !include.some((pattern) => globMatches(pattern, operation))) {
164+
if (
165+
include.length > 0 &&
166+
!include.some((pattern) => matchesMcpToolFilterPattern(pattern, operation))
167+
) {
179168
return false;
180169
}
181-
return !exclude.some((pattern) => globMatches(pattern, operation));
170+
return !exclude.some((pattern) => matchesMcpToolFilterPattern(pattern, operation));
182171
}
183172

184173
function addMcpUtilityTool(params: {

‎src/agents/agent-bundle-mcp-runtime.test.ts‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -928,6 +928,46 @@ describe("session MCP runtime", () => {
928928
}
929929
});
930930

931+
it("rejects adversarial MCP tool filters without regex backtracking", async () => {
932+
const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "bundle-mcp-linear-filter-"));
933+
const serverPath = path.join(tempDir, "linear-filter.mjs");
934+
const logPath = path.join(tempDir, "server.log");
935+
await writeListToolsMcpServer({
936+
filePath: serverPath,
937+
logPath,
938+
tools: [
939+
{
940+
name: `${"a".repeat(64)}c`,
941+
inputSchema: { type: "object", properties: {} },
942+
},
943+
],
944+
});
945+
946+
const runtime = await getOrCreateSessionMcpRuntime({
947+
sessionId: "session-linear-tool-filter",
948+
sessionKey: "agent:test:session-linear-tool-filter",
949+
workspaceDir: "/workspace",
950+
cfg: {
951+
mcp: {
952+
servers: {
953+
docs: {
954+
command: process.execPath,
955+
args: [serverPath],
956+
toolFilter: { include: [`${"*a".repeat(24)}*b`] },
957+
},
958+
},
959+
},
960+
},
961+
});
962+
963+
try {
964+
expect((await runtime.getCatalog()).tools).toEqual([]);
965+
} finally {
966+
await runtime.dispose();
967+
await fs.rm(tempDir, { recursive: true, force: true });
968+
}
969+
});
970+
931971
it("lists MCP tools from servers that omit the tools capability", async () => {
932972
const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "bundle-mcp-unadvertised-tools-"));
933973
const serverPath = path.join(tempDir, "unadvertised-tools.mjs");

‎src/agents/agent-bundle-mcp-runtime.ts‎

Lines changed: 6 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import {
2424
normalizeJsonSchemaForTypeBox,
2525
} from "../shared/json-schema-defaults.js";
2626
import { runTasksWithConcurrency } from "../utils/run-with-concurrency.js";
27+
import { matchesMcpToolFilterPattern } from "./agent-bundle-mcp-filter.js";
2728
import { sanitizeServerName } from "./agent-bundle-mcp-names.js";
2829
import type {
2930
McpCatalogTool,
@@ -343,21 +344,6 @@ async function listAllPrompts(client: Client, timeoutMs: number) {
343344
return prompts;
344345
}
345346

346-
function escapeRegex(value: string): string {
347-
return value.replace(/[\\^$+?.()|[\]{}]/g, "\\$&");
348-
}
349-
350-
function globMatches(pattern: string, value: string): boolean {
351-
const trimmed = pattern.trim();
352-
if (!trimmed) {
353-
return false;
354-
}
355-
if (!trimmed.includes("*")) {
356-
return trimmed === value;
357-
}
358-
return new RegExp(`^${trimmed.split("*").map(escapeRegex).join(".*")}$`).test(value);
359-
}
360-
361347
function normalizeStringList(value: unknown): string[] | undefined {
362348
if (!Array.isArray(value)) {
363349
return undefined;
@@ -379,10 +365,13 @@ function getMcpToolSelection(rawServer: unknown): McpToolSelection {
379365
function shouldExposeMcpTool(selection: McpToolSelection, toolName: string): boolean {
380366
const include = selection.include ?? [];
381367
const exclude = selection.exclude ?? [];
382-
if (include.length > 0 && !include.some((pattern) => globMatches(pattern, toolName))) {
368+
if (
369+
include.length > 0 &&
370+
!include.some((pattern) => matchesMcpToolFilterPattern(pattern, toolName))
371+
) {
383372
return false;
384373
}
385-
return !exclude.some((pattern) => globMatches(pattern, toolName));
374+
return !exclude.some((pattern) => matchesMcpToolFilterPattern(pattern, toolName));
386375
}
387376

388377
function sanitizeMcpMetadataText(value: string | undefined): string | undefined {

0 commit comments

Comments
 (0)