Iis – Configure IIS to return 404 for directory browse attempts

asp.netiis

In IIS (6 or 7), when Directory Browsing is disabled, IIS returns a "403 – Forbidden" error when it detects an attempt to browse a directory (eg "http://mydomain.com/folder").

Is there any way to configure IIS to return a "404 – Not Found" error instead of a "403" for directory browse attempts? A security scan of our site noted that returning "403" could assist a malicious person mapping our site; had not thought of that before, but I have to admit it makes sense.

This is an asp.net webforms site.

This question has been asked (Replace IIS 403 with 404 for Directory Listing) but the only posted answer is not correct. Adding a custom error page does not work.

Best Answer

I could not find a way to configure IIS, but I did find a workaround using an asp.net generic handler (http://forums.asp.net/p/1478217/3453189.aspx, scroll down to the answer by gvlahakis).

First, create a generic handler that returns 404:

public class DirectoryBrowsingAttempt : IHttpHandler
{
    public bool IsReusable {get {return true;}
    public void ProcessRequest(HttpContext context) {context.Response.StatusCode = 404;}
}

Second, add tags to the web.config to point directory browsing attempts to the above handler, one for each folder that you need to protect, in both the httpHandlers and system.webServer sections. The tags below protect a folder named "js" off of the root.

<httpHandlers>
  <add verb="*" path="js/*" validate="false" type="MyNameSpace.DirectoryBrowsingAttempt"/>
</httpHandlers>
<system.webServer>
<handlers>
  <add name="NoAccess" verb="*" path="js/*"  preCondition="integratedMode" type="MyNameSpace.DirectoryBrowsingAttempt"/>
</handlers>

This workaround behaves differently in IIS 6 vs. IIS 7. For example, I protected a folder that contained the site's images in this manner: IIS 6 still delivered the images contained in this folder to web pages (the desired behavior, I just want to block directory browsing attempts); IIS 7 blocked them.

There are probably ways to use the "location" tab in the web.config to allow images to be served up by overriding the default image handler, but I've no desire to go that far down the rabbit hole.