Tag Archives: Configuration

IIS Security – Past and Present

This topic has been covered many times both by Microsoft and non-Microsoft employees. However, I’ve recently been asked what the main features of IIS 7 are and have seen a great deal of misinformation about IIS security on twitter, blog posts and forums.

I think, therefore, the issue deserves yet another look. In this post, I’m going to go over security in the past for IIS and then move on to talk about security features in IIS 7. These are not in any particular order. This post is not meant to diminish the many thoughtful works already created by others – both complimentary and critical. This is just meant to bring the subject back up for discussion again in hopes that you can be properly equipped with the decision making information you may need.

Ghosts of IIS Security Past

The reason for so much misinformation about the current state of security in IIS is likely due to the earned reputation the product had in versions previous to IIS 6.0. A quick search on the web for IIS 5 security vulnerabilities may be like a walk down memory lane for some of the more veteran administrators and IT staff across the globe. The search results are littered with critical vulnerabilities related to buffer overflows, ISAPI extensions, exploits on rarely-used features, or features that were available by a default installation. We are haunted by names like “Code Red” and “Nimda”. I don’t know about you, but those very names send shivers down my spine. I was consulting as a developer and web administrator for a very large property management company when these hit. We were lucky enough to avoid these as we had patched our services. That said, many whom I did business with on a regular basis were not very happy. So, to be clear, I feel the misinformation that is spread today is built on an element of experience with previous versions. Secunia reports 16 advisories and 6 vulnerabilities with IIS 5.  And so started the reputation , perhaps deservedly so, that IIS was not secure unless you really knew what you were doing with security.

Bill Gates was apparently visited by the ghosts of security past, present and future when he laid his head on his pillow January 14th, 2002. I say that because on January 15th, 2002 Mr. Gates sent out the now-famous trustworthy computing memo to every employee at Microsoft.  This set off a major revamp of products from the ground up. Standards were set for test planning and testing. Writing Secure Code was mandatory reading for every Microsoft developer and tester. The results have been staggering.

Security drastically improved in Microsoft products over the years, and IIS was definitely no exception to this. IIS 6 saw 5 security advisories and 4 vulnerabilities reported since 2003. Not to get ahead of myself, but IIS 7 has exactly 1 advisor and 1 vulnerability from Secunia. Compare this against Apache 2.0.x which has had 39 advisories and 23 vulnerabilities (4 of which are still unpatched as of this writing) and Apache 2.2.x which has had 10 advisories and 16 vulnerabilities (2 of which are still unpatched as of this writing) in the same period.  Now I have seen attempts ([1], [2]) to quantify or otherwise explain these numbers further. You can read those articles for yourself and determine how much weight you want to give them. However you skew it, the facts should speak for themselves – IIS has dramatically improved and taken a leadership roll in security in IIS 6 and 7. Our ghost of IIS past still haunts the product’s reputation today, despite obvious strides taken. Even if you feel you like Apache better I think it is only fair to give credit where it is due.

Improvements in IIS 6

The IIS team took the four tenants of Microsoft’s Trustworthy Computing initiative to heart: Secure by Design, Secure by Default, Secure in Deployment and Secure Communication. Since we are already on the next version, I won’t spend a great deal of time talking about the security improvements in the last version other than a brief overview so you know how they relate to changes in our current version, IIS 7.

IIS 6 took vast strides to improve security. During upgrade installations, IIS 6 was disabled by default if the previous server had not been secured by the IIS lockdown tool. The architecture was completely revamped to separate kernel-mode HTTP listening from user-mode application execution. Changes were made to application pools, authentication, access control, encryption and certificate handling, auditing, logging and patch management that made the product far superior to its predecessors. You can find a detailed list of these features on TechNet.  SecurityFocus did a comparison of these features in March of 2004.Server Watch wrote an article in December of 2003. By most accounts, everything accomplished in IIS 6 was a huge step in the right direction.

Despite the massive steps already taken in IIS6, IIS 7 took these all a bit further. Let’s go ahead and investigate these now.

Improvements in IIS 7.x

Customizable Installation

Continuing with the tenant of being secure in deployment, IIS 7 has made installation a wonder to behold. In IIS 6, you could reduce your attack surface by disabling features native to web server. However, these features were still loaded into the process. This carried not only a security factor, but also a performance and memory footprint issue.  IIS 7 has a completely modular architecture. That means that features which you do not want are not only NOT loaded into the process, you can leave the bits for those features off of your disk completely.

Limitable Attack Surface

This is a bit dubious and is essentially part of the customizable installation. By reducing the modules that are available on disk or loaded into a process, you significantly reduce the attack surface for your specialized web servers. If all you intend to do is serve static content with caching and no default documents, you can simply install the static file handler and caching module and leave the rest of the IIS modules off of your server. Additional controls and limitations will also reduce your attack surface and I’ll cover those below.

IUSR account

Anyone who has tried to migrate an IIS installation from one machine to another or attempted to recover your installation on a new machine, previous to IIS 7, has likely run into an issue with the local “IUSR_” account.  IIS 7 now uses a built-in IUSR account that allows you to easily copy your security settings from one machine to the next. This is great news for those using distributed configuration in web farms, recovery, restoration, or replication.

IIS_IUSRS group

IIS 6 introduced the IIS_WPG group. Application pool security identities had to be assigned to this group in order to host the w3wp.exe process. Like the IUSR account, IIS 7 now creates a built-in security group (IIS_IUSRS) and assigns application pool identities to the group automatically. You can find more information about the built-in user and built-in group for IIS 7 on IIS.NET (Understanding the Built-In User and Group Accounts in IIS 7.0).

ASP.NET / IIS Unified Security Architecture

Previous versions of IIS did not provide a unified approach to security with ASP.NET. The IIS 7 unified request pipeline that supports both Windows and non-Windows principals and provides one place to do all authentication and authorization. Apart from simplification and performance improvements, this also reduces the attack surface and allows for greater flexibility in authentication / authorization scenarios with custom modules.

Request Filtering / URL Rewriting

IIS 7.0 includes a request filtering module that is based on the URLScan ISAPI Filter for IIS 6.0. The module helps you tighten security of your Web servers.

The IIS team has also released an add-on URL rewrite module for IIS 7.0, which provides functionality for rule-based URL manipulation. Even though the primary purpose of the URL rewrite module is to rewrite URL paths for requests, the rewrite module can also be used as a security enforcement tool that helps prevent access to Web site content.

Application Pool Identities

On top of Application Pool Isolation, IIS introduces a new security feature in Service Pack 2 of Windows Server 2008 and Windows Vista. It’s called Application Pool Identities. Application Pool Identities allows you to run Application Pools under an unique account without having to create and manage domain or local accounts. The name of the Application Pool account corresponds to the name of the Application Pool.

Kernel mode SSL

The implementation of SSL has changed from IIS 6.0 to IIS 7.0.  On Windows Server 2003, all SSL configuration was stored in the IIS metabase and encryption/decryption happened in user mode (required a lot of kernel/user mode transitions).  On Windows Vista and Windows Server® 2008, HTTP.sys handles SSL encryption/decryption in kernel mode, resulting in up to 20% better performance for secure connections. 

Configuration Improvements

IIS 7.0 allows locking and unlocking configuration settings in various levels and scopes. Locking down configuration means that it cannot be overridden (or set at all) at lower levels in the hierarchy. Unlocking configuration can only be done at the level where it was locked. This is useful, for example, when creating different configuration for different sites or paths, and only some of sites and paths are allowed to override it. Locking can be done at the section level or for specific elements, attributes, collection elements and collection directives within sections.

Dynamic IP Restriction

IIS 7 provides a new module that allows dynamic, temporary IP address restriction. This module prevents brute force attacks and HTTP clients that make unusually high number of concurrent requests or a large number of requests over a short period of time.

Summary

A verbose list of security features in IIS 6 and IIS 7 might be nearly impossible. Apart from the obvious features, there were numerous improvements to code made over these two versions that make the product far more secure than IIS 5 and earlier. That said, this should give you a summary start on information. I’ve listed some reference documents that may help you understand these features better.  In general, I would encourage you to ask questions of the product team and or other users on the IIS.NET forums if you hear something that sounds negative regarding IIS. If the feedback is true, the product team has the benefit of improving the next release. If the feedback is unfounded, the product team has the benefit of helping you find the information you need to make an informed decision.

See Also

IIS cannot start after upgrade to Vista SP1

Some time ago, I tried to start up the IIS Management Console on my Vista machine and I received an exception. After trying a few quick fixes, I gave up. I had several VPC images that I worked from and I didn’t particularly need this machine to work when I had so many others.  However, I’ve been doing a great deal of development on this machine now, and having IIS working is obviously rather handy. So, I tracked down the exception and solved my problem. I thought I’d go ahead and chronical my adventures for anyone else who is having this issue and needs help.

So first of all, the error that was displayed when I started inetmgr was as follows:

---------------------------
Failed to connect
---------------------------
There was an error when trying to connect. Do you want to retype your credentials and try again?
Details:
Creating an instance of the COM component with CLSID {2B72133B-3F5B-4602-8952-803546CE3344}
from the IClassFactory failed due to the following error: 8007000d.
---------------------------
Yes   No
---------------------------

So I thought that this might be a configuration error. I tried to roll back to a known good configuration but appcmd failed with the following exception:

ERROR ( hresult:80070426, message:Command execution failed.
The service has not been started. )

I tried to start the service with a good old fashion iisreset command and the following exception occurred:

Attempting stop…
Internet services successfully stopped
Attempting start…
Restart attempt failed.
The IIS Admin Service or the World Wide Web Publishing Service, or a service dep
endent on them failed to start.  The service, or dependent services, may had an
error during its startup or may be disabled.

Once again, I thought I’d go into the services console and try to start IIS manually. After trying to start it manually, it failed, stating that a dependent service failed. So I looked at Windows Process Activation Services (WAS) and noticed it was stopped. I tried to start it manually and found the following:

—————————
Services
—————————
Windows could not start the Windows Process Activation Service service on Local Computer.
Error 13:
The data is invalid.
—————————
OK �
—————————

So I checked out the event log and found the following four entries:

First Event :

Log Name:      System
Source:        Service Control Manager
Date:          9/21/2008 11:52:00 PM
Event ID:      7001
Task Category: None
Level:         Error
Keywords:      Classic
User:          N/A
Description:
The World Wide Web Publishing Service service depends on the Windows Process Activation Service service which failed to start because of the following error:
The data is invalid.

Second Event:

Log Name:      System
Source:        Service Control Manager
Date:          9/21/2008 11:52:00 PM
Event ID:      7023
Task Category: None
Level:         Error
Keywords:      Classic
User:          N/A
Description:
The Windows Process Activation Service service terminated with the following error:
The data is invalid.

Third Event:

Log Name:      System
Source:        Microsoft-Windows-WAS
Date:          9/21/2008 11:51:59 PM
Event ID:      5005
Task Category: None
Level:         Error
Keywords:      Classic
User:          N/A
Description:
Windows Process Activation Service (WAS) is stopping because it encountered an error. The data field contains the error number.

Fourt Event:

Log Name:      System
Source:        Microsoft-Windows-WAS
Date:          9/21/2008 11:51:59 PM
Event ID:      5036
Task Category: None
Level:         Error
Keywords:      Classic
User:          N/A
Description:
The configuration manager for Windows Process Activation Service (WAS) did not initialize. The data field contains the error number.

I checked through my event logs and realized that this started happening after I had upgraded to SP1. I hadn’t recognized this as the issue because, as I said, don’t typically use IIS on this machine on a regular basis. I decided to go back to my initial assessment that this had to be configuration related. I started doing comparisons between configuration of a pure Vista installation vs a Vista machine with SP1. I found that the schema had changed during the install, but something had been left out.  The schema file was updated to add the configurationHistory configuration section, but a corresponding section definition was not added to the applicationHost.config file.  

Whether this was what was causing the problem or not, I knew this was going to cause a problem. I added the following configuration entry to the applicationHost.config file under the section group for “system.applicationHost”. 

<section name="configHistory" allowDefinition="AppHostOnly" overrideModeDefault="Deny" />

After this I started the WAS service, the World Wide Publishing Service and the IIS Admin Service. I opened up the IIS Management Console and everything was working just fine.

I’m not sure what exactly happened during the SP1 upgrade that caused this file to not be updated, but I’m pleased to report that all things are up and running again.

Accessing Custom IIS 7 Configuration at Runtime

I’ve been working on a series of posts and Webcasts in my “spare time” directed at some of the areas in which I am most frequently asked questions. I am currently working on developing topics dealing with IIS configuration. It seems logical that this would bring me a great deal of questions considering that IIS 7.0 is using a completely different configuration system than it did in previous versions. That said, I wanted to follow up to my Webcast (“Extending IIS Configuration“) with an article, and another webcast dealing with accessing custom configuration data at runtime.

In the webcast, I described how to extend an existing IIS configuration system object. I want to talk a little more about that. In this blog post I will take on four topics:

  1. Give you some warnings that were not provided in the Webcast regarding extending native IIS configuration
  2. Show you how to access your extended configuration data at runtime in a managed-code HTTP module
  3. Describe how to improve the example used in the Webcast in a custom configuration section.
  4. Show you how to access your custom configuration section at runtime in a managed-code HTTP module

Extending Native Configuration Elements

Introduction

I talked with Carlos today to discuss the validity of extending native configuration elements for our own purposes. While there are certainly valid reasons to do this, it doesn’t come without a risk to your application. Any time that you modify a piece of data that was created by another party — Microsoft or otherwise — you run the risk of having your data overwritten or corrupting the data that the other party needs to use. That said, lets revisit the sample that is frequently given in many articles and was reused in my webcast.

Warnings

In our Webcast, we discussed the idea that you could extend a native configuration element simply by creating a new configuration element schema and placing it in our %windir%sytem32inetsrvconfigschema directory. For our example, we created a file named SiteOwner_schema.xml and put the following code into it:

<configSchema>
   
<sectionSchema name=”system.applicationHost/sites”>
       
<attribute name=”ownerName” type=”string”/>
        <
attribute name=”ownerEmail” type=”string”/>
        <
attribute name=”ownerPhone” type=”string”/>    
    </
sectionSchema>
</configSchema>

All we have done is matched the same section schema path as the existing “system.applicationHost/sites” sectionSchema element in our IIS_schema.xml file. We then added schema information for our three new attributes.

This simple step allows us to immediately start adding attributes to our site configuration, and to access that data programmatically, through PowerShell, and through the AppCmd utility. However, you should be aware of a few dangers before you do something of this nature.

The first problem is that many of our native configuration elements have associated “default” configuration elements. For instance, the <site/> element has an associated <siteDefaults/> element. When modifying the configuration schema for <site/> , you should also modify the <siteDefaults/> configuration schema to match. That said, you might consider changing the above sample configuration schema as follows:

<configSchema>
   
<sectionSchema name=”system.applicationHost/sites”>
       
<attribute name=”ownerName” type=”string”/>
        <
attribute name=”ownerEmail” type=”string”/>
        <
attribute name=”ownerPhone” type=”string”/>
    </sectionSchema>    
    <element name=”siteDefaults”>       
       
<attribute name=”ownerName” defaultValue=”undefined” type=”string”/>
        <
attribute name=”ownerEmail” defaultValue=”undefined”  type
=”string”/>
        <
attribute name=”ownerPhone” defaultValue=”undefined” type=”string”/>    
     </element>
</configSchema>

As you can see, in the bolded section above we have now modified the <siteDefaults/> configuration element to match our changes to the <site/> element.  This isn’t the end of the story, however. While changing this might have seemed simple, modifying other elements become much more complex. Consider the fact that when you modify the schema for <application/> elements, there are several places where <applicationDefaults/> are kept. You will find <applicationDefaults/> under both the sites collection definition, as well as under the associated a site element definition. If you modify the application schema definition, you must be sure to edit the schema for both of the applicationDefaults definitions. This gets even more complex if you try to modify the <virtualDirectoryDefaults/> definition. You’ll find that defined three times in the native configuration: under the sites collection definition, under the application element definition, and under the site element definition itself.

You can see how you can quickly start adding complexity to your changes. Making sure that you make changes everywhere you need to becomes all the more risky.

The second problem you may have is that you may not be able to rely on your third-party to keep their schema definition in line with your own expectations. From one minor revision to the next, a configuration schema you may be depending on can change before your very eyes. This becomes a huge issue. Your future installation may need to make many dependency and version checks to decide what schema document to install, and your module may even need to make checks in case the user upgrades the third-party component without installing the upgraded schema. This can get very tricky, to say the least.

The third problem we can run into when we take a dependency on existing configuration is that external code may not behave the way we want it to. For instance, there is no guarantee that utilities and code written to handle those elements will know what to do if it encounters data that it doesn’t expect. Sure, we can cause IIS to validate our changes through schema, but there is no guarantee that the components which handle those elements can take on the challenge of handling the existing data. There is even a good chance that you could cause an Access Violation (read: crash) if the data is not handled properly. There is also a good chance that the components which normally handle those elements may overwrite your custom data.

So before we go on to show you how to access this extended configuration element data, please be warned that it may not be the best solution to your problem. Later in this article, I will describe how to modify our example to give us the same functionality without altering the schema definition of the existing elements.

Accessing Extended Native Configuration Elements at Runtime

Introduction

With the warnings having been fairly posted, I’ll show you quickly how to access your custom configuration data at runtime from an HTTP module. Once you have saved your schema file to the appropriate directory, its time to write the HTTP module. That module is going to be very simple. We need to create a module that uses the PreSendRequestHeaders event. In this event we will get our “system.applicationHost/sites” configuration section, loop through the configured sites looking for the site on which the current HTTP request is executing, and then write HTTP headers out to the client. Just to make sure that our sample is working, we’ll wrap it up by adding JavaScript to an HTML page that will request the headers from the Web site and display them in a message box.

Getting Started

For this sample, I used Visual Studio 2008, but you can use plain old notepad and command-line compilation if your are feeling particularly froggy.

Visual Studio 2008 Walk-through

The following walk-through will create an HTTP module that can display the site owner details of the configuration system

  1. Click on the File | New | Project …  menu item.
  2. In the “Project types” tree on the left, drill down to the C# | Windows tree element
  3. In the “Templates” selector on the right, select the “Class Library” template
  4. Change the Name of the project to “SiteOwner
  5. Change the Location to “c:samples”
  6. Verify that the “Create directory for solution” checkbox is checked
  7. Click OK
  8. Click on the Project | Add Reference … menu item.
  9. Under the .NET tab, select the component with the Component Name of “System.Web
  10. Click OK
  11. Rename the “Class1.cs” file in the Solution Explorer to “SiteOwnerHeaderModule.cs
  12. Paste the following code in “SiteOwnerHeaderModule.cs” file:
    using System;
    using System.Web;
    using System.Web.Hosting;
    using Microsoft.Web.Administration;
    using System.Collections.Specialized;

    namespace SiteOwner
    {
       
    public class SiteOwnerHeaderModule : IHttpModule {
           
    public void Dispose() {}
           
    public void Init(HttpApplication context) {
               
    context.PreSendRequestHeaders += new EventHandler(OnPreSendRequestHeaders);
           
    }
           
    void OnPreSendRequestHeaders(object sender, EventArgs e){
                // Get the site collection

               
    ConfigurationSection section =
                   
    WebConfigurationManager.GetSection(“system.applicationHost/sites”);
               
    ConfigurationElementCollection cfgSites = section.GetCollection();
                HttpApplication app = (HttpApplication)sender;
                HttpContext context = app.Context;
                // Loop through the sites to find the site of 
                // the currently executing request
               
    foreach (ConfigurationElement cfgSite in cfgSites) {
                   
    if (HostingEnvironment.SiteName == (string)cfgSite.GetAttributeValue(“name”)) {
                        // This is the correct site, get the site owner attributes
                       
    SiteOwner siteOwner = new SiteOwner(cfgSite);
                       
    NameValueCollection headers = context.Response.Headers;
                       
    headers.Add(“Site-Owner-Name”, siteOwner.Name);
                       
    headers.Add(“Site-Owner-Email”, siteOwner.Email);
                       
    headers.Add(“Site-Owner-Phone”, siteOwner.Phone);
                       
    break;
                   
    }
               
    }
           
    }
       
    }
       
    class SiteOwner {
           
    public string Name { get; set; }
           
    public string Email { get; set; }
           
    public string Phone { get; set; }
           
    public SiteOwner(ConfigurationElement site) {
               
    this.Name = site.GetAttributeValue(“ownerName”) as string ;
               
    this.Email = site.GetAttributeValue(“ownerEmail”) as string ;
               
    this.Phone = site.GetAttributeValue(“ownerPhone”) as string;
           
    }
       
    }
    } 

  13. Click the File | Save menu item.
  14. Right-click the SiteOwner project in the Solution Explorer window and select Properties from the menu
  15. Click the Signing tab
  16. Check the Sign the assembly checkbox
  17. Select “<new>” from the Choose a strong name key file dropdown box
  18. Type “KeyFile” in the Key file name box
  19. Uncheck the checkbox labeled Protect my key file with a password
  20. Click OK
  21. Click the File | Save SiteOwner menu item
  22. Click the Build | Build SiteOwner menu item.

Notepad.exe and Command-line Walk-through

The following walk-through will create an HTTP module that can display the site owner details of the configuration system. This walk-through assumes that you have the Microosft .NET Framework SDK or Windows SDK installed. These include the C# compilers needed to build. For more help on building with csc.exe, see “Command-line building With csc.exe

  1. Paste the code from step 10 of the Visual Studio .NET 2008 walk-through into a new notepad instance
  2. Click File | Save As
  3. Browse to the “C:samples” folder if it exists; create the folder if it does not
  4. Type “SiteOwnerHeaderModule.cs” in the File name box
  5. Click the Save button
  6. Open a new SDK Command Prompt (Windows SDK) or Visual Studio Command Prompt (Visual Studio 2008).
  7. At the command prompt type:
    csc.exe /target:module /out:SiteOwner.netmodule /debug /r:System.Web.dll /r:%windir%system32inetsrvMicrosoft.Web.Administration.dll SiteOwnerHeaderModule.cs
  8. Press ENTER then type:
    sn.exe -k keyfile.snk
  9. Press ENTER then type:
    al.exe /out:SiteOwner.dll SiteOwner.netmodule /keyfile:keyfile.snk

Deploying Your HTTP Module

Once you have built your assembly using either Visual Studio 2008 or csc.exe, its time to deploy it to your system. This sample assumes that you don’t want all of your customers to have to install this same component to each Web site, so we’ll install it as a default module on the system.

Registering the Assembly in the GAC

To do this we first need to copy the assembly file(s) to the target system, and register them in the Global Assembly Cache. Using your preferred method to copy the files, copy the SiteOwner.dll (and SiteOwner.netmodule if you used command-line compilation) to the %windir%system32inetsrv directory on the target installation machine. Next open up a command prompt and type:

gacutil -i %windir%system32InetSrvSiteOwner.dll

Now you’ll need to get a copy of the “Public Key Token” for the assembly so that you can install this “strong-named assembly” module in IIS. To do this open up your %windir%assembly directory in Windows Explorer. Scroll down to the SiteOwner “file” in that window and copy the “Public Key Token”. You can do this easily by right-clicking the “file” and selecting Properties from the menu. Double click on the Public Key Token to select the entire contents, then right click the highlighted text and select Copy from the menu.

image

Installing the Module as a Default Module in IIS 7.0

Now that you have your assembly registered and your Public Key Token copied, its time to add this module to all the Web sites on your IIS 7.0 server. To accomplish this, open up your %windir%system32inetsrvconfigapplicationHost.config file in notepad. Scroll down near the bottom of the file to the default location path that looks something like this:

<location path=”” overrideMode=”Allow”>

Inside of that element scroll down to the <modules> element under the <system.webServer> section. You should find a number of modules already listed. To add yours, simply scroll to the bottom of the list and type the following:

<add name=”SiteOwner” type=”SiteOwner.SiteOwnerHeaderModule, SiteOwner, Version=1.0.0.0, Culture=neutral, PublicKeyToken=” />

Once you have typed this line in, you can paste your Public Key Token in right after “PublicKeyToken=” in the line you just typed. Save the applicationHost.config file.

Testing the Module

Choose a Web site on your server to test your application. If you want to run this module for files other than ASP.NET files, you’ll need to choose a Web site running in Integrated Pipeline. For our sample, we are going to make an HTML file to test our code. Our HTML file will contain some JavaScript that will get the headers from the server and display them in a message box. We could use a number of diagnostic tools to do this same work, but this will serve our purposes.

Open up Notepad and paste the following markup into it:

<html>
<body>
<script language=”JavaScript” type=”text/javascript”>
<!–
var req = new ActiveXObject(‘Microsoft.XMLHTTP’);
req.open(‘HEAD’, location.href, false);
req.send();
alert(req.getAllResponseHeaders())
//–>
</script>
</body>
</html>

Save the file to the physical root of the Web site you wish to test. Type in the corresponding URL to your test file in your web browser. Your result should be a JavaScript alert that looks something like the following:

image 

You’ll notice in my results, I have already set the Site’s ownerName attribute. (see the Webcast titled “Extending IIS Configuration” to see how).

Improving our Sample

Introduction

As I stated earlier in this post, this demonstrates something that is definitely possible, but somewhat risky to do. We now want to improve our sample to limit our dependencies on native and/or third-party configuration schema definitions, and prevent us from encroaching on another module’s configuration territory. In concept, what we will do is move our configuration data to its own configuration section and use the site’s ID to allow us to map the data from the site collection to our configuration section.

Modifying the Schema

First, you’ll want to remove the custom site owner configuration data from the site nodes. Otherwise, once we modify the schema, the configuration will not validate. Once you’ve removed that data open the SiteOwner_schema.xml file in notepad and change it to the following:

<configSchema> 
   
<sectionSchema name=”system.applicationHost/siteOwner”> 
       
<collection addElement=”site”> 
       
<attribute name=”id” type=”uint” required=”true” isUniqueKey=”true” />
            <
attribute name=”ownerName” type=”string” /> 
            <
attribute name=”ownerEmail” type=”string” /> 
            <
attribute name=”ownerPhone” type=”string” /> 
        </
collection> 
   
</sectionSchema> 
</configSchema>

Save the file in the same location as you did previously. Now we need to tell the applicationHost.config file about our new section schema. To do this, we add a new section declaration underneath of the system.applicationHost sectionGroup in the applicationHost.config file.

<sectionGroup name=”system.applicationHost”>
    …
    <section name=”siteOwner” allowDefinition=”AppHostOnly” overrideModeDefault=”Deny” />
    …
</
sectionGroup>

Next we need to modify our HTTP module to read from the new configuration section:

using System;
using System.Web;
using System.Web.Hosting;
using Microsoft.Web.Administration;
using System.Collections.Specialized;

namespace SiteOwner{
   
public class SiteOwnerHeaderModule : IHttpModule{
       
public void Dispose() { }
       
public void Init(HttpApplication context){
           
context.PreSendRequestHeaders
               
+= new EventHandler(OnPreSendRequestHeaders);
       
}
       
void OnPreSendRequestHeaders(object sender, EventArgs e){
           
// Get the site collection
            ConfigurationSection section = 
                WebConfigurationManager.GetSection(“system.applicationHost/sites”);
           
ConfigurationElementCollection cfgSites = section.GetCollection(); 
            HttpApplication app = (HttpApplication)sender;
            HttpContext context = app.Context;

           
// Loop through the sites to find the site of 
            // the currently executing request
            foreach (ConfigurationElement cfgSite in cfgSites){
                if (HostingEnvironment.SiteName == (string)cfgSite.GetAttributeValue(“name”)){
                   
// This is the correct site, find the associated
                    // Site Owner record in our custom config section
                    SiteOwner siteOwner = SiteOwner.Find((long)cfgSite.GetAttributeValue(“id”));
                   
if (siteOwner != null) {
                       
// Add the headers if we found a matching
                        // site owner record configured
                        NameValueCollection headers = context.Response.Headers;
                       
headers.Add(“Site-Owner-Name”, siteOwner.Name);
                       
headers.Add(“Site-Owner-Email”, siteOwner.Email);
                       
headers.Add(“Site-Owner-Phone”, siteOwner.Phone);
                   
}
                   
break;
               
}
           
}
       
}
   
}
   
class SiteOwner{
       
public string Name { get; set; }
       
public string Email { get; set; }
       
public string Phone { get; set; }
       
public SiteOwner(ConfigurationElement owner){
           
this.Name = owner.GetAttributeValue(“ownerName”) as string;
           
this.Email = owner.GetAttributeValue(“ownerEmail”) as string;
           
this.Phone = owner.GetAttributeValue(“ownerPhone”) as string;
       
}
       
public static SiteOwner Find(long siteId){
             // Find the matching siteOwner record for this siteId         
           
ConfigurationSection section = 
                        WebConfigurationManager.GetSection(“system.applicationHost/siteOwner”);
           
ConfigurationElementCollection cfgSiteOwners = section.GetCollection();
           
foreach (ConfigurationElement cfgOwner in cfgSiteOwners) {
               
if (siteId == (long)cfgOwner.GetAttributeValue(“id”)){
                   
return new SiteOwner(cfgOwner);
               
}
           
}
           
return null;
       
}
   
}
}

 

There isn’t much changed in this compared to the last. The difference, apart from a few code comments, is that I’ve modified the OnPreRequestHeaders function to get the current site ID, and pass that into the static SiteOwner.Find function. Then I modified the SiteOwner.Find function to read from our new configuration section. Please note that production code would likely set SiteOwner to extend from ConfigurationElement, and a special ConfigurationSection would be developed. Go ahead and compile and deploy this assembly the same way you did with the previous version. Make sure that you run gacutil on the new assembly once it is copied. Also, since we are running against a static HTML file, you might need to run iisreset.exe from a command-line in order to clear the cache from the server.

Once you have deployed your assembly and the schema file, its time to test the application. If we refresh our Web page, we will get a JavaScript alert without any site owner headers listed:

image

This is because we haven’t created any site owner configuration entries yet. So lets add a record directly to our config. I added the following configuration directly after the <sites> node in the applicationHost.config file:

<siteOwner>
   
<site id=”1″ ownerName=”Tobin Titus” ownerEmail=”tobint@microsoft.com” ownerPhone=”555-121-2121″ />
</
siteOwner>       

Save your file and refresh your Web browser. You should now see your site owner configuration data.

image

Conclusions

In this blog post, we’ve walked through extending existing IIS configuration objects, and accessing the custom data at runtime through an HTTP module. We’ve also talked about the risks of this approach and have demonstrated a better approach. This approach gives us the same ability to customize our IIS 7.0 configuration system, but gives us a much smaller dependency on the native configuration schema. We have little worry about schema changes, we don’t have to worry about other modules or utilities stomping on our custom data, and most importantly, we are far less likely to cause any Access Violations with the later approach. 

Many thanks go to Carlos once again for his help in putting this post together as well as for his CodeColorizer plug-in for Live Writer. High-fives and cookies in his office!