XSS
攻擊前提
- 攻擊腳本必須添加到頁面上
攻擊方式
- 跨站腳本XSS(Cross site script) 代碼注入
- script 標簽注入攻擊
<li><script>alert(1)</script></li>- 標簽屬性注入攻擊
<img src="" onerror="alert(1)"><p onclick="alert(2)">誘導點擊</p>- 廣告注入
<iframe src=''></iframe>
防止XSS攻擊
- 獲取的數(shù)據(jù)不允許進行字符串拼接
- 使用element.inneText方法 把數(shù)據(jù)添加到dom 中,inneText 方法會轉(zhuǎn)義所有內(nèi)容
- 把所有數(shù)據(jù)里的
/["'&<>]/使用正則進行轉(zhuǎn)義- 存儲數(shù)據(jù)時過濾并轉(zhuǎn)義
/["'&<>]/- 防止URL 上的參數(shù)在頁面上展示
http://url?code=<p onclick="alert(2)">誘導點擊</p>這里的code query參數(shù)內(nèi)容不得在頁面中渲染
CSRF

攻擊原理
- 利用用戶已經(jīng)登錄的狀態(tài) 偽造請求發(fā)送給服務器進行用戶操作
攻擊方式
- 跨站請求偽造(Cross site request forgery)
- 用戶已登錄(cookie登錄)
如果沒設置httpOnly cookie是根據(jù)域名和路徑訪問的, 無關(guān)端口- 偽造請求(GET, POST)
偽造GET
<img src="http://localhost:3000/csrf?data=111" alt="">
http://localhost:3000/csrf?data=111 // 直接地址欄中輸入
表單偽造POST
<form id="form" style="display: none;" action="http://localhost:3000/csrf?data=111" method="post" target="csrf">
</form>
<input id="btn" type="button" value="submit">
<iframe src="" style="display: none;" name="csrf" frameborder="0"></iframe>
<script>
btn.addEventListener('click', (e) => {
e.preventDefault()
form.submit()
})
</script>
防止CSRF攻擊
- 請求時不僅瀏覽器攜帶cookie,
請求參數(shù)也需要把跟cookie 相關(guān)的值攜帶到參數(shù)中, 偽造的請求無法獲取正確網(wǎng)站cookie的值, 比如常見約定的csrfToken- 使用Authorization 的token 授權(quán)
- 提交表單的時候增加token 認證
- 驗證請求header 的Referer
攜帶請求來源信息