Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學

ASP 網站資料庫被掛馬 (JS 外連) 緊急清除與防護代碼實作

編輯:XP 系統應用技巧

資料庫欄位被注入惡意 <script src="https://..."> 導致前端頁面掛馬。提供三步驟清除腳本與 ASP 防注入函數,適用 Access/SQL Server。

第一步:備份資料庫

操作前完整備份 .mdf/.ldf 或 .mdb,防誤刪可回滾。

第二步:執行 ASP 清除腳本

<%
' conn.asp 自行包含連線字串
Set conn = Server.CreateObject("ADODB.Connection")
conn.Open Application("ConnStr")

Set rsSchema = conn.OpenSchema(adSchemaTables)
Dim k: k = 0
Do While Not rsSchema.EOF
    If rsSchema("TABLE_TYPE") = "TABLE" Then
        k = k + 1
        ' 若表極多可分批:If k > 10 And k < 20 Then
        Set rs = conn.Execute("SELECT * FROM [" & rsSchema("TABLE_NAME") & "]")
        Do While Not rs.EOF
            For Each fld In rs.Fields
                If InStr(LCase(fld.Value), "<script") > 0 Or InStr(LCase(fld.Value), "https://") > 0 Then
                    ' 簡易替換,實際建議用正則完整移除 script 標籤
                    conn.Execute("UPDATE [" & rsSchema("TABLE_NAME") & "] SET [" & fld.Name & "] = REPLACE([" & fld.Name & "], '" & Replace(fld.Value, "'", "''") & "', '') WHERE [ID] = " & rs("ID"))
                End If
            Next
            rs.MoveNext
        Loop
    End If
    rsSchema.MoveNext
Loop
%>

※ 表極多時可分批執行 (如 If k>10 And k<20) 避免 IIS 超時。

第三步:在 conn.asp 加入防護函數

Function Check_Sqljs() ' 偵測 POST/GET 含 script+https:// 特徵
    Dim F_Post, F_Get
    Check_Sqljs = False
    If Request.Form <> "" Then
        For Each F_Post In Request.Form
            If (InStr(LCase(Request.Form(F_Post)), "<script") > 0 Or InStr(LCase(Request.Form(F_Post)), "'") > 0) And InStr(LCase(Request.Form(F_Post)), "https://") > 0 Then
                Check_Sqljs = True: Exit For
            End If
        Next
    End If
    If Request.QueryString <> "" Then
        For Each F_Get In Request.QueryString
            If (InStr(LCase(Request.QueryString(F_Get)), "<script") > 0 Or InStr(LCase(Request.QueryString(F_Get)), "'") > 0) And InStr(LCase(Request.QueryString(F_Get)), "https://") > 0 Then
                Check_Sqljs = True: Exit For
            End If
        Next
    End If
End Function

Function CheckDataFrom() ' 檢查 HTTP_REFERER 是否同源
    CheckDataFrom = True
    Dim sv1, sv2
    sv1 = CStr(Request.ServerVariables("HTTP_REFERER"))
    sv2 = CStr(Request.ServerVariables("SERVER_NAME"))
    If Mid(sv1, 8, Len(sv2)) <> sv2 Then CheckDataFrom = False
End Function

' 在每頁頂端或共用 include 呼叫
If Check_Sqljs() Or Not CheckDataFrom() Then
    Response.Write "非法請求已攔截"
    Response.End()
End If

補充建議

  • 使用參數化查詢 (Command.Parameters) 從根本防範 SQL 注入。
  • 資料庫帳號最小權限原則 (僅 SELECT/INSERT/UPDATE,無 DROP/ALTER)。
  • 定期掃描資料庫異常字串,配合 WAF (Web 應用防火牆) 防禦。
Copyright © Windows教程網 All Rights Reserved