Designing a Secure Web Site

for RuBoard

Before we dive into a bunch of code, let's look at our options and take this step by step.

The first step is establishing a Web server. We'll skip the formalities of how to create a development, staging, and production environment and just imagine that they are all in place. One of the tools that is a part of Microsoft's Security Toolkit is URLScan . This ISAPI filter checks incoming requests for a variety of malformations and decides whether to allow the request to proceed or to reject it. Although it is no substitute for keeping up with whatever service packs , hotfixes, or bulletins that are sent out by Microsoft, it is an effective tool at reducing the number of ways potential hackers can get in. URLScan works with IIS 4, 5, and 5.1 and is easy to install and configure.

NOTE

You can get the latest copy of URLScan, as part of the IIS Lockdown Tool, free from the Microsoft Web site. The direct URL is http://www.microsoft.com/Downloads/Release.asp?ReleaseID=33961. The information only Web page is http://www.microsoft.com/technet/security/urlscan.asp. Installation of the URLScan filter is done easily through the IIS Lockdown Wizard. Not only will it set up the configuration file for you based on the type of server you are running (BizTalk, Exchange, and so on), but it also registers the filter with IIS.


The urlscan.ini file stores the configuration for the filter, so from within that file we want to make sure a few things are enabled ”just to make sure. Discretion is always the better side of valor. Table 27.1 shows the values within the urlscan.ini file that we are going to pay special attention to, what their values will be, and why they are set that way.

Table 27.1. Selected urlscan.ini Properties
Property Name Value Reason
UseAllowVerbs 1 This prevents certain kinds of requests from coming through. For this, we will enable GET , POST , and HEAD ”nothing else.
UseAllowExtensions Setting this to 0 means that it will use the settings in the DenyExtensions section of the URLScan.ini file. It is in this section that we will deny access to file extensions to which no user will have access, for example, .asa , .config , and so on.
NormalizeURLBeforeScan 1 Forces normalization (canoncalization) of the URL before determining to allow or deny the request.
VerifyNormalization 1 This just canoncalizes the URL again to make sure nothing changed from the first check (Buffer attacks can happen this way).
EnableLogging 1 Have a log file to find out if any bad requests come though, and who made them.

As shown in Table 27.1 and implemented in Listing 27.1, these settings will be important in securing the ASP.NET application. By setting explicit verbs in the AllowVerbs section, we are preventing actions associated with the HTTP verbs that do not relate to what is explicitly needed by the application. At no point will anything other than GET , POST , or HEAD be used, so get rid of everything else.

In the DenyExtensions section, we can add any variety of file extensions that we do not want the Web server to provide direct access to. In this application, access is going to be denied to any .exe , .dll , .cmd , or .com file located anywhere on the Web server.

CAUTION

The URLScan filter is not directory specific by default; it is server specific. After it's installed, the default behavior is to protect the entire machine. Unless there is some incredibly overwhelming need, there is no need to ever modify this behavior.


Using NormalizeURLBeforeScan , we can prevent attacks associated with malformed URL requests, such as those associated with Nimda and CodeRed. What this does is force a URL to be canonicalized ”that is, fully determined ”prior to attempting to execute the request.

VerifyNormalization is just a double-check on NormalizeURLBeforeScan to make sure that nothing has changed during the canonicalization process. This further protects against buffer overflow attacks.

Finally, EnableLogging is just good practice to see if your server is being attacked and what additional measures, if any, you should take to protect it. Such measures can include further file extension blocking or allowing additional verbs should your site deploy a software package that uses them, such as SharePoint Portal Server.

Listing 27.1 shows the complete urlscan.ini file with generated comments from the IIS Lockdown Wizard. This listing is shown merely as an example of how the urlscan.ini file looks and can be configured. It become important when using the URLScan filter to know what is available for you to change and the consequences of doing so. In this listing, notice the sections that correspond with the items in Table 27.1 and how they are set. Also in this listing, notice the .config addition to the Infrequently User Scripts section. This prevents users from being able to browse your web.config or machine.config file.

Listing 27.1 urlscan.ini ”Complete
 [options] UseAllowVerbs=1 ; if 1, use [AllowVerbs] section, else use [DenyVerbs] section UseAllowExtensions=0 ; if 1, use [AllowExtensions] section, else use [DenyExtensions] graphics/ccc.gif section NormalizeUrlBeforeScan=1 ; if 1, canonicalize URL before processing VerifyNormalization=1 ; if 1, canonicalize URL twice and reject request if a change occurs AllowHighBitCharacters=1 ; if 1, allow high bit (ie. UTF8 or MBCS) characters in URL AllowDotInPath=0 ; if 1, allow dots that are not file extensions RemoveServerHeader=0 ; if 1, remove "Server" header from response EnableLogging=1 ; if 1, log UrlScan activity PerProcessLogging=0 ; if 1, the UrlScan.log filename will contain a PID (ie. UrlScan.123. graphics/ccc.gif log) AllowLateScanning=0 ; if 1, then UrlScan will load as a low priority filter. PerDayLogging=1 ; if 1, UrlScan will produce a new log each day with activity in the form UrlScan.010101. graphics/ccc.gif log RejectResponseUrl= ; UrlScan will send rejected requests to the URL specified here. Default is / graphics/ccc.gif <Rejected-by-UrlScan> UseFastPathReject=0 ; If 1, then UrlScan will not use the RejectResponseUrl or allow IIS to log the request ; If RemoveServerHeader is 0, then AlternateServerName can be ; used to specify a replacement for IIS's built in 'Server' header AlternateServerName= [AllowVerbs] ; ; The verbs (aka HTTP methods) listed here are those commonly ; processed by a typical IIS server. ; ; Note that these entries are effective if "UseAllowVerbs=1" ; is set in the [Options] section above. ; GET HEAD POST ;OPTIONS ; FrontPage Server Extensions requires OPTIONS.  If you need to enable          ; it, uncomment the OPTIONS verb and set "AllowLateScanning=1" in the          ; [Options] section above.  Additionally, after changing this file and          ; restarting the web service, you should go to the "ISAPI Filters" tab          ; for the server's properties in MMC and ensure that UrlScan is listed          ; lower than fpexedll.dll. [DenyVerbs] ; ; The verbs (aka HTTP methods) listed here are used for publishing ; content to an IIS server via WebDAV. ; ; Note that these entries are effective if "UseAllowVerbs=0" ; is set in the [Options] section above. ; PROPFIND PROPPATCH MKCOL DELETE PUT COPY MOVE LOCK UNLOCK [DenyHeaders] ; ; The following request headers alter processing of a ; request by causing the server to process the request ; as if it were intended to be a WebDAV request, instead ; of a request to retrieve a resource. ; Translate: If: Lock-Token: [AllowExtensions] ; ; Extensions listed here are commonly used on a typical IIS server. ; ; Note that these entries are effective if "UseAllowExtensions=1" ; is set in the [Options] section above. ; .asp .htm .html .txt .jpg .jpeg .gif [DenyExtensions] ; ; Extensions listed here either run code directly on the server, ; are processed as scripts, or are static files that are ; generally not intended to be served out. ; ; Note that these entries are effective if "UseAllowExtensions=0" ; is set in the [Options] section above. ; ; Also note that ASP scripts are allowed to run with the below ; settings.  If you wish to prevent ASP from running, add the ; following extensions to this list: ;    .asp ;    .cer ;    .cdx ;    .asa ; ; Deny executables that run on the server .exe .bat .cmd .com ; Deny infrequently used scripts .htw     ; Maps to webhits.dll, part of Index Server .ida     ; Maps to idq.dll, part of Index Server .idq     ; Maps to idq.dll, part of Index Server .htr     ; Maps to ism.dll, a legacy administrative tool .idc     ; Maps to httpodbc.dll, a legacy database access tool .shtm    ; Maps to ssinc.dll, for Server Side Includes .shtml   ; Maps to ssinc.dll, for Server Side Includes .stm     ; Maps to ssinc.dll, for Server Side Includes .printer ; Maps to msw3prt.dll, for Internet Printing Services .config  ; Disables someone trying to browse the web.config file ; Deny various static files .ini     ; Configuration files .log     ; Log files .pol     ; Policy files .dat     ; Configuration files [DenyUrlSequences] ..  ; Don't allow directory traversals ./  ; Don't allow trailing dot on a directory name \    ; Don't allow backslashes in URL :   ; Don't allow alternate stream access %   ; Don't allow escaping after normalization &   ; Don't allow multiple CGI processes to run on a single request 

If you don't believe this is worth the minor effort of installation and configuration, trust me ”it is. Listing 27.2 shows a few actual entries from my Web server's urlscan.log ( urlscan.112401.log ) file for the date that this chapter was written. What is most disturbing about these entries is that patches are available, and the administrators of these site have either chosen to ignore them or do not know that they are sending these kinds of requests. An e-mail was sent to the administrator or Web master for each of these sites. In most cases, the response was an apology. What this shows are requests attempting to access executable files to execute malicious code on the Web server.

Listing 27.2 urlscan.112401.log Entries
 [11-24-2001 - 11:50:27] ---------------- Initializing UrlScan.log ------------ [11-24-2001 - 11:50:27] -- Filter initialization time: [11-20-2001 - 22:45:30] [11-24-2001 - 11:50:27] Client at 209.249.70.152: URL contains extension '.exe', which is graphics/ccc.gif disallowed. Request will be rejected.  Site Instance='1',Raw URL='/scripts/root.exe' [11-24-2001 - 11:50:33] Client at 209.249.70.152: URL contains extension '.exe', which is graphics/ccc.gif disallowed. Request will be rejected.  Site Instance='1', Raw URL='/MSADC/root.exe' [11-24-2001 - 11:50:42] Client at 209.249.70.152: URL contains extension '.exe', which is graphics/ccc.gif disallowed. Request will be rejected. Site Instance='1',Raw URL='/c/winnt/system32/cmd.exe' 

Now that the basics of what requests can and can't come through are covered, it's time to request the certificate for SSL, get it installed, and restart IIS to make sure that any changes made in the urlscan.ini file are active.

NOTE

At this point, knowledge of how to acquire and install certificates for IIS is assumed. If you are unfamiliar with installing certificates, please refer to Chapter 16 in the "More About Certificates ”Options and Installing" section.


At this point, all I have done codewise is create a new C# ASP.NET Web Application in the Visual Studio .NET IDE. This was done to create the directories in IIS and create the template web.config file that we will be modifying throughout the following sections of this chapter. The next step in creating our application is to determine how users will gain access to the site. To determine this, the next few sections center on the different authentication choices provided by ASP.NET.

Authentication Choices

The second step in the process is to determine how to authorize users attempting to access the site. The first thing that the user will do is browse to the URL for this site. At this point, they must be authenticated because there is no mention in the requirements of allowing anonymous access to anything. IIS provides the following options for authentication:

  • Anonymous ”Does nothing for authentication.

  • Basic Authentication ”Nothing is encrypted.

  • Forms-based Authentication ”Encryption depends on settings in web.config file; within IIS, anonymous access is allowed.

  • Digest Authentication ”Hash value is created on the client and sent to the server; the password itself is not sent.

  • Integrated Windows Authentication ”Provides a hash-based exchange between Internet Explorer and Windows. User's password is not sent over the Internet.

Because everything is running on a Windows 2000 network, we will use Integrated Windows Authentication. Why? Integrated Windows Authentication allows us the most secure login available without deploying additional software on the client; it will also enable us to impersonate or delegate quite easily should that become necessary.

Impersonation on this site will further reduce the risk of attack because the code will only execute as the authenticated user. In addition, we have already incorporated some additional security settings for IIS. Even with such advanced technology embedded into the operating system and Web server, the goal remains the same: Keep the data encrypted at all times between the client and the server. It is not possible to stress the importance of this enough. As a general rule, go with this: If you don't want everybody in the known world to see something you are typing, it better be encrypted. Using encryption via SSL is better than relying on the fact that your company is too small for anyone to care about. In addition, the outside world might not necessarily be the biggest concern. Many attacks on information come from within. Listing 27.3 shows the authentication element's value in the web.config file for the SecureOffice site.

Listing 27.3 Authentication Element Setting
 <authentication mode="Windows"/> 

Authorization Choices

Now that we have an authentication mechanism established, it's time to determine who can do or see what is on the site. The choices are File Authorization, where the OS and File ACLs control who can access what, and URL Authentication where access is more controlled by where a user is coming from. Because no administrator really wants to keep track of all the possible IP addresses users could be coming in with from home dial-up accounts, we rely on File Authorization. To enable this, we add an authorization element to the web.config file, and within that add a deny element. Another step we take is the creation of a "SecureOfficeUsers" group . This helps in managing users within the company that have access to the application. Listing 27.4 shows the complete entry.

Listing 27.4 Authorization Element
 <authorization>     <allow roles="KPCRASH\ SecureOfficeUsers"/>     <deny users="?" /> </authorization> 

In Listing 27.4, note the deny element's users attribute value. The ? represents anonymous users, and for this application, they are not allowed to do anything. The configuration options for authorization also enable you to control verbs in relation to users and groups; this is discussed in Chapter 15, "Authorization ”Control Who Is Accessing Your Site." For this site, we rely on the settings in the urlscan.ini file to control the verbs allowed. During the process of authorization, an instance of the WindowsIdentity class is created. Using this class, you can gather information about the user. Listing 27.5 shows a sample of what can be retrieved with our current Web configuration.

Listing 27.5 default.aspx.cs
 using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; using System.Security; using System.Security.Principal; using System.Threading; using System.Net; using System.Security.Permissions; namespace SecureOffice {  /// <summary>  /// Summary description for _default.  /// </summary>  public class _default : System.Web.UI.Page  {   private void Page_Load(object sender, System.EventArgs e)   {    WindowsIdentity wi = (WindowsIdentity)this.User.Identity;    //This is just here to show checking a role.    string wp_InAdmin = User.IsInRole("HOME\ \ Domain Admins").ToString();    //We could also check here to make sure they are in the    //SecureOfficeUsers group, but if they weren't, they would    //not be seeing this page.    //Note, the values that are available through    //the WindowsIdentity    string wi_Name = wi.Name;    string wi_Type = wi.AuthenticationType;    string wi_Auth = wi.IsAuthenticated.ToString();    string wi_Anon = wi.IsAnonymous.ToString();    string wi_Guest = wi.IsGuest.ToString();    string wi_System = wi.IsSystem.ToString();    string wi_Token = wi.Token.ToString();    //Write everything out to a web page.    Response.Write("Principal Value:");    Response.Write("<BR>");    Response.Write("Is in Administrators " + wp_InAdmin);    Response.Write("<BR><BR>");    Response.Write("Identity Values:");    Response.Write("<BR>");    Response.Write("Name: " + wi_Name);    Response.Write("<BR>");    Response.Write("Type: " + wi_Type);    Response.Write("<BR>");    Response.Write("IsAuthenticated: " + wi_Auth);    Response.Write("<BR>");    Response.Write("IsAnonymous: " + wi_Anon);    Response.Write("<BR>");    Response.Write("IsGuest: " + wi_Guest);    Response.Write("<BR>");    Response.Write("IsSystem: " + wi_System);    Response.Write("<BR>");    Response.Write("Token: " + wi_Token);    Response.Write(wi_Name.GetHashCode().ToString());   }   #region Web Form Designer generated code   override protected void OnInit(EventArgs e)   {    //    // CODEGEN: This call is required by the ASP.NET Web Form Designer.    //    InitializeComponent();    base.OnInit(e);   }   /// <summary>   /// Required method for Designer support - do not modify   /// the contents of this method with the code editor.   /// </summary>   private void InitializeComponent()   {    this.Load += new System.EventHandler(this.Page_Load);   }   #endregion  } } 

NOTE

This entire code sample is available for download from the Sams Web site.


At this point, in the real world, we would turn on some basic functionality to show users which files they could see, and allow them to view them. This could be taken many different directions, but the base groundwork has been firmly demonstrated in code listings of this chapter. When SSL is enabled on the site, all data will be encrypted during transit, keeping the chance of a replay attack (see the section, "Possible Attack Scenarios," later in this chapter), from happening.

Channel Options

When your application cannot use Web Services, but has assemblies that will access information via SOAP, .NET makes available the HttpChannel and the TCPChannel classes. These classes encapsulate the functionality necessary to perform secure SOAP transactions over the Internet. ChannelServices are what allow you to send messages back and forth between the client and server, even if they are from the same machine.

HttpChannel

The HttpChannel class combines the HttpClientChannel class and the HttpServerChannel class. This becomes convenient in developing Web sites because messages can be exchanged using the HttpChannel from an .aspx file to gather data necessary to the application. To do this, basically you would have an instance of HttpChannel make a request to a URI, the request would then go through the SOAP formatter, and out to the server via HTTP/HTTPS. The response would come back to the client via HTTP/HTTPS, run back through the SOAP formatter, and be made available to the client's programming logic.

TcpChannel

TcpChannel , like HttpChannel , combines the TCPClientChannel class and the TCPServerChannel class. The main difference is that the TCPChannel class uses binary sockets for data transfer for those wanting to employ a "roll-your-own" means of working with the data. Both classes contain the bindTo property, which allows the channel to attach itself to a specific IP Address on a server. Use of this aids in security through allowing selected channel traffic to only travel on a specified NIC (Network Interface Card).

NOTE

More information regarding the HTTPChannel and the TCPChannel is available in Chapter 16.


A real-world example of where these classes might come into play is in handling the negotiations to get data from a database that might not be exposed to the Internet, or in performing basic authentication to another machine, on another network, in order to call Web services.

Possible Attack Scenarios

In this section, we will touch upon some of the possible attack scenarios behind the reasons for using the combination of security features discussed in the previous sections, as well as some that are not.

Within the world of hacking, there are people that literally have nothing better to do than scan ranges of IP addresses, check which ports are open on them, and determine what they can do on that port. The techniques used to do this are not kept secret; they are published on several Web sites, http://www.hackers.com, for example. Along with this are the very public announcements about security holes found in products such as IIS that spawn a wave of copycats who try to launch attacks on top of someone else's.

One common misperception is that a firewall is bulletproof. Although not having one is just asking for trouble, it is not and cannot be aware of all the software running behind it, nor all the possible security risks associated with them. This is where proactive system administration comes in. Checking the Microsoft Security Web site (http://www.microsoft.com/security) is an excellent resource for keeping track of what's going on with flaws, updates, and fixes available for Microsoft products.

Invalid Data Attack

In this attack, a hacker attempts to gain information or access through adding commands in the URL. An example of this was shown in Listing 27.2, URL='/c/winnt/system32/cmd.exe' . In this attempt, the hacker was trying to take advantage of a buffer overflow, which might execute arbitrary code. By appending the URL with the direct path to where the cmd.exe file might be, the user could then pass information through the request that might execute within that command window. This form of attack is also referred to as a "malformed URL attack." Another example of this is shown in Listing 27.6.

Listing 27.6 Malformed URL Request Example
 URL='/_mem_bin/..%255c../..%255c../..%255c../winnt/system32/cmd.exe' 
Replay Attack

With a replay attack, the attacker uses a program that sniffs and records the network traffic going between a client and a server. With this, the attacker can "play back" the information sent by the client to try and gain access. There are ways to combat this, however ” employing encryption with an adequate (40-bits, at least) key length is one way, provided a timestamp and a TTL setting is used. This prevents playbacks because for the data to be sent back to the server it cannot be decoded. This is made available in .NET through the use of HttpChannel and TCPChannel. These classes enable you to establish secure client/server connections using the CryptStream class to keep the data encrypted while in route. Also, support for SSL is built into the HttpChannel class. Another way is through the deployment of IPSec policies; however, at the time of this writing, IPSec has some performance questions as well as some incompatibility issues with certain firewalls and VPNs.

Brute Force Attack

During a brute force attack, usernames and passwords are guessed until access is achieved, or the hacker gives up. Usually, if a hacker doesn't at least get a username, they can't try the password for that user. This kind of attack is what leads system administrators to rename the administrator account, disable the guest account, and remove WINS bindings from the TCP/IP stack. Most hackers can quickly determine the operating system of a Web server through the request headers. When that is established, you can "test" the common usernames set up for that OS. In Windows, "Administrator," "Guest," and NULL are all popular accounts that hackers try to use to get in. If a hacker does guess an administrator's password, they can then download the entire System Accounts Manager (SAM) database and use a dictionary attack to gain the passwords of everyone on the machine they have attacked.

Preventing brute force attacks is not difficult. The first thing is to create an incredibly hard-to-guess Administrator password. Hint: "Password" is known; they try that. Other rules with passwords have to do with not using any of the following:

  • Your name

  • Pet names

  • Kids' names

  • Significant other's name

  • Common English words

  • Phone numbers

  • Birthdates

If this list has removed all the passwords you can think of, try this: Using a hash algorithm (MD5, SHA-1), think of something that is easy for you to remember. Then take the first 12 characters of the hash and use that. From personal experience, I can tell you that the number of people who don't follow these rules are the majority ”by a lot.

for RuBoard


. NET Framework Security
.NET Framework Security
ISBN: 067232184X
EAN: 2147483647
Year: 2000
Pages: 235

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net