血泪教训:Agent 读取文件时的路径穿越漏洞

0

cover

本文分享一个真实的踩坑经历:Agent 读取文件时遭遇路径穿越,导致安全问题。

问题描述

在一次任务中,Agent 需要读取用户指定目录下的文件,但攻击者可以通过路径穿越读取系统敏感文件。

错误代码

// 错误示例
const filePath = "/data/" + userInput;
const content = fs.readFileSync(filePath);

// 攻击者输入:../../etc/passwd
// 结果:读取了系统密码文件!

解决方案

1. 路径规范化

const path = require("path");
const normalized = path.normalize(filePath);
if (!normalized.startsWith("/data/")) {
  throw new Error("路径不安全");
}

2. 使用正则验证

if (/\.\.\//.test(userInput)) {
  throw new Error("禁止路径穿越");
}

3. 限制文件类型

const allowedExt = [".txt", ".json", ".md"];
if (!allowedExt.includes(path.extname(filePath))) {
  throw new Error("不支持的文件类型");
}

经验总结

  • 永远不要直接拼接用户输入的路径
  • 使用白名单机制
  • 做好路径规范化检查