输入并不可信
本课属于 Coddy Node.js 学习旅程的“身份验证与安全”单元。第 24 课,共 24 课。
客户端发送的任何内容都可能由攻击者编写。一个 50 MB 的请求体会占用你的内存。包含 <script> 的便条会在查看它的人的浏览器中作为代码运行:这就是跨站脚本攻击(XSS)。
限制你接受的内容:每个 Express 请求体解析器都接受一个 limit,请求体过大时,会在你的路由运行之前返回 413 Payload Too Large。按原样存储文本,并在将其放入 HTML 时进行转义,这样浏览器就会显示这些字符,而不是运行它们。html.js 为你提供了 escapeHtml。
app.use(express.urlencoded({ limit: '2kb' }));
escapeHtml('<img src=x onerror=steal()>');
// '<img src=x onerror=steal()>'挑战
简单把客户端发送的所有内容都当作可能由攻击者编写。拒绝过大的请求体,并让笔记页面把用户输入的 HTML 显示为纯文本,而不是运行它。
- 在
server.js中,为顶部的 JSON 请求体解析器设置 10 KB 的限制。超过限制的请求体会在任何路由运行之前返回状态码 413 Payload Too Large。长度为 9,000 个字符的笔记仍必须能够保存。 - 从
./html.js导入escapeHtml。它会把<这样的字符转换为<,这样浏览器就会显示它们,而不是运行它们。它的作用和你在 Express Basics 中学过的escapeHtml一样。 - 在
GET /对应的页面中,把每条笔记的文本和用户名传给escapeHtml,然后再将它们放入 HTML。保存笔记时保持原样,不要改动。只在文本要放入 HTML 时进行转义。
试一试:点击“运行”。发送 POST /signup,然后发送 POST /login,两者都使用 {"username": "ada", "password": "correct horse"}。发送 POST /notes,使用 {"text": "<script>alert('hi')</script>"}:状态码为 201。发送 GET /:列表会把 <script>alert('hi')</script> 显示为普通文本,页面源代码中原标签所在的位置会显示 <script>。检查还会替你发送一条长度为 11,000 个字符的笔记,并要求状态码为 413,所以你不必自己输入。
亲手试试
import express from 'express';
import { ObjectId } from 'mongodb';
import { randomBytes } from 'node:crypto';
import { parseCookies } from './cookies.js';
import { notes, sessions, users } from './db.js';
import { hashPassword, verifyPassword } from './passwords.js';
const app = express();
app.disable('x-powered-by');
app.use(express.json());
// 这些响应头告诉浏览器谨慎处理每个响应。
app.use((req, res, next) => {
res.set({
'X-Content-Type-Options': 'nosniff',
'Referrer-Policy': 'no-referrer',
'Content-Security-Policy': "default-src 'self'",
});
next();
});
// 唯一的管理员账号。密码来自环境变量。
await users.insertOne({ username: 'admin', role: 'admin', passwordHash: await hashPassword(process.env.ADMIN_PASSWORD) });
app.post('/signup', async (req, res) => {
const username = String(req.body.username ?? '').trim().toLowerCase();
const password = String(req.body.password ?? '');
if (!username || password.length < 8) {
return res.status(400).json({ error: 'Pick a username and a password of at least 8 characters' });
}
if (await users.findOne({ username })) {
return res.status(409).json({ error: 'That username is taken' });
}
await users.insertOne({ username, role: 'member', passwordHash: await hashPassword(password) });
res.status(201).json({ username });
});
// 各用户名的登录失败记录:{ count, since }。
const failures = new Map();
const WINDOW_MS = 60 * 1000;
app.post('/login', async (req, res) => {
const username = String(req.body.username ?? '').trim().toLowerCase();
let failed = failures.get(username);
if (failed && Date.now() - failed.since >= WINDOW_MS) {
failed = undefined;
}
if (failed && failed.count >= 5) {
res.set('Retry-After', String(Math.ceil((failed.since + WINDOW_MS - Date.now()) / 1000)));
return res.status(429).json({ error: 'Too many failed logins. Try again later.' });
}
const user = await users.findOne({ username });
if (!user || !(await verifyPassword(String(req.body.password ?? ''), user.passwordHash))) {
failures.set(username, { count: (failed?.count ?? 0) + 1, since: failed?.since ?? Date.now() });
return res.status(401).json({ error: 'Wrong username or password' });
}
const sid = randomBytes(24).toString('base64url');
await sessions.insertOne({ _id: sid, userId: user._id, createdAt: new Date() });
res.cookie('sid', sid, {
httpOnly: true,
sameSite: 'lax',
secure: true,
maxAge: 24 * 60 * 60 * 1000,
});
res.json({ username: user.username });
});
// 根据会话 cookie 查找用户,找不到就返回 401。
async function requireUser(req, res, next) {
const { sid } = parseCookies(req.get('cookie'));
const session = sid && (await sessions.findOne({ _id: sid }));
const user = session && (await users.findOne({ _id: session.userId }));
if (!user) {
return res.status(401).json({ error: 'Log in first' });
}
req.user = { id: user._id.toHexString(), username: user.username, role: user.role };
next();
}
// 如果已登录用户没有此角色,就返回 403。
function requireRole(role) {
return (req, res, next) => {
if (req.user.role !== role) {
return res.status(403).json({ error: 'Not allowed' });
}
next();
};
}
app.get('/me', requireUser, (req, res) => {
res.json({ username: req.user.username });
});
app.post('/logout', async (req, res) => {
const { sid } = parseCookies(req.get('cookie'));
if (sid) {
await sessions.deleteOne({ _id: sid });
}
res.clearCookie('sid');
res.status(204).end();
});
// 以页面形式显示你的笔记。
app.get('/', requireUser, async (req, res) => {
const list = await notes.find({ owner: req.user.id }).toArray();
const items = list.map((note) => `<li>${note.text}</li>`).join('');
res.send(`<!doctype html><title>Vault</title><h1>${req.user.username}'s notes</h1><ul>${items}</ul>`);
});
// 笔记:每个用户只能读写自己的笔记。
app.get('/notes', requireUser, async (req, res) => {
res.json(await notes.find({ owner: req.user.id }).toArray());
});
app.post('/notes', requireUser, async (req, res) => {
const note = { owner: req.user.id, text: String(req.body.text ?? '') };
await notes.insertOne(note);
res.status(201).json(note);
});
app.get('/notes/:id', requireUser, async (req, res) => {
if (!ObjectId.isValid(req.params.id)) {
return res.status(404).json({ error: 'Note not found' });
}
const note = await notes.findOne({ _id: new ObjectId(req.params.id), owner: req.user.id });
if (!note) {
return res.status(404).json({ error: 'Note not found' });
}
res.json(note);
});
app.delete('/notes/:id', requireUser, async (req, res) => {
if (!ObjectId.isValid(req.params.id)) {
return res.status(404).json({ error: 'Note not found' });
}
const { deletedCount } = await notes.deleteOne({ _id: new ObjectId(req.params.id), owner: req.user.id });
if (!deletedCount) {
return res.status(404).json({ error: 'Note not found' });
}
res.status(204).end();
});
// 供管理员查看:账号总数。
app.get('/admin', requireUser, requireRole('admin'), async (req, res) => {
res.json({ users: await users.countDocuments() });
});
app.listen(3000, () => {
console.log('Vault is running on port 3000');
});
身份验证与安全中的所有课
自己练习: Express 在线编辑器