Search code examples
iisfirewallwindows-server

How to configure IIS IP Blocker programmatically


is there a simple way to add IP to the restriction list in IIS IP and Domain blocker programmatically, at best from within ASP.NET code?


Solution

  • As suggested by @kev you need to use the Windows Management Instrumentation (WMI) and Active Directory Service Interfaces (ADSI).

    below are some ways to block IP by programmatically:

    1)

    using System;
    
        using System.Text;
        using Microsoft.Web.Administration;
    
        internal static class Sample {
    
            private static void Main() {
    
                using(ServerManager serverManager = new ServerManager()) { 
                    Configuration config = serverManager.GetWebConfiguration("sitename");
    
                    ConfigurationSection ipSecuritySection = config.GetSection("system.webServer/security/ipSecurity");
                    ipSecuritySection["allowUnlisted"] = false;
    
                    ConfigurationElementCollection ipSecurityCollection = ipSecuritySection.GetCollection();
    
                    ConfigurationElement addElement = ipSecurityCollection.CreateElement("add");
                    addElement["ipAddress"] = @"192.168.2.50";
                    ipSecurityCollection.Add(addElement);
    
                    ConfigurationElement addElement1 = ipSecurityCollection.CreateElement("add");
                    addElement1["ipAddress"] = @"192.168.2.52";
                    ipSecurityCollection.Add(addElement1);
    
                    serverManager.CommitChanges();
                }
            }
        }
    

    2)

    using System;
    using System.IO;
    using System.Collections;
    using System.DirectoryServices;
    using System.Reflection;
    
    
    namespace soccerwrek
    {
     class IISWMI
     {      
    
      [STAThread]
      static void Main(string[] args) 
          {
             try
             {
                // retrieve the directory entry for the root of the IIS server
    
                System.DirectoryServices.DirectoryEntry IIS = 
                   new System.DirectoryServices.DirectoryEntry(
                   "IIS://localhost/w3svc/1/root");
    
                // 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);
    
                // display what was being denied
                foreach(string s in origIPDenyList)
                   Console.WriteLine("Before: " + s);
    
                // check GrantByDefault.  This has to be set to true, 
                // or what we are doing will not 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)
                {
                   typ.InvokeMember("GrantByDefault", 
                          BindingFlags.DeclaredOnly | 
                          BindingFlags.Public | BindingFlags.NonPublic | 
                          BindingFlags.Instance | BindingFlags.SetProperty, 
                          null, IPSecurity, new object[] {true});
                }
    
                // update the list of denied IPs.  This is a 
                // complete replace.  If you want to maintain what
                // was already being denied, you need to make sure 
                // those IPs are in here as well.  This area
                // will be where you will most likely modify to
                // your needs as this is just an example.
                Console.WriteLine("Updating the list of denied IPs.");
                object[] newIPDenyList = new object[4];
                newIPDenyList[0] = "192.168.1.1, 255.255.255.255";
                newIPDenyList[1] = "192.168.1.2, 255.255.255.255";
                newIPDenyList[2] = "192.168.1.3, 255.255.255.255";
                newIPDenyList[3] = "192.168.1.4, 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 to see if the update took
                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());
             }
      }
     }
    }
    

    You could refer this links for more detail:

    https://social.msdn.microsoft.com/Forums/vstudio/en-US/f6580aaf-ed47-4bb1-b976-6108595b8dfb/block-ip-in-windows-through-c?forum=csharpgeneral