fix: 收紧 agent 出网与数据隔离

SSRF 校验补 DNS 解析与每一跳重校验,重定向手动跟随,超时夹紧、响应体截断 2MB;订单工具改用 userId 隔离并转义正则;沙箱固定拦截 .git/.env/密钥文件;环境变量脱敏改为命名模式兜底并删除 env_set。
This commit is contained in:
lik
2026-10-24 22:04:59 +08:00
committed by trae-solo-agent
parent 5e10096fea
commit 1774239553
9 changed files with 325 additions and 112 deletions
+9 -7
View File
@@ -1,9 +1,10 @@
import { tool } from "@langchain/core/tools";
import z from "zod";
import { DBModel } from "../../../../models/index.js";
import { escapeRegex } from "./utils.js";
function createEscortRecordQueryTool(userInfo) {
const userMobile = userInfo?.profile?.mobile;
const userId = userInfo?._id;
return tool(
async ({ patientName, status, page = 1, pageSize = 20 }) => {
@@ -11,17 +12,18 @@ function createEscortRecordQueryTool(userInfo) {
const filter = {};
if (patientName) {
filter["patient.name"] = { $regex: patientName, $options: "i" };
filter["patient.name"] = { $regex: escapeRegex(patientName), $options: "i" };
}
// 强制使用当前登录用户的手机号进行查询
if (!userMobile) {
// 按订单归属用户过滤:不能用手机号作为隔离键,
// 因为手机号可由用户自行修改(改到他人号码即可读到他人订单)
if (!userId) {
return {
success: false,
error: "用户未登录或手机号缺失,无法查询陪诊记录",
error: "用户未登录,无法查询陪诊记录",
};
}
filter["patient.mobile"] = userMobile;
filter.userId = userId;
if (status) {
filter.status = status;
@@ -54,7 +56,7 @@ function createEscortRecordQueryTool(userInfo) {
{
name: "escort_record_query",
description:
"Query escort records from database for the current user. Supports filtering by patient name and appointment status. Returns paginated results sorted by appointment date in descending order. The query is automatically scoped to the current logged-in user's mobile phone number.",
"Query escort records from database for the current user. Supports filtering by patient name and appointment status. Returns paginated results sorted by appointment date in descending order. The query is automatically scoped to the current logged-in user.",
schema: z.object({
patientName: z
.string()
@@ -1,6 +1,7 @@
import { tool } from "@langchain/core/tools";
import z from "zod";
import { DBModel } from "../../../../models/index.js";
import { escapeRegex } from "./utils.js";
const escortRecordQueryTool = tool(
async ({ patientName, mobile, status, page = 1, pageSize = 20 }) => {
@@ -8,7 +9,7 @@ const escortRecordQueryTool = tool(
const filter = {};
if (patientName) {
filter["patient.name"] = { $regex: patientName, $options: "i" };
filter["patient.name"] = { $regex: escapeRegex(patientName), $options: "i" };
}
if (mobile) {
+22
View File
@@ -0,0 +1,22 @@
/**
* 数据库工具的公共小工具
*/
/**
* 转义正则元字符,用于把用户/模型输入当作字面量做模糊匹配
*
* 直接把输入拼进 $regex 有两个问题:用户输入 "(" 会导致查询报错,
* 输入嵌套量词(如 (a+)+$)可能触发 ReDoS。这里统一转义并截断长度。
*
* @param {string} input 原始关键词
* @param {number} maxLength 最大参与匹配的长度
* @returns {string}
*/
function escapeRegex(input, maxLength = 64) {
if (typeof input !== "string") return "";
return input
.slice(0, maxLength)
.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
export { escapeRegex };
+26 -39
View File
@@ -3,6 +3,32 @@
import { tool } from '@langchain/core/tools';
import { z } from 'zod';
/**
* 敏感变量判定:按命名模式兜底,而不是只认几个固定关键词。
*
* 原实现只匹配 API_KEY/SECRET/PASSWORD/TOKEN/CREDENTIAL,
* 会漏掉 MONGODB_URI、DB_PASS、SIGN_KEY 这类常见命名。
*/
const SENSITIVE_PATTERNS = [
/API_?KEY/i,
/SECRET/i,
/PASS(WORD|WD)?/i,
/TOKEN/i,
/CREDENTIAL/i,
/PRIVATE/i,
/AUTH/i,
/(^|_)KEY($|_)/i,
/(^|_)URI($|_)/i,
/DSN/i,
/CONN(ECTION)?/i,
];
/**
* @param {string} key 环境变量名
* @returns {boolean}
*/
const isSensitive = (key) => SENSITIVE_PATTERNS.some((p) => p.test(key));
/**
* 获取环境变量工具
* @param {Object} input - 输入参数
@@ -13,9 +39,6 @@ export const getEnvTool = tool(
async (input) => {
const { name } = input || {};
const sensitiveKeys = ['API_KEY', 'SECRET', 'PASSWORD', 'TOKEN', 'CREDENTIAL'];
const isSensitive = (key) => sensitiveKeys.some(s => key.toUpperCase().includes(s));
if (name) {
const value = process.env[name];
if (value === undefined) {
@@ -44,40 +67,4 @@ export const getEnvTool = tool(
}
);
/**
* 设置环境变量工具
* @param {Object} input - 输入参数
* @param {string} input.name - 环境变量名
* @param {string} input.value - 环境变量值
* @returns {string} - 返回设置结果的JSON字符串
*/
export const setEnvTool = tool(
async (input) => {
const { name, value } = input || {};
if (!name) {
return JSON.stringify({ error: 'Environment variable name is required' });
}
if (value === undefined) {
return JSON.stringify({ error: 'Environment variable value is required' });
}
try {
process.env[name] = value;
return JSON.stringify({ success: true, name, value });
} catch (error) {
return JSON.stringify({ error: `Failed to set environment variable: ${error.message}` });
}
},
{
name: 'env_set',
description: '设置环境变量的值。',
schema: z.object({
name: z.string().describe('环境变量名'),
value: z.string().describe('环境变量值')
})
}
);
export default getEnvTool;
+124
View File
@@ -0,0 +1,124 @@
/**
* Agent 出网 HTTP 客户端:统一承载 SSRF 校验、重定向控制、超时上限与响应体截断。
*
* http_get / http_post 只负责参数整理,真正的安全约束集中在这里,
* 避免两个工具各写一套、修了一个漏掉另一个。
*
* 约束:
* - 每一跳都重新做同步 + DNS 校验,最多 3 跳(重定向可被用来绕过首次校验);
* - POST 不跟随重定向(303/302 会改写成 GET,语义与安全性都不可控);
* - 超时由服务端夹紧到 1s~15s,不接受模型传入的任意大值;
* - 响应体最多读取 2MB,超出即截断并标记 truncated。
*/
import { checkUrlAllowedAsync } from "./url_guard.js";
const DEFAULT_TIMEOUT = 15000;
const MAX_TIMEOUT = 15000;
const MAX_REDIRECTS = 3;
const MAX_BODY_BYTES = 2 * 1024 * 1024;
const REDIRECT_STATUS = new Set([301, 302, 303, 307, 308]);
/**
* 夹紧超时:非法值用默认值,过大值截到上限
* @param {number} timeout 调用方传入的毫秒数
* @returns {number}
*/
function clampTimeout(timeout) {
const value = Number(timeout);
if (!Number.isFinite(value) || value <= 0) return DEFAULT_TIMEOUT;
return Math.min(Math.max(value, 1000), MAX_TIMEOUT);
}
/**
* 读取响应体,超过上限时截断
* @param {Response} response fetch 响应
* @returns {Promise<{buffer: Buffer, truncated: boolean}>}
*/
async function readBodyLimited(response) {
if (!response.body) return { buffer: Buffer.alloc(0), truncated: false };
const reader = response.body.getReader();
const chunks = [];
let size = 0;
let truncated = false;
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = Buffer.from(value);
if (size + chunk.length > MAX_BODY_BYTES) {
chunks.push(chunk.subarray(0, MAX_BODY_BYTES - size));
size = MAX_BODY_BYTES;
truncated = true;
await reader.cancel().catch(() => {});
break;
}
chunks.push(chunk);
size += chunk.length;
}
return { buffer: Buffer.concat(chunks), truncated };
}
/**
* 发起受控的 HTTP 请求
* @param {string} url 目标地址
* @param {Object} options
* @param {string} [options.method] 请求方法
* @param {Object} [options.headers] 请求头
* @param {string} [options.body] 请求体
* @param {number} [options.timeout] 超时毫秒数(会被夹紧)
* @returns {Promise<{status:number,statusText:string,headers:Object,buffer:Buffer,text:string,truncated:boolean,url:string}>}
*/
async function safeFetch(url, options = {}) {
const method = (options.method || "GET").toUpperCase();
const timeout = clampTimeout(options.timeout);
let currentUrl = url;
for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {
// 每一跳都重新校验,防止「公网地址 302 到内网」绕过首次检查
const blocked = await checkUrlAllowedAsync(currentUrl);
if (blocked) throw new Error(blocked);
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeout);
try {
const response = await fetch(currentUrl, {
method,
headers: options.headers,
body: options.body,
redirect: "manual",
signal: controller.signal,
});
if (REDIRECT_STATUS.has(response.status)) {
const location = response.headers.get("location");
await response.body?.cancel().catch(() => {});
if (!location) throw new Error(`Redirect without location: ${response.status}`);
if (method !== "GET") throw new Error("Redirects are not followed for non-GET requests");
currentUrl = new URL(location, currentUrl).toString();
continue;
}
const { buffer, truncated } = await readBodyLimited(response);
return {
status: response.status,
statusText: response.statusText,
headers: Object.fromEntries(response.headers.entries()),
buffer,
text: buffer.toString("utf8"),
truncated,
url: currentUrl,
};
} finally {
clearTimeout(timer);
}
}
throw new Error(`Too many redirects (max ${MAX_REDIRECTS})`);
}
export { safeFetch, clampTimeout };
+19 -24
View File
@@ -1,63 +1,58 @@
import { tool } from 'langchain';
import * as z from 'zod';
import { checkUrlAllowed } from './url_guard.js';
import { safeFetch } from './http_client.js';
export const httpGetTool = tool(
async ({ url, headers = {}, timeout = 30000 }) => {
// SSRF 防护:仅允许 http/https 且目标不得为环回/内网地址
const blocked = checkUrlAllowed(url);
if (blocked) {
return JSON.stringify({ success: false, error: blocked });
}
async ({ url, headers = {}, timeout = 15000 }) => {
try {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), timeout);
const response = await fetch(url, {
// 校验(含 DNS)、重定向控制、超时夹紧、响应体截断统一在 safeFetch 内完成
const response = await safeFetch(url, {
method: 'GET',
headers: {
'User-Agent': 'XAgent-Bot/1.0',
...headers
},
signal: controller.signal
timeout
});
clearTimeout(timeoutId);
const contentType = response.headers.get('content-type') || '';
const contentType = response.headers['content-type'] || '';
let body;
if (contentType.includes('application/json')) {
body = await response.json();
try {
body = JSON.parse(response.text);
} catch (e) {
// 服务端声明 json 但返回非法内容时退回原文,避免工具直接抛错中断对话
body = response.text;
}
} else if (contentType.includes('text/') || contentType.includes('application/javascript')) {
body = await response.text();
body = response.text;
} else {
const buffer = await response.arrayBuffer();
body = Buffer.from(buffer).toString('base64');
body = response.buffer.toString('base64');
}
return JSON.stringify({
success: true,
status: response.status,
statusText: response.statusText,
headers: Object.fromEntries(response.headers.entries()),
headers: response.headers,
truncated: response.truncated,
body
});
} catch (error) {
if (error.name === 'AbortError') {
return JSON.stringify({ success: false, error: `Request timed out after ${timeout}ms` });
return JSON.stringify({ success: false, error: 'Request timed out' });
}
return JSON.stringify({ success: false, error: error.message });
}
},
{
name: 'http_get',
description: 'Send HTTP GET request and return response content. Supports custom headers and timeout settings.',
description: 'Send HTTP GET request and return response content. Response body is capped at 2MB.',
schema: z.object({
url: z.string().describe('Request URL'),
headers: z.record(z.string(), z.string()).optional().describe('Request headers'),
timeout: z.number().optional().describe('Timeout in milliseconds, default 30000')
timeout: z.number().optional().describe('Timeout in milliseconds, clamped to 1s-15s')
})
}
);
+17 -22
View File
@@ -1,15 +1,9 @@
import { tool } from "@langchain/core/tools";
import z from "zod";
import { checkUrlAllowed } from "./url_guard.js";
import { safeFetch } from "./http_client.js";
const httpPostTool = tool(
async ({ url, body, headers = {}, contentType = 'json', timeout = 30000 }) => {
// SSRF 防护:仅允许 http/https 且目标不得为环回/内网地址
const blocked = checkUrlAllowed(url);
if (blocked) {
return { success: false, error: blocked };
}
async ({ url, body, headers = {}, contentType = 'json', timeout = 15000 }) => {
let requestBody;
const requestHeaders = {
'User-Agent': 'XAgent-Bot/1.0',
@@ -38,50 +32,51 @@ const httpPostTool = tool(
}
try {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), timeout);
const response = await fetch(url, {
// 校验(含 DNS)、超时夹紧、响应体截断统一在 safeFetch 内完成;POST 不跟随重定向
const response = await safeFetch(url, {
method: 'POST',
headers: requestHeaders,
body: requestBody,
signal: controller.signal
timeout
});
clearTimeout(timeoutId);
const responseContentType = response.headers.get('content-type') || '';
const responseContentType = response.headers['content-type'] || '';
let responseBody;
if (responseContentType.includes('application/json')) {
responseBody = await response.json();
try {
responseBody = JSON.parse(response.text);
} catch (e) {
responseBody = response.text;
}
} else {
responseBody = await response.text();
responseBody = response.text;
}
return {
success: true,
status: response.status,
statusText: response.statusText,
headers: Object.fromEntries(response.headers.entries()),
headers: response.headers,
truncated: response.truncated,
body: responseBody
};
} catch (error) {
if (error.name === 'AbortError') {
return { success: false, error: `Request timed out after ${timeout}ms` };
return { success: false, error: 'Request timed out' };
}
return { success: false, error: error.message };
}
},
{
name: "http_post",
description: "Send HTTP POST request. Supports JSON and form data.",
description: "Send HTTP POST request. Supports JSON and form data. Response body is capped at 2MB.",
schema: z.object({
url: z.string().describe("Request URL"),
body: z.union([z.string(), z.object({})]).describe("Request body, can be string or JSON object"),
headers: z.record(z.string()).optional().describe("Request headers"),
contentType: z.enum(['json', 'form', 'text', 'raw']).optional().describe("Content type, default json"),
timeout: z.number().optional().describe("Timeout in milliseconds, default 30000")
timeout: z.number().optional().describe("Timeout in milliseconds, clamped to 1s-15s")
}),
},
);
+88 -16
View File
@@ -3,9 +3,16 @@
*
* Agent 的 HTTP 工具处理的 URL 来自模型输出,而模型输入含不可信的用户内容,
* 因此可能被诱导去访问环回/内网地址(如本机 127.0.0.1 上的其他服务、云元数据地址)。
* 这里集中做白名单式校验:仅允许 http/https,且目标不能是环回/内网/链路本地地址。
*
* 两层校验:
* 1. checkUrlAllowed —— 同步校验协议与字面量主机(覆盖直接写内网 IP 的情况);
* 2. checkUrlAllowedAsync —— 再对域名做 DNS 解析,逐个校验解析结果
* (覆盖「公网域名解析到内网地址」的绕过)。仅做同步校验是不够的。
*/
import dns from "dns/promises";
import net from "net";
// 仅允许的协议
const ALLOWED_PROTOCOLS = ["http:", "https:"];
@@ -28,15 +35,56 @@ function isPrivateIPv4(host) {
if (a === 169 && b === 254) return true; // 169.254.0.0/16 链路本地(含云 metadata)
if (a === 172 && b >= 16 && b <= 31) return true; // 172.16.0.0/12
if (a === 192 && b === 168) return true; // 192.168.0.0/16
if (a === 192 && b === 0) return true; // 192.0.0.0/24 IETF 保留
if (a === 198 && (b === 18 || b === 19)) return true; // 198.18.0.0/15 基准测试
if (a >= 224) return true; // 组播与保留段
return false;
}
/**
* 校验 URL 是否允许出网访问
* 是否为内网/保留 IPv6 地址
* @param {string} host 不带方括号的 IPv6 地址
*/
function isPrivateIPv6(host) {
const h = host.toLowerCase();
if (h === "::1" || h === "::") return true;
if (/^f[cd]/.test(h)) return true; // 唯一本地 fc00::/7
if (/^fe[89ab]/.test(h)) return true; // 链路本地 fe80::/10
// IPv4 映射地址:URL 会把 ::ffff:127.0.0.1 规范化成 ::ffff:7f00:1
const mapped = h.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/);
if (mapped) return isPrivateIPv4(mapped[1]);
const mappedHex = h.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/);
if (mappedHex) {
const hi = parseInt(mappedHex[1], 16);
const lo = parseInt(mappedHex[2], 16);
return isPrivateIPv4(`${hi >> 8}.${hi & 255}.${lo >> 8}.${lo & 255}`);
}
// NAT64 64:ff9b::/96 同样内嵌 IPv4
const nat64 = h.match(/^64:ff9b::([0-9a-f]{1,4}):([0-9a-f]{1,4})$/);
if (nat64) {
const hi = parseInt(nat64[1], 16);
const lo = parseInt(nat64[2], 16);
return isPrivateIPv4(`${hi >> 8}.${hi & 255}.${lo >> 8}.${lo & 255}`);
}
return false;
}
/**
* 是否为内网/保留地址(IPv4 或 IPv6 字面量)
* @param {string} address IP 地址
*/
function isPrivateAddress(address) {
return net.isIP(address) === 6 ? isPrivateIPv6(address) : isPrivateIPv4(address);
}
/**
* 同步校验 URL:协议、字面量主机、内网 IP
* @param {string} url 待校验的 URL
* @returns {string|null} 不允许时返回原因文案,允许时返回 null
*/
export function checkUrlAllowed(url) {
function checkUrlAllowed(url) {
let parsed;
try {
parsed = new URL(url);
@@ -54,21 +102,45 @@ export function checkUrlAllowed(url) {
if (BLOCKED_HOSTNAMES.has(hostname)) {
return `Blocked host: ${hostname}`;
}
if (isPrivateIPv4(hostname)) {
if (isPrivateAddress(hostname)) {
return `Blocked private network address: ${hostname}`;
}
if (hostname.includes(":")) {
// IPv6:环回 ::1 / 未指定 :: / 唯一本地 fc00::、fd00:: / 链路本地 fe80::
if (hostname === "::1" || hostname === "::") {
return `Blocked private network address: ${hostname}`;
}
if (/^f[cd]/.test(hostname)) {
return `Blocked private network address: ${hostname}`;
}
if (/^fe[89ab]/.test(hostname)) {
return `Blocked private network address: ${hostname}`;
}
}
return null;
}
/**
* 先同步校验,再解析域名并逐个校验解析结果
* @param {string} url 待校验的 URL
* @returns {Promise<string|null>} 不允许时返回原因文案,允许时返回 null
*/
async function checkUrlAllowedAsync(url) {
const blocked = checkUrlAllowed(url);
if (blocked) return blocked;
const hostname = new URL(url).hostname.replace(/^\[|\]$/g, "").toLowerCase();
if (net.isIP(hostname)) return null; // 字面量地址已在同步阶段校验
let addresses;
try {
addresses = await dns.lookup(hostname, { all: true });
} catch (e) {
return `DNS lookup failed: ${hostname}`;
}
if (!addresses.length) return `DNS lookup returned no address: ${hostname}`;
for (const { address } of addresses) {
if (isPrivateAddress(address)) {
return `Blocked private network address: ${hostname} -> ${address}`;
}
}
return null;
}
export {
checkUrlAllowed,
checkUrlAllowedAsync,
isPrivateAddress,
isPrivateIPv4,
isPrivateIPv6,
};