April 24th, 2008IIS IP Secuirty
Carrying on from my IIS admin via a web service work, i needed to apply IPSecurity restrictions to some of the sites that would be created.
Plently of googling revealed some information about an IISIPSecurity class in .NET 3.0 and above, but i could only rough c# sample code here , and that was for a console app
so after many failed attempts to convert to VB.NET to work with my web service, and even tried the ADSIIIS.dll com interop, i gave up and converted the c# code into an assembly , which works. I know hind sight is 20:20, but i shodul have just done that in the first place
my code is here
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.DirectoryServices;
using System.Reflection;
namespace IISSecurity
{
public class IISIPSecurity
{
static string SetIPSecurityProperty(string metabasePath, string member, string item)
{// metabasePath is of the form “IIS://<servername>/<path>”
// for example “IIS://localhost/SMTPSVC/1″
// member is of the form “IPGrant|IPDeny|DomainGrant|DomainDeny”
// item is of the form “<ipaddress|domain>”, for example, 157.56.236.15 or domain.microsoft.com try
{
if ((“IPGrant” != member) && (“IPDeny” != member) && (“DomainGrant” != member) && (“DomainDeny” != member))
{
return “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);
bool exists = false;
foreach (object dataItem in data)
{
if (dataItem.ToString().StartsWith(item))
{
exists = true;
}
}
if (exists)
{
return “Not appling already exists”;
}
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);
}
return “OK”;
}
}
catch (Exception ex)
{
return ex.Message;
}
}
}
}