Dynamic Blocking and unlocking IP

Source: Internet
Author: User
Tags foreach bool iis reflection

When we respond to malicious requests from the website, one solution is to kill the problematic request IP.

If you want to quickly deal with this problem, you need to write a piece of code to reach a certain threshold, automatic blocking. The more complex point is not permanently banned, but also automatically after a certain time to unlock.

Block the logic code to see what is provided later.

What needs to be explained is: when IIS7, the situation is different.

The following code, in the processing of the block IP, regardless of IIS6 or IIS7 can be blocked by the IP to join the blocked list. However, it is important to note that our code is written to replace the original data. However, under the IIS7, the effect of execution is the original do not replace, a new batch of blocked IP. Of course, if the new IP is IIS7, the following exception will be reported:

System.Runtime.InteropServices.COMException was caught
Message= "The file cannot be created when the file already exists. (Exception from Hresult:0x800700b7) "
Source= "System.DirectoryServices"
errorcode=-2147024713
StackTrace:
In System.DirectoryServices.DirectoryEntry.CommitChanges ()
In IIS_Security_ConsoleApplication.Program.IPDeny () position d:/mycodes/iis_security_consoleapplication/iis_security_ Consoleapplication/program.cs: Line No. 109
InnerException:

That said, IIS7, we can add the block IP list through the programming interface, but do not send out the blocking IP through the programming interface.

Reference Code:

Here are two sets of reference code, in fact the principle is the same.

Under IIS 6, there are no problems, and IIS 7 will have no problem deleting the original data.

Code One:


Using System.DirectoryServices;
Using System.Reflection;
Using System;

Class Program
{

static void IPDeny ()
{

Try
{
string serverName = "localhost";
Retrieve the directory entry for the root of the IIS server
System.DirectoryServices.DirectoryEntry IIS = new System.DirectoryServices.DirectoryEntry (string. Format ("Iis://{0}/w3svc/1/root", ServerName));

Retrieve the list of currently denied IPs
Console.WriteLine ("Retrieving the list of currently denied IPs.");

Get the IPSecurity property
Type Typ = IIS. properties["IPSecurity"][0]. GetType ();
Object ipsecurity = IIS. properties["IPSecurity"][0];


Retrieve the IPDeny list from the IPSecurity object
Array origipdenylist = (array) typ. InvokeMember ("IPDeny", BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic
| BindingFlags.Instance | BindingFlags.GetProperty, NULL, ipsecurity, NULL);

List addresses that have been rejected
foreach (string s in origipdenylist)
Console.WriteLine ("Before:" + s);

Check GrantByDefault. This have to is set to true,
Or what we are doing won't work.
BOOL Bgrantbydefault = (bool) typ. InvokeMember ("GrantByDefault", BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic
| BindingFlags.Instance | BindingFlags.GetProperty, NULL, ipsecurity, NULL);

Console.WriteLine ("GrantByDefault =" + Bgrantbydefault);
if (!bgrantbydefault)
{
You must set the default allowed access
Typ. InvokeMember ("GrantByDefault", BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance
| BindingFlags.SetProperty, NULL, ipsecurity, new object[] {true});
}


Update the list of rejected IPs
Note Here is a complete replacement
If you want to keep the original Deny list, you need the original deny list in this array

Console.WriteLine ("Updating the list of denied IPs.");

object[] newipdenylist = new Object[4];
Newipdenylist[0] = "192.168.1.21, 255.255.255.255";
NEWIPDENYLIST[1] = "192.168.1.22, 255.255.255.255";
NEWIPDENYLIST[2] = "192.168.1.23, 255.255.255.255";
NEWIPDENYLIST[3] = "192.168.1.24, 255.255.255.255";

Console.WriteLine ("Calling SetProperty");

Add the updated list back to the IPSecurity object
Typ. InvokeMember ("IPDeny", BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance
| BindingFlags.SetProperty, NULL, ipsecurity, new object[] {newipdenylist});



Iis. properties["IPSecurity"][0] = ipsecurity;

Console.WriteLine ("Commiting the changes.");

Commit the changes
Iis.commitchanges ();
Iis. RefreshCache ();

Check for updated data
Console.WriteLine ("Checking to see if the update took.");

IPSecurity = IIS. properties["IPSecurity"][0];
Array y = (array) typ. InvokeMember ("IPDeny",
BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetProperty,
NULL, ipsecurity, NULL);

foreach (string s in y)
Console.WriteLine ("After:" + s);
}
catch (Exception e)
{
Console.WriteLine ("Error:" + e.tostring ());
}

}
}

Code two:

        Using System.DirectoryServices;
Using System.Reflection;
Using System;



static void Setipsecurityproperty (String metabasepath, string member, string item)
{
MetabasePath is of the form "iis:///"
For example "IIS://LOCALHOST/SMTPSVC/1"
Member is of the form "ipgrant| ipdeny| Domaingrant| DomainDeny "
Item is of the form ' ", for example, 157.56.236.15 or domain.microsoft.com
Console.WriteLine ("/nenumerating the IPSecurity property at {0}:", MetabasePath);

Try
{
if ("ipgrant"! = Member) && ("ipdeny"! = Member) && ("domaingrant"! = Member) && ("domaindeny"! = Member))
{
Console.WriteLine ("Failed in Setipsecurityproperty; Second param must be one of ipgrant| ipdeny| Domaingrant| DomainDeny ");
}
Else
{
DirectoryEntry path = new DirectoryEntry (MetabasePath);
Path. RefreshCache ();
Object ipsecobj = path. Invoke ("Get", new string[] {"IPSecurity"});
Type t = Ipsecobj.gettype ();
Array data = (array) t.invokemember (member, BindingFlags.GetProperty, NULL, ipsecobj, NULL);
Console.WriteLine ("Old {0} =", member);
BOOL exists = false;
foreach (object DataItem in data)
{
Console.WriteLine ("{0}", dataitem.tostring ());
if (dataitem.tostring (). StartsWith (item))
{
exists = true;
}
}

if (exists)
{
Console.WriteLine ("{0} already exists in {1}", item, member);
}
Else
{
object[] NewData = new Object[data. Length + 1];
Data. CopyTo (NewData, 0);
Newdata.setvalue (item, data. Length);

T.invokemember (member, BindingFlags.SetProperty, NULL, ipsecobj, new object[] {newdata});

Path. Invoke ("Put", new object[] {"IPSecurity", ipsecobj});

Path.commitchanges ();

Path. RefreshCache ();
Ipsecobj = path. Invoke ("Get", new string[] {"IPSecurity"});
data = (Array) t.invokemember (member, BindingFlags.GetProperty, NULL, ipsecobj, NULL);
Console.WriteLine ("New {0} =", member);
foreach (object DataItem in data)
Console.WriteLine ("{0}", dataitem.tostring ());
Console.WriteLine ("Done.");
}
}
}
catch (Exception ex)
{
if ("HRESULT 0x80005006" = = ex. Message)
Console.WriteLine ("IPSecurity does not exist at {0}", MetabasePath);
Else
Console.WriteLine ("Failed in Setipsecurityproperty with the following exception:/n{0}", ex. Message);
}
}

static void Main (string[] args)
{

Get what sites are currently on the server
DirectoryEntry root = new DirectoryEntry ("Iis://localhost/w3svc");
foreach (DirectoryEntry dir in Root.) Children)
{
if (dir. schemaClassName = = "IIsWebServer")
{
string ww = dir. properties["ServerComment"]. Value.tostring ();

Console.Write ("iis://localhost/w3svc/{0}/root/{1}/r/n", dir.) Name, WW);
}
}


IPDeny ();

Setipsecurityproperty ("Iis://localhost/w3svc/1/root", "IPDeny", "192.168.5.79");

Console.ReadLine ();
}

References:

Blocking IIS IP Addresses with ASP.
Http://www.west-wind.com/WebLog/posts/59731.aspx

How to programmatically add IP Addresses to IIS ' s Deny Access List
Http://www.codeproject.com/KB/security/iiswmi.aspx

HOWTO: Restricting site access by IP address or domain name
http://support.microsoft.com/default.aspx/kb/324066

Use ADSI to manipulate the path of IIS
Http://blog.joycode.com/ghj/archive/2004/06/08/24047.aspx

Setting IP Security Using system.directoryservices
Http://www.cnblogs.com/drw/articles/17951.html

How to control the list of disabled IPs for IIS via Web mode.
Http://blog.joycode.com/ghj/archive/2004/06/08/24075.aspx

Setting IP Security Using system.directoryservices
http://msdn.microsoft.com/en-us/library/ms524322 (vs.85). aspx

How to automate adding denied IPs for IIS

http://www.nukeforums.com/forums/viewtopic.php?p=54746&highlight=&sid=1176c746e2037ed24acac86dd53ca747

IIS 7.0:configure IPv4 Address and Domain Name allow Rules
Http://technet2.microsoft.com/windowsserver2008/en/library/d0de9475-0439-4ec1-8337-2bcedacd15c71033.mspx?mfr=true

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.