Setting IP Security Using System.DirectoryServices

Set IP security to configure IIS to restrict client access based on IP addresses or DNS host names. Configuring IP security modifies the IPSecurity metabase property.

Example Code

The following example shows you how to use the C# programming language to enumerate the IPSecurity property at a node in the IIS metabase, and add a new restriction.

This example requires Windows XP Professional Service Pack 2 or Windows Server 2003 Service Pack 1.

Note

System.DirectoryServices can be used to get and set String and DWORD properties in the IIS metabase, and invoke most methods. However, you cannot set restriction properties unless you are using Windows XP Professional with Service Pack 2 or Windows Server 2003 with Service Pack 1.

To keep this code example concise, it does not include code access security (CAS) parameters or parameter checking. For more information, see Code Access Security and Validating User Input to Avoid Attacks. Additionally, you can instantiate your System.DirectoryServices.DirectoryEntry object with an authentication parameter.

using System;
using System.IO;
using System.DirectoryServices;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Collections;

namespace System_DirectoryServices_DirectoryEntry_ConfigIIS
{
  class Program
  {
    static void Main(string[] args)
    {


...


SetIPSecurityProperty("IIS://localhost/W3SVC", "DomainDeny", "domain.microsoft.com");


...


}


...


static void 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
    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(" Property IPSecurity does not exist at {0}", metabasePath);
        else
            Console.WriteLine("Failed in SetIPSecurityProperty with the following exception: \n{0}", ex.Message);
    }
}


...


  }
}
Imports System
Imports System.IO
Imports System.DirectoryServices
Imports System.Reflection
Imports System.Runtime.InteropServices
Imports System.Collections

Module Program

    Sub Main(ByVal args() As String)


...


End Sub


...


End Module