首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫

ASP 防 SQL 注入改良函數:SafeRequest 實作與原理

     編輯:MySQL 資料庫相關知識

背景

針對既有 ASP 程式存在 SQL 注入漏洞,綜合網路各種防禦手法,改良出 SafeRequest 函數替代原生 Request 物件,集中過濾高風險關鍵字。

程式碼實作

Function SafeRequest(ParaName)
    Dim ParaValue
    ParaValue = Request(ParaName)
    If IsNumeric(ParaValue) = True Then
        SafeRequest = ParaValue
        Exit Function
    ElseIf InStr(LCase(ParaValue), "select ") > 0 Or _
           InStr(LCase(ParaValue), "insert ") > 0 Or _
           InStr(LCase(ParaValue), "delete from") > 0 Or _
           InStr(LCase(ParaValue), "count(") > 0 Or _
           InStr(LCase(ParaValue), "drop table") > 0 Or _
           InStr(LCase(ParaValue), "update ") > 0 Or _
           InStr(LCase(ParaValue), "truncate ") > 0 Or _
           InStr(LCase(ParaValue), "asc(") > 0 Or _
           InStr(LCase(ParaValue), "mid(") > 0 Or _
           InStr(LCase(ParaValue), "char(") > 0 Or _
           InStr(LCase(ParaValue), "xp_cmdshell") > 0 Or _
           InStr(LCase(ParaValue), "exec master") > 0 Or _
           InStr(LCase(ParaValue), "net localgroup administrators") > 0 Or _
           InStr(LCase(ParaValue), " and ") > 0 Or _
           InStr(LCase(ParaValue), "net user") > 0 Or _
           InStr(LCase(ParaValue), " or ") > 0 Then
        Response.Write ""
        Response.End
    Else
        SafeRequest = ParaValue
    End If
End Function

使用方式

全專案將 Request("param") 替換為 SafeRequest("param") 即可。

原理與限制

  • 數值型直接放行:IsNumeric 判斷為數字則不檢查。
  • 關鍵字黑名單:涵蓋 DML/DDL 指令、系統預存程序、註釋符號、邏輯運算子等。
  • 攔截行為:彈出警示並導向指定頁面,終止腳本執行。

注意:黑名單法無法防禦所有變形攻擊(如編碼繞過、寬字節注入),建議搭配參數化查詢、最小權限帳號、WAF 等多層防護。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved