2012-06-25 37 views
1

我接管了運行舊版社區服務器的域。毋庸置疑,機器人正在向我發送垃圾郵件,試圖找到漏洞。在HttpModule中阻止IP地址

我想在觸發System.Web.HttpRequest.ValidateInputIfRequiredByConfig()之前封鎖整個IP塊。我有一個IHttpModule,我已經嘗試過,但我認爲它被調用後,因爲HealthMonitoring捕捉異常。下面是該模塊:

public class IpBlockerModule : IHttpModule 
{ 
    private static readonly string[] Hacks = new[] 
               { 
                "60.169.73.", 
                "60.169.75.", 
                "61.160.232.", 
                "61.160.207.", 
                "92.85.161." 
               }; 

    public void Dispose() 
    { 

    } 

    public void Init(HttpApplication context) 
    { 
     context.BeginRequest += (Application_BeginRequest); 
    } 

    private void Application_BeginRequest(object source, EventArgs e) 
    { 
     var context = ((HttpApplication) source).Context; 
     var ipAddress = context.Request.UserHostAddress; 

     if (!IsHackIpAddress(ipAddress)) 
     { 
      context.Response.StatusCode = 403; // (Forbidden) 
     } 
    } 

    private static bool IsHackIpAddress(string ip) 
    { 
     if (ip == null) return true; 

     return Hacks.Any(x => x.StartsWith(ip)); 
    } 
} 

而且培訓相關的web.config部分:

<system.web> 
    <httpModules> 
     <add name="IpBlockerModule" type="MyNameSpace.IpBlockerModule" /> 
    </httpModules>  
</system.web> 

<system.webServer> 
    <validation validateIntegratedModeConfiguration="false" /> 
    <modules runAllManagedModulesForAllRequests="true" > 
     <add name="IpBlockerModule" type="MyNameSpace.IpBlockerModule" preCondition="" /> 
    </modules> 
</system.webServer> 

這背後的原因是我的收件箱正從所有

A potentially dangerous Request.Path value was detected from the 
client 

垃圾郵件
A potentially dangerous Request.Form value was detected from the client 

noti fications。我的模塊出了什麼問題,或者我是否正確地假設模塊直到事後才被解僱?

回答

4

作爲替代解決方案,您是否考慮讓IIS爲您完成這項工作?這種方式的請求永遠不會讓你的應用程序。您可以通過在web.config做到這一點,有一個文章,詳細located here.下面的例子是從文章直接複製和將放在你的web.config的<system.webServer>單元的內部的流程:

<security> 
    <ipSecurity allowUnlisted="true"> <!-- this line allows everybody, except those listed below -->    
     <clear/>  <!-- removes all upstream restrictions -->     
     <add ipAddress="83.116.19.53"/>  <!-- blocks the specific IP of 83.116.19.53 -->     
     <add ipAddress="83.116.119.0" subnetMask="255.255.255.0"/>  <!--blocks network 83.116.119.0 to 83.116.119.255-->     
     <add ipAddress="83.116.0.0" subnetMask="255.255.0.0"/>  <!--blocks network 83.116.0.0 to 83.116.255.255-->     
     <add ipAddress="83.0.0.0" subnetMask="255.0.0.0"/>  <!--blocks entire /8 network of 83.0.0.0 to 83.255.255.255-->     
    </ipSecurity> 
</security> 
+0

這看起來應該可以工作,但是,即使在我的web.config文件的'system.webServer'部分中添加''部分,也會拋出500.但是,我繼續將其添加到IIS全局配置中,並且它似乎工作正常。昨晚沒有更多異常通知。 – mxmissile