Tuesday, May 21, 2013

Restricting Access By Location in IIS

A customer and I were reviewing their web logs and remarking on how many hits were coming in from countries with which they don't even remotely do business. There were several visits each day from China, Russia, Korea, etc. If they were coming to the site, they were either seriously lost or just up to no good.

We decided to restrict access to those folks that just shouldn't be there. Here is how we did it:

First, we are using IIS7. If you are using a Unix flavor, you need to modify your .htaccess file in the /etc directory. If you are on IIS, there is a similar procedure. You will be modifying the following file:


Open this file on your IIS Server and search for

location path=
until you find the web instance you want to apply these settings to.

Next you want to get this file: http://ip-to-country.webhosting.info/downloads/ip-to-country.csv.zip This file is a list of IP addresses by country code.

The last thing to download is this excellent javascript file built by Kanwaljeet Singla. It parses the ip-to-country file into commands you can use in the applicationHost.config file. Once you have the file, rename it to: ipres.js

When you have everything, put it into a folder and pop open your command prompt and go to that directory. Here are a few interesting commands that Kanwaljeet built in:

 // Generate an "allow" list for USA IP addresses
cscript.exe //nologo ipres.js /f ip-to-country.csv /a USA
 // Generate an "deny" list for China IP addresses
cscript.exe //nologo ipres.js /f ip-to-country.csv /d China

So, here is how I got the website to deny anything but United States IP addresses:

  1. Ran the utility above with the command:
    cscript.exe //nologo ipres.js /f ip-to-country.csv /a USA > usa.txt

    This created a file called usa.txt

  2. Opened usa.txt in notepad and copied the text between
    <ipSecurity allowUnlisted="false">
    and the last "add" entry
  3. Opened the ISS ApplicationHost.config file mentioned above in notepad.
  4. Pasted the entire section into the system.webServer/Security section. I also added a special entry that allows me to access the site locally:
    <add ipAddress="" subnetMask="" allowed="true" />
  5. Recycled the Application Pool with that website and voila!
Great credit goes to Kanwaljeet Singla for his cool tool.

No comments:

Post a Comment