萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP 程式設計

ASP 正則表達式過濾 `

函式目的

移除使用者輸入中完整的 `` 區塊,降低儲存型 XSS 風險。注意:這只是**基礎過濾**,完整防 XSS 需結合輸出編碼、CSP、輸入驗證多層防禦。

核心函式

<%
Function RemoveScriptTags(inputStr)
    Dim objRegExp, result
    If IsNull(inputStr) Or inputStr = "" Then
        RemoveScriptTags = inputStr
        Exit Function
    End If
    
    Set objRegExp = New RegExp
    objRegExp.IgnoreCase = True   ' 不區分大小寫  (貪婪? 改為懶惰 .+?)
    objRegExp.Pattern = "]*>[\s\S]*?"
    
    result = objRegExp.Replace(inputStr, "")
    Set objRegExp = Nothing
    RemoveScriptTags = result
End Function

' 使用範例
Dim userInput, cleanInput
userInput = Request.Form("content")
cleanInput = RemoveScriptTags(userInput)
' 後續儲存 cleanInput...
%>

正則模式解析

片段說明
`匹配標籤開頭
`[^>]*`匹配屬性部分:非 `>` 字元任意數量 (含 `type="text/javascript"`, `src="..."`)
`>`匹配標籤結束 `>`
`[\s\S]*?`**關鍵**:匹配任意字元 (含換行) **懶惰量化**,儘量少匹配,直到遇到下一部分
``匹配結束標籤

為什麼不用 `.+?`?因為 `.` 在 VBScript RegExp 預設**不匹配換行符**,跨行 `", _ ' Script 標籤 "]*>[\s\S]*?", _ ' Iframe "]*>[\s\S]*?", _ ' Object "]*>", _ ' Embed (單標籤) "]*>[\s\S]*?", _ ' Applet "]*>[\s\S]*?", _ ' Form (防表單劫持) "on\w+\s*=", _ ' 事件處理屬性 onclick=, onload= 等 "javascript\s*:", _ ' javascript: 協議 "vbscript\s*:", _ ' vbscript: 協議 "expression\s*\(" _ ' CSS expression() (IE) ) result = inputStr For i = 0 To UBound(patterns) objRegExp.Pattern = patterns(i) result = objRegExp.Replace(result, "") Next Set objRegExp = Nothing SanitizeHtml = result End Function

⚠️ 正則過濾的局限性 (必讀)

  1. 繞過技巧多樣:`ipt>`, `

ASP 程式設計排行

推薦文章

copyright © 萬盛學電腦網 all rights reserved