前言
在目前主推網絡安全的情況下,很多開發項目都需要在上線前進行滲透測試,當符合滲透測試標準及沒有安全漏洞即可正常上線,當前還會有代碼審計的,這個另當別論。
如何對XSS進行防護
在很多的富文本編輯器項目中,xss漏洞已經是家常便飯了。接下來直接上修復代碼。
當前使用環境為vue3+ts+vite項目,首先安裝依賴
npm install xss
在main.ts中引入
import xss from 'xss'
然后全局掛在自定義方法,這里提供兩種掛在方法
第一種
//掛在全局xss過濾器方法
app.config.globalProperties.$xss = (html: any) => {return xss(html)
}
在組件中的使用
import { getCurrentInstance } from 'vue'const instance = getCurrentInstance()
if (!instance) {// 處理無法獲取到實例的情況throw new Error('Cannot get current instance')
}
// 通過實例的 appContext.config.globalProperties 訪問 $xss
const $xss = instance.appContext.config.globalProperties.$xss
console.log($xss('<img src=q οnerrοr=alert(1)>'))
第二種
const $xss = (html: any): any => {return xss(html)
}
// 使用 provide 提供 $xss 方法
app.provide('$xss', $xss)
組件中的使用
import { inject } from 'vue'
// 使用 inject 注入 $xss 方法
const $xss: any = inject('$xss')
console.log($xss('<img src=q οnerrοr=alert(1)>'))
在v-html中沒有過濾xss的效果
在v-html中使用xss過濾后的效果
CSS樣式丟失處理
很不巧過濾完css出現了css樣式代碼丟失,我應該如何解決,這種情況一般都是我們的過濾太嚴格了,我們添加一些自己允許的白名單配置即可。出現下圖狀況
修復方案
const options: any = {onIgnoreTagAttr: function(tag: any, name: any, value: any, isWhiteAttr: any) {if (name.substr(0, 2) === 'on') {return '' // 過濾掉所有的事件監聽器屬性,例如 onclick}// 如果屬性是 style,并且不在白名單內,仍然允許它通過if (name === 'style' || name === 'iframe') {return `${name}="${value}"` // 直接返回 style 屬性}},onTag: (tag: any, html: any) => {if (tag === 'style') {// 當遇到 style 標簽時,直接返回,不做處理return html}if (tag === 'iframe') {// 從 HTML 字符串中解析出 src 屬性的值const srcMatch = html.match(/src="([^"]+)"/)const src = srcMatch ? srcMatch[1] : ''// 驗證 src 是否來自可信來源if (src.startsWith('http://www.iot-wiki.cn')) {return html} else {// 如果不是可信來源,移除 iframereturn ''}}},stripIgnoreTag: true, // 去除不在白名單上的標簽stripIgnoreTagBody: ['script'],// 去除不在白名單上的標簽及其內容css: false
}
const $xss = (html: any): any => {return xss(html, options)
}
// 使用 provide 提供 $xss 方法
app.provide('$xss', $xss)
最后
如果你的項目是vue2+webpack+js的話,推薦使用vue-xss庫,方便快捷
安裝命令
npm install vue-xss
在main.js中引入并且使用
import VueXss from 'vue-xss'
Vue.use(VueXss)
在組件中的使用
<div v-html="$xss(content)"></div>
如果你的是陰間項目,使用的是vue2+ts+webpack的項目,那你可以參考上面的vue3+ts+vite項目的使用方法,注意vue2和vue3全局掛在自定義方法是不一樣的,這里需要自行修改。
*如果有更好的解決方案歡迎評論diss我