上传功能的危险分三层:能不能传上去 → 传上去能不能执行 → 执行了能不能碰到别人的身份。多数人只防了第一层。
// 常见写法
if (name.endsWith('.php') || name.endsWith('.jsp')) reject();
// 绕过:shell.php5 / shell.phtml / shell.php.jpg + 解析配置 / shell.svg(XSS)
改成白名单,并且判断依据要是 MIME + 扩展名双校验,不是只看文件名:
const ALLOW = new Set(['image/jpeg','image/png','image/webp','application/pdf']); if (!ALLOW.has(file.mimetype)) reject(); const ext = path.extname(file.originalname).toLowerCase(); if (!['.jpg','.jpeg','.png','.webp','.pdf'].includes(ext)) reject(); // 存盘名自己生成,永远不用用户传的名字 const name = crypto.randomUUID() + ext;
这一步最要命。上传的 evil.html 或 evil.svg 被 /uploads/ 以 text/html 返回,就等于给了攻击者一个同源页面——它能带着访问者的 Cookie 调你的所有接口。
location /uploads/ {
add_header Content-Disposition "attachment";
add_header Content-Type "application/octet-stream";
add_header X-Content-Type-Options "nosniff";
}
再狠一点:把上传域名独立出来,或者干脆走对象存储的私有读 + 签名 URL。
<div class="file">${file.name}</div> // 文件名叫 <img src=x onerror=...> 就执行了
所有从接口拿的数据只要进 innerHTML,就必须转义。后台管理页尤其容易忘——管理员权限最高,XSS 打中就是全站沦陷。
.html,访问它的 URL,看浏览器是下载还是渲染成页面。渲染了,就是同源 XSS。