HTTP_X_FORWARDED_FOR 標頭,記錄真實 IP 並封鎖代理存取<%@ Language=VBScript CodePage=65001 %>
<%
' === 設定區 ===
Const REFRESH_SEC = 10 ' 同頁最小間隔秒數
Const ENABLE_PROXY_CHECK = True
Const ENABLE_BLACKLIST = True
Const LOG_FILE = "cclog.txt"
Const BLACKLIST_FILE = "badip.txt"
' ===============
' 初始化 Session 變數
If Session("cc_init") <> "1" Then
Session("cc_init") = "1"
Session("lastReq") = Now()
Session("clientIP") = GetClientIP()
Session("proxyIP") = Request.ServerVariables("HTTP_X_FORWARDED_FOR")
End If
' 載入黑名單到 Application (啟動時一次)
If Application("badip_list") = "" Then
Application.Lock
If Application("badip_list") = "" Then
Application("badip_list") = LoadBadIPs()
End If
Application.Unlock
End If
' ---------- 第一層:頻率限制 ----------
If DateDiff("s", Session("lastReq"), Now()) < REFRESH_SEC Then
LogAttack "RATE_LIMIT", Session("clientIP"), Session("proxyIP")
Response.Write "系統繁忙,請 " & REFRESH_SEC & " 秒後再試 (001)"
Response.End
End If
Session("lastReq") = Now()
' ---------- 第二層:代理偵測 ----------
If ENABLE_PROXY_CHECK Then
Dim proxyIP : proxyIP = Session("proxyIP")
If proxyIP <> "" Then
' 記錄代理 IP 到黑名單檔
Call AppendBadIP(proxyIP)
LogAttack "PROXY_DENY", Session("clientIP"), proxyIP
Response.Write "偵測到代理伺服器,拒絕存取 (002)"
Response.End
End If
End If
' ---------- 第三層:黑名單攔截 ----------
If ENABLE_BLACKLIST Then
Dim ip : ip = Session("clientIP")
If InStr(Application("badip_list"), ip & vbCrLf) > 0 Then
LogAttack "BLACKLIST_HIT", ip, ""
Response.Write "您的 IP 已被封鎖 (003)"
Response.End
End If
End If
' ===== 輔助函式 =====
Function GetClientIP()
Dim ip : ip = Request.ServerVariables("HTTP_X_FORWARDED_FOR")
If ip = "" Then ip = Request.ServerVariables("REMOTE_ADDR")
GetClientIP = ip
End Function
Function LoadBadIPs()
Dim fso, f, content
Set fso = Server.CreateObject("Scripting.FileSystemObject")
On Error Resume Next
Set f = fso.OpenTextFile(Server.MapPath(BLACKLIST_FILE), 1, True) ' ForReading
If Err.Number = 0 Then
content = f.ReadAll
f.Close
Else
content = ""
Err.Clear
End If
Set f = Nothing: Set fso = Nothing
LoadBadIPs = content & vbCrLf ' 確保換行結尾利於 InStr
End Function
Sub AppendBadIP(ip)
Dim fso, f
Set fso = Server.CreateObject("Scripting.FileSystemObject")
On Error Resume Next
Set f = fso.OpenTextFile(Server.MapPath(BLACKLIST_FILE), 8, True) ' ForAppending
f.WriteLine ip
f.Close
Set f = Nothing: Set fso = Nothing
' 同步更新記憶體
Application.Lock
Application("badip_list") = Application("badip_list") & ip & vbCrLf
Application.Unlock
On Error GoTo 0
End Sub
Sub LogAttack(type, clientIP, proxyIP)
Dim fso, f, line
line = Now() & vbTab & type & vbTab & clientIP & vbTab & proxyIP & vbCrLf
Set fso = Server.CreateObject("Scripting.FileSystemObject")
On Error Resume Next
Set f = fso.OpenTextFile(Server.MapPath(LOG_FILE), 8, True)
f.Write line
f.Close
Set f = Nothing: Set fso = Nothing
On Error GoTo 0
End Sub
%>
在每個需保護的頁面**最頂端**包含:
<!--#include file="anti_cc.asp"-->
REFRESH_SEC