Monday, October 10, 2011

Defending IIS 7

IIS is secure by default out-of-the-box. But web servers are a combination of components (i.e., network environment, hardware, software, OS, and applications. Making sure IIS and its running applications are secure means checking and hardening a lot of components beyond IIS. This section of the chapter will cover system and IIS hardening recommendations.

Step Summary

Here are the summarized steps that need to be performed to strongly harden an IIS server:
  1. Configure network/perimeter security.
  2. Ensure physical security.
  3. Install updated hardware drivers.
  4. Install operating system.
  5. Configure host firewall.
  6. Configure remote administration.
  7. Install IIS.
  8. Install patches.
  9. Harden operating system.
  10. Configure and tighten IIS.
  11. Secure Web site(s).
  12. Clean and test.
  13. Install and tighten applications.
  14. Conduct penetration tests.
  15. Deploy.
  16. Monitor log files.
Intranet web servers or sites with reduced exposure risk may not need a web server hardened beyond the Microsoft defaults. IIS is very secure out-ofthe-box. However, following these recommended steps will result in a significantly harder-to-attack IIS web server and offer additional defense-in-depth responses if other parts of the web server or defense fail. Now, we'll cover each of those steps in detail.

Configuring Network/Perimeter Security

Before hardening IIS can even begin, an administrator must make sure the network that is installed is safe and secure. The network should be free of rogue software, malicious mobile code, and malicious network sniffers. Any perimeter firewalls or routers should allow only the bare minimum of TCP/IP ports to or from the server. In most cases, that means just allowing TCP port 80 and maybe 443 (for HTTPS) from the Internet to the server. If the web server serves up normal WWW traffic only, the perimeter filters should not allow any other port, except maybe the remote management port, to access the server.
No port traffic should be allowed from the web server to the Internet, by default, unless it is a part of the web server's function. Temporary exceptions may be made for port 80 traffic (for browsing the Web to get patch updates) and port 53 (for DNS queries). However, many Web sites have these ports open from the web server to the Internet all the time, and this is allowing too much access. If a hacker is successful in placing and executing a rogue program, and egress ports are allowed through the filter, the hacker may be able to send a command shell back from the server to his remote location over the open ports.

Ensuring Physical Security

The web server computer should be in a physically secure location. Unauthorized users should not have physical access to the computer. Consider buying a computer that allows physical access to be controlled by a physical mechanism (for example, lock or Smart card). The computer should have a locking case that prevents easy theft of the hard drive.
Unless otherwise contraindicated IIS should always be installed on a dedicated computer. Any IIS server invites increased hacking attempts and makes any computer it is installed on a higher risk of successful exploitation. And any other application may make IIS vulnerable to a side-channel attack.
Prevent booting from anything but the primary boot drive. This will prevent local attacks that attempt to circumvent regular Windows security mechanisms. It will also prevent boot viruses and other types of malware. Disable any unused USB, serial, and printer ports. Then password-protect the BIOS so that the configuration can be maintained. Use a BIOS password that is long and complex, but one that is not the same as your normal admin passwords.

Installing Updated Hardware Drivers

Don't forget to check for and install updated hardware drivers for your computer's BIOS, motherboard, interface cards, video card, and hard drive controller cards. It is the rare computer that arrives with all the drivers updated. It would be a shame for a web server to get exploited or for its data to become corrupt because the server's hard drive controller card had a bug.

Installing an Operating System

To prevent directory traversal attacks, IIS should be installed on a system with two separate, clean hard drives, each formatted with NTFS; or at least create two separate logical volumes. IIS has not been the victim of a directory traversal attack in many years, but in the event that a hacker develops a successful one, having the IIS server software and content installed on one hard drive and the Windows operating system installed on another will prevent future traversal attacks.
Install the Windows operating system as you normally would. Most web servers should be installed as standalone servers, unless the web server will be participating in domain authentications (for example, Windows Authentication). Unless you are dealing with an extranet server, most public facing web servers don't need Active Directory. If Active Directory is accessible through the web server (either because it is a domain member or domain controller), a successful hacker will be able to gather much more information. IIS should never be installed on a Domain Controller.
You want to install the OS with the minimal settings, with the minimal applications, and the minimal services loaded. If possible, load the OS with a static IP address. Dynamic IP addressing might give the hacker a way to exploit the server. Optimally, the web server would not be connected to the network until after all patches were installed.

Configuring a Host Firewall

As soon as the OS is installed, install a host-based firewall on the operating system. You want to protect the web server from remote exploitation. The built-in Windows Firewall is a good choice. It does a fine job at protecting Windows by preventing all inbound connections not initiated by an outbound connection, or by using rule exceptions.
Keep the firewall enabled with no port exceptions until OS and IIS patching have occurred. When the server is ready for operations, enable the firewall for only the port exceptions needed to run the web server. Often these exceptions would be ports 80, 443 (if HTTPS is needed), and a remote management port.

Configuring Remote Administration

While any remote admin tool (PC Anywhere, VNC, and so on) can be used, Remote Desktop is an excellent choice for remote administration on Windows computers. However, because web servers are high risk attack targets, risk can be minimized by making the changes described here.
First, make sure the latest RDP client, which has improved security and authentication, is being used. On the web server, change the default RDP port from TCP 3389 to another number that is random and high. By not running RDP on the default port, it makes it harder for remote attackers to detect and abuse RDP The web server's RDP listening port can be changed using a regedit modification to the HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\ Terminal Server\WinStations\RDP-Tcp value. Change the value to decimal (versus hexadecimal) and input the new port. On the client-side, from which the remote admin is connecting, the RDP client connection string must include a port number at the end of the connection string to connect to indicate the non-default port number used (for example: http://www.example.com:33089). See http://www.support.microsoft.com/?id=187623 for more details.
There are other RDP changes you should make to the Terminal Services (which RDP uses) settings on the web server. Specifically deny access to IIS anonymous user accounts and the anonymous null session. This can be done by adding the related user accounts (or the IIS_IUSRS group) to the "Deny logon through Terminal Services" privilege in the Group Policy or the Local Computer Policy at \Computer Configuration\Windows Settings\Security Settings\Local Policies\User Rights Assignment.
Enable high-level encryption under \Computer Configuration\Administrative Templates\Windows Components\Terminal Services\Encryption and Security\Set client connection encryption level. In the same area, enable "Delete temporary folders on exit, Use temporary folders per session," disable the Active Desktop, set the permission capability to Full Security, and restrict each user to one session.
Force the RDP users to close the session after disconnecting. These options are available in the Terminal Services Configuration console or in an Active Directory domain, under the remote admin user's Sessions tab in their User Account properties.
Enable "Do not allow an initial program to be launched. Always show desktop" in the Terminal Services Configuration console. In the console, disable all mappings except the clipboard under Client Settings.
Once these changes are made, RDP can be confidently used for remote administration of IIS web servers.

Installing IIS in a Minimal Configuration

Install IIS with the default options. IIS needs to be installed so patches can be applied against it. Many patching tools, including Windows Update, WSUS, and other Microsoft patching tools, require that the software they are patching be installed and active before the missing patches can be detected and applied. At the same time, installers need to minimize available attack vectors until after the patches are applied. After hardening the OS and installing patches, any additional IIS functionality needed can be installed.

Installing Patches

Install all OS and application patches, being sure to install service packs before other patches. This may be complicated by the fact that the server may not be connected to the network or a filtering device may be blocking access to Windows Update from the server (as previously recommended). Install as many patches as you can without connecting to the network. In most cases this means downloading OS and IIS patches from another already patched computer and then installing them manually on the server. If you must open port 80 to run Windows Update and download the patches from Microsoft, open only ports 80 and 53 outbound (if needed). Windows Firewall should automatically open the needed ports when needed. Run Windows Update or any other trusted patching tool, install the missing patches (or service packs), and then disconnect. Continue running the patching routine until no more patches are missing. It is not unusual for it to take two or three complete patching cycles.
Administrators may want to consider enabling the Automatic Updates service. If so, AU should download the patches, but never automatically install. Consider installing and using Microsoft Baseline Security Analyzer (MBSA) to check for any missing patches. If not connected to the Internet, you can download MBSA and the latest Mssecure.xml file from another patched machine and manually install and test. Delete any temporary folders used by the patches and reboot the server as required.

Hardening the Operating System

Now is the time to harden the underlying OS. You want to disable or remove any service or feature that is not needed to support the web server, its applications, or its administration. This section will discuss an example scenario demonstrating how to harden a standalone web server needing a bare minimum of services. Web servers with complex requirements (such as down-level client compatibility, domain membership, dynamic content, and so on) will not be able implement all suggestions.
A standalone web server facing the Internet and not needing domain authentication needs only the following services enabled:
  • Application Layer Gateway Service (if Windows Firewall is used)
  • Automatic Updates (if used)
  • Background Intelligent Transfer Service (if used)
  • Basic Filtering Engine
  • COM+ Event Service (if COM objects are used on server; when in doubt, leave enabled)
  • Computer Browser (only if needing to NetBIOS browse or connect to other computer's drives or printers)
  • Cryptographic Services
  • DCOM Server Process Launcher (if Distributed COM objects are used)
  • DHCP Client (if used)
  • DNS Client (if used)
  • Event Log
  • FTP Publishing Service (if used)
  • Group Policy Client (if used)
  • IIS Admin Service
  • IKE and AuthIP IPsec Keying Modules (if IPsec is enabled)
  • IPHelper (if IPv6 is used)
  • IPsec Policy Agent (if IPsec is enabled)
  • .NET Framework
  • .Net.Msmq Listener Adapters (if used)
  • .Net.Pipe Listener Adapters (if used)
  • .Net.Tcp Listener Adapters (if used)
  • .Net.Tcp Port Sharing Service (if used)
  • Net Logon (if authenticated remote domain logons are used)
  • Network Connections
  • Plug and Play
  • Protected Storage
  • Remote Procedure Call (RPC)
  • Security Accounts Manager
  • Terminal Services (if RDP is used)
  • Web Management Service (if remote features are used)
  • Windows Management Instrumentation (if WMI is used)
  • Windows Process Activation Service (WAS)
  • Windows Firewall (if used)
  • World Wide Publishing Service (of course)
Every service should be disabled unless explicitly needed. Uninstall or remove all other non-needed applications and services.
Use Local Computer Policy or Group Policy to obtain the following settings:
  • Set minimum password size to 14 (largest value possible right now).
  • Give 15-character passwords to all custom application pool identity and administrative accounts.
  • Enable password complexity.
  • Enable Account Lockouts (3–5 bad passwords in 1 minute, lock out for 1 minute).
  • Rename the Administrator and Guest accounts.
  • Remove the Everyone and Power Users groups from "Access this computer from the network" user right.
  • Under User Rights Assignment, remove Backup Operators as members of the "Access this computer from the network" user right (unless you do remote backup of the web server).
  • Change Unsigned Driver behavior from Warn to Don't Allow.
  • Enable Message Text for Interactive Logon (just to defeat any bruteforce logon tools).
  • Disable Logon caching.
  • Enable the "Do not allow the anonymous access of SAM accounts and shares" option (although this may disable some remote management tools).
  • Enable the "Do not allow the storage of credentials or Passports for network authentication" option.
  • Enable the "Do not store Lan Man hash value on next password change" option.
  • Change LM Authentication Level to NTLMv2, refuse LM and NTLM (unless you need down-level clients to authenticate using Integrated Windows authentication).
  • Enable the Clear virtual memory page file option (although this will cause long shutdown and bootup times, so measure use against availability concerns).
  • Remove Posix as an optional Windows subsystem.
  • Restrict CD-ROM and floppy drives use to local logged-on users only.
  • Deny Log On Locally right to all members of the IIS_IUSRS group.
  • Enable the "Interactive Logon: Do not display user info" option.
  • Remove DFS$ and COMCFG from file shares that allow anonymous logon.
  • Disable File and Printer Sharing in the Network Configuration dialog box.
Reboot the system and troubleshoot any resulting error messages.

Configuring and Tightening IIS

Now that the OS is hardened, let's turn our attention to IIS. Following are web server-specific changes to make (as compared to Web site changes).

Installing Additional IIS Features

Now is the time to choose which additional IIS features to install. The objective is to install features and modules necessary to support the Web site, and disable or minimize everything else. If features beyond static content are needed,  "Installing IIS 7," again and install the needed IIS components. Choose to install only the options necessary to make your Web site meet its operational requirements. Every additional feature is a potential attack point.

IIS 7 Modules

IIS 7 has broken down key functionality into dozens of task-specific DLL modules. These modules can be loaded and unloaded globally, per Web site, or per application. Remove unused modules. For example, if none of your Web sites will ever use SSL client certificate mapping, you can unload the Authmap.dll. Table 1 shows some of the security modules that can be loaded or unloaded.
Table 1: Sampling of IIS 7 Security Modules Open table as spreadsheet
MODULE NAME
DESCRIPTION
MODULE DLL
AnonymousAuthModule
Performs Anonymous authentication when no other authentication method succeeds.
Inetsrv\Authanon.dll
BasicAuthModule
Performs Basic authentication.
Inetsrv\Authbas.dll
CertificateMapping-AuthenticationModule
Performs Certificate Mapping authentication using Active Directory.
Inetsrv\Authcert.dll
DigestAuthModule
Performs Digest authentication.
Inetsrv\Authmd5.dll
IISCertificateMapping-AuthenticationModule
Performs Certificate Mapping authentication using IIS certificate configuration.
Inetsrv\Authmap.dll
RequestFilteringModule
Performs URLScan tasks such as configuring allowed verbs and file extensions, setting limits, and scanning for bad character sequences.
Inetsrv\Modrqflt.dll
UrlAuthorizationModule
Performs URL authorization.
Inetsrv\Urlauthz.dll
WindowsAuthModule
Performs NTLM integrated authentication.
Inetsrv\Authsspi.dll
You can enable and disable various modules by using the IIS Manager and clicking on the Modules icon (see Figure 1), and then adding and removing the various modules as desired (see Figure 2). Remove all modules not needed to support the Web site and application.
Image from book
Figure 1: Selecting Modules Feature in IIS 7
Image from book
Figure 2: Enabling or disabling specific modules in IIS 7

Minimizing Web Components Even Further

Minimize all web components to the bare minimum set needed. Disable and/or remove unneeded items, including the following:
  • Protocol listeners
  • IIS components
  • IIS handlers
  • IIS handler permissions
  • Authentication methods
  • Providers (which store session states)
  • Scripts, ISAPI filters, and so on
  • MIME types
  • IIS content
Most of these components are configurable in IIS Admin and by directly editing the XML config files. Most settings are configurable on a per web server, per Web site, and per web object basis (to varying degrees). Every component removed is one less attack vector to worry about; plus it saves on management and backup time.

Feature Delegation

Use feature delegation to minimize the number of web server administrators and what each web server administrator can do. Optimally, you would have only one user account able to administrate all Web sites on the server. That account would have a strong password, which was known only to a minimal set of administrators.

Strengthening NTFS Permissions

On dedicated web servers, remove NTFS permissions that are granted to the Everyone group on the root folder of disk volumes supporting web server content. Remove any compilers, development environments, or sample files.
Using Windows Explorer, set Full Control permission to Deny on the \%windir% and %windir%\System32 folders for the IIS_IUSR group. Then add Everyone Deny permissions to the Windows\Temporary Compressed Files, unless web compression is needed. Delete all files in the iisadmpwd folder, if it exists.

Note 
Test this specific recommendation heavily before implementing. Some applications require access to the %Windir%, %Windir%\System32, and Temporary Compressed Files folders in order to function appropriately. Additionally, denying Everyone access could prevent other programs, such as antivirus scanners, from working correctly. Adding this specific deny recommendation is a great defense-in-depth step for many different types of attacks, but may cause operational issues. If in doubt, skip it or temporarily remove it in a troubleshooting scenario.

Configuring Request Filtering

Request Filtering (known as URL Filtering in previous versions of IIS) enables an administrator to define what request string traffic from client machines is and isn't allowed to be processed by their IIS server. Invalid connection traffic is simply dropped. In previous versions of IIS, a separate program called URLScan had to be added to gain full URL filtering capabilities. Now, the functionality is built into IIS 7, although at the moment it can be configured only by editing the web server or Web site XML configuration files directly. A great Request Filtering summary (and URLScan comparison) can be found at http://www.iis.net/default.aspx?tabid=2&subtabid=25&i=1040. At a bare minimum, enable the following filter features:
  • Set UseAllowExtensions to 1. This will enable URL Filtering to deny-by-default any extension not specifically allowed. Then under the AllowedExtensions section, type in only the file extensions needed on the web server. Only content files being downloaded or uploaded need to be added. Be sure to add "." to AllowExtensions (just the period, not the quotes) to cover files that don't end in an extension.
  • Set MaxURL to 70 or some other number that indicates the maximum size of the URL string that your server will accept. You want to prevent overly long URLs, possibly containing buffer overflow or directory traversal attacks, from being uploaded.
  • Set MaxAllowContent Length to 100000 or something acceptable that indicates the maximum size of any single content component. Again, the idea is to prevent unauthorized uploading or downloading.
In URLScan, the Set AllowVerbs feature allowed the admin to determine what HTTP verbs were and weren't allowed to reach the web server. As discussed previously, this functionality has been moved in the Handler Permissions feature (and it can be added manually as well). Using IIS Admin it can be more easily configured on an even more granular basis.
For good security, allow only the GET and HEAD HTTP methods to reach read-only Web sites. Block all other methods. For Web sites that must allow users to modify content, additionally allow the PUT and/or POST methods, as required. The PUT verb is needed for regular HTTP write operations and the POST verb is need for writing done via HTML forms. Unless otherwise specifically needed, block all other verbs.
Here is an example of how an administrator would modify a Application-Host.config file to add Request Filtering:
             


maxAllowedContentLength="10000000"
maxUrl="200"
maxQueryString="35"





allowUnlisted="false"






Securing Web Sites

Now that the overall web server is secured, the following settings should be made to each Web site:

Hardening NTFS Permissions

Do not install any Web sites to \Inetpub\wwwroot. That's where any hacker will look for web files. Instead, install to almost any other randomly created directory. Consider naming the directory something innocuous, like D:\Temp, if you want to fool any local hackers. Most hackers and web server scripts expect Web sites to be in the default locations, so use another directory name and fool many hackers and scripts.
Each web server should have its own web content directories. Each web application pool identity should have only the bare minimum access that it needs to each related content directory. Content directories should be structured to maximize security simplicity. Most administrators structure their Web site directories according to the Web sites' overall linking structure. For example:
\Inetpub\wwwroot
\Inetpub\wwwroot\Examplecom
\Inetpub\wwwroot\Examplecom\Main
\Inetpub\wwwroot\Examplecom\Company Structure
\Inetpub\wwwroot\Examplecom\Mission
\Inetpub\wwwroot\Examplecom\Recruiting
The administrators make subdirectory structures that mimic the linking structure and place all content into common parent directories that describe the Web site's logical structure. Most of the time, all the files in the same folder share the same permissions. This is completely wrong.
Instead, Web site folders should be structured along security lines, so that all content in the same directories truly describes common security permissions. The following code uses the preceding example but improves on it:
\Temp\Web
\Temp\Web\Examplecom
\Temp\Web\Examplecom\HTML content
\Temp\Web\Examplecom\HTML content\Main
\Temp\Web\Examplecom\HTML content\Company Structure
\Temp\Web\Examplecom\HTML content\Mission
\Temp\Web\Examplecom\HTML content\Recruiting

\Temp\Web\Examplecom\Scripts
\Temp\Web\Examplecom\Scripts\Main
\Temp\Web\Examplecom\Scripts\Company Structure
\Temp\Web\Examplecom\Scripts\Mission
\Temp\Web\Examplecom\Scripts\Recruiting

\Temp\Web\Examplecom\Executables
\Temp\Web\Examplecom\Executables\Main
\Temp\Web\Examplecom\Executables\Company Structure
\Temp\Web\Examplecom\Executables\Mission
\Temp\Web\Examplecom\Executables\Recruiting

\Temp\Web\Examplecom\Pictures
\Temp\Web\Examplecom\Pictures\Main
\Temp\Web\Examplecom\Pictures\Company Structure
\Temp\Web\Examplecom\Pictures\Mission
\Temp\Web\Examplecom\Pictures\Recruiting
Although this structure may look unnecessarily complicated at first, it's really simple. In the first example, the administrator would have to manually look at each file in each directory and determine what security it should have. In the latter example, the appropriate permissions can be set at the higher parent directories (such as HTML content, Scripts, Executables, Pictures) and all the related files automatically inherit the correct permissions. It may take a little bit longer to set up, but it saves in overall administration time and ensures greater security. The former model is bound to break down and cause a security issue. The latter structure ensures that good security occurs naturally.
Then using Windows Explorer (for NTFS permissions) and IIS Admin (for IIS permissions), set the bare minimum permissions needed for the Web site to function appropriately. Remember to tie NTFS permissions to the appropriate application pool identity and the appropriate impersonated user account.
Ensure that any IIS-related user accounts (such as IIS_IUSRS, web pool identity, and so on) do not have access to any files or folders that they should not have access to. There is no reason for IIS-related user accounts to have access to most high-risk files and folders. For example, unless there is a legitimate reason for the IIS_IUSRS group to have access to Cmd.exe, http://www.Command.com, or Debug.exe, give the IIS_IUSRS account Deny-Full Control permissions to those files. That way, if an IIS anonymous user account "breaks out" of IIS, the hacker won't be able to readily access the Windows command prompt, as they often attempt to do. This will defeat many hackers and hacking tools. Appropriately set permissions will help increase the security of any Web site.

Web Site IP Settings

Change the IP address of the Web site in the IIS Admin console to be a static private address instead of All Unassigned. This will prevent hackers from using unintended IP addresses to gain unauthorized access to the web server. Install the Web site to a non-default port (nearly anything but ports 80 and 443, as discussed earlier in the section "Configuring Network/Perimeter Security"), if possible. Moving web servers from ports 80 and 443 will do much to decrease the security risk of any affected Web site.

Application Pool Changes

As discussed previously, application pools and their identities should be locked down to just the files and folders they need to allow the Web site to function appropriately. Every Web site needing different security requirements should have its own application pool. Consider creating a custom identity service account, assigning it just the permissions it needs, and assigning it to the application pool.
After making the appropriate changes, stop and restart IIS to let new changes take effect. Then re-run MBSA to check for missing patches.

Cleaning and Testing

When setting up and patching any new computer, there are bound to be temporary files and folders left around. For example, you should delete the \wutemp folder left over by patching. Look for other temporary files and delete them, too. Then empty the Recycle Bin. Then reboot once more. Check error logs after bootup for any messages to investigate.

Installing and Securing Applications

Now for the even harder part: Securing an OS and IIS server is easy compared to installing a secure application. Many penetration experts swear they have never met a secure web application. Applications should be modeled and protected using the Security Development Lifecycle (http://www.msdn2.microsoft.com/en-us/library/ms995349.aspx). There are many books, articles, and classes on this subject. In a nutshell, SDL attempts to anticipate all the threats that are possible against a particular application, and builds in the security defenses as a part of the development lifecycle. SDL makes secure design a key part of the project and makes sure it is not "bolted on" at the end of the project. Every application undergoing SDL review at Microsoft has resulted in significantly fewer vulnerabilities, and the vulnerabilities that were found were less critical in nature.
Coders and the web server administrator should work together to ensure that a secure application gets installed on IIS, and that the bare minimum permissions have been defined and configured as discussed previously.

Conducting Penetration Tests

Open up the appropriate web server ports on the host-based firewall to allow for internal penetration testing. Penetration tests, regardless of whether they use their own wits or automated tools, should test the OS, IIS, and the application. Two good, free web server penetration testing tools are Nessus (http://www.nessus.org) and Nikto (http://www.cirt.net/code/nikto.shtml). Nessus comes in both Linux and Windows versions, and in both free and commercial forms. Nikto is an open source tool that requires Linux or Cygwin (http://www.cygwin.com/) to run in Windows environments. Nessus actually uses Nikto for its web penetration testing. Both products run hundreds of vulnerability tests on web servers. Any noted deficiencies should be corrected before go-live. Lessons learned should be incorporated into future roll outs.

Deploying to Production

Open the appropriate web server ports on the perimeter firewall and expose the Web site to the world. You've done your job well and there is little to worry about. Every Web site can be hacked, but yours should be one that is not easily cracked. You can also open the Web site to external penetration testing if another round of testing is required.

Monitoring Log Files

Last, monitor the firewall and log files located in the centralized log directory. Investigate critical or persistent threats.