Attributes and Settings

for RuBoard

With respect to ASP.NET, there are several elements made available to you inside the system.web element. Table 20.1 shows a list of these elements and the attributes and/or subtags associated with them. Each element, unless otherwise noted, is explained following the table. A subtag simply refers to an element that supports a higher-level element; it may have its own subtags and attributes as well. This does not mean that all of the listed elements are required by any stretch, this is only illustrating the possibilities. Please note that, as indicated, these values are all case sensitive and are shown in proper case.

Table 20.1. system.web Elements
Possible Element Attributes and Subtags
<authentication> mode attribute is required, possible values are Windows , Forms , Passport , and None . Subtags depend on mode's value; <forms> and <passport> are available.
<authorization> No attributes. Has subtags of <allow> and <deny> . These subtags each carry the attributes of users , verbs , and roles .
<browserCaps> No attributes. Has subtags of <use> , <filter> , and <result> .
<clientTarget> No attributes. Has subtags of <add> , <clear> , and <remove> .
<compilation> Has attributes of debug , defaultLanguage , explicit , batch , batchTimeout , maxBatchGeneratedFileSize , maxBatchFileSize , numRecompilesBeforeApprestart , strict , and tempDirectory . Has subtags of <compilers> and <assemblies> .
<customErrors> mode attribute is required, defaultRedirect attribute is optional. Has the <error> subtag.
<globalization> Has the optional attributes of requestEncoding , responseEncoding , fileEncoding , culture , and uiCulture .
<httpHandlers> No attributes. Has subtags of <add> , <remove> , and <clear> .
<httpModules> No attributes. Has subtags of <add> , <remove> , and <clear> .
<httpRuntime> Has optional attributes of appRequestQueueLimit , executionTimeout , maxRequestLength , minFreeLocalRequestFreeThreads , minFreeThreads , and useFullyQualifiedRedirectUrl .
<identity> Has three attributes ” impersonate , userName , and password .
<iisFilter> No attributes. Used only for Windows Management Interface (WMI).
<machineKey> Has three required attributes ” validationKey , decryptionKey , and validation .
<pages> Has six optional attributes ” buffer , enableSessionState , enableViewState , pageBaseType , userControlBaseType , and autoEventWireup .
<processModel> Has 22 optional attributes, all related to the configuration of IIS properties that are currently manageable through the IIS MMC. .NET's managed code system does not read these settings, so the server must be restarted for any changes to go into effect here. This element is not used under IIS 6 and is not discussed in this chapter. For more information, see the .NET Framework SDK documentation.
<securityPolicy> No attributes. Has the subtag of <trustLevel> .
<sessionState> Has a required attribute of mode. Has optional attributes of cookieless , timeout , stateConnectionString , and sqlConnectionString .
<trace> Has two optional attributes, autoflush and indentsize .
<trust> Has the required attribute of level and an optional attribute of originUrl .
<webServices> No attributes. Has subtags of <protocols> , <serviceDescriptionFormatExtensionTypes> , <soapExtensionTypes> , <soapExtensionReflectorTypes> , <soapExtensionImporterTypes> , and <wsdlHelpGenerator> .

The <authentication> Element

In short, the authentication element is used to define how users are authenticated within a particular application. As for hierarchy, authentication must be initially set at the root level of an application. All subdirectories will then inherit these settings unless explicitly overridden. Depending on what you set the value of the mode attribute to will define which subtags follow. As shown in Table 20.1, the possible values are Windows , Forms , Passport , and None . By setting the value to Windows , the CLR will invoke an instance of the WindowsAuthenticationModule , which is an authentication provider. This provider relies on IIS to provide the correct authentication information. Hence, its availabilities and limitations are that of IIS ”Anonymous, Basic authentication, Integrated Windows authentication, and Digest authentication. This method of authenticating users provides quite a great deal of information because an instance of the WindowsPrincipal class is created and added to the application context. All of the information contained in the NTFS ACL is then available to your application. This information is exposed in the WindowsPrincipal class through the Identity property and through the IsInRole method. Just as they sound, the Identity property will return the currently authenticated username for a context. The IsInRole method will return a Boolean indicator regarding the user's membership in a specific Windows user group . Windows authentication is the default method of authentication within the .NET Framework.

The next available value in the list is Forms . Setting the mode value to Forms provides a simple, yet reasonable secure means by which to authenticate users.

NOTE

It cannot be said enough that with all of the information given in this book, almost all of this should still be used in combination with SSL.


Using Forms authentication has all the makings of being the most widely used form of authentication available in .NET. It relies on information stored in the web.config file, not IIS. It does not require information to be stored in a relational database, and it does not require an operating system account for each user.

Forms authentication has its own attributes and subtag as well. After you have selected to use Forms authentication, the next step is to set the name attribute to a unique name for the cookie that will be used to store the user information. This can be any valid string of text, but by default is .ASPXAUTH . Obviously, if you plan to run more than one application from the same server, this value should be changed. The next attribute is log inUrl . This value represents a placeholder for the URL to redirect a user to where either no cookie is detected or invalid credentials have been given.

After that, there is the protection attribute. It has four possible values ” All , None , Encryption , and Validation . The None option does exactly what it sounds like ”nothing. This option leaves user information invalidated and unencrypted in a plain-text cookie; this is not a secure option under any circumstances. The Encryption option encrypts the cookie using either DES or Triple-DES (3DES). This decision is made based on the security-level available to the server. For example, if your server is running 128-bit encryption, you will have use of 3DES; otherwise, DES will be used. While this option does encrypt the data, it does not necessarily prevent such events as a plain text attack where a hacker has used a dictionary attack to determine what the user information inside the cookie is. To help with this is the Validation option. This option uses a Message Authentication Code (MAC) to generate a message that is appended to the user cookie. The purpose of this is to validate that the cookie has not been altered in transit. ASP.NET takes care of checking that entire process out for you when the user returns. The final option uses all of the above except for the None option. Setting this attribute to All will encrypt the data in the cookie and validate it automatically. This, in conjunction with SSL, provides a reasonably secure means of authentication.

After you have chosen the level of protection to use, you may optionally decide to set the timeout attribute. By default, this value is set for 30 minutes and represents the amount of time that can elapse between user requests and when the cookie will expire.

The final attribute is that of path . As in most cases related to cookies, path sets where the cookie is stored. The default value is \ . Keep in mind that modern browsers are case sensitive when it comes to cookie paths and may not send the cookie back on a request with an invalid path.

The subtag of forms is <credentials> . This element is used for defining from where the passwords are going to come. As stated earlier, you do not need a relational database or other file to store user credential information in, but if you are going to, this is where you tell ASP.NET where to find it. credentials has one required attribute and that is passwordFormat with possible values of Clear , MD5 , and SHA1 . The value of passwordFormat defines which hashing algorithm is used to encrypt the passwords given. If you plan to use this element, keep in mind that the passwords must also be stored in one of these formats as well.

Next in our list is Passport . Passport authentication requires that you have a subscribed as a valid passport site. Specific information on how to do this can be found at http://www.passport.com/business. Once established, Passport authentication works very similar to Forms authentication, only you are using the Passport server to validate credentials and return a PassportAuthenticationModule to your server. After you have this module, you can derive the same IPrincipal class that the WindowsPrincipal class, previously mentioned, is drawn from and have access to that user's information. The passport element has one required value, redirectUrl . This serves the same purpose as that of log inUrl under Forms authentication.

The final option, None , is exactly that ”no authentication of any kind is performed for any resource.

For code samples and detailed information regarding using the authentication element, refer to Chapter 14, "Authentication: Know Who Is Accessing Your Site."

The <authorization> Element

The authorization element notifies ASP.NET who is or is not allowed to perform certain actions on a particular site. There are two subtags available ” <allow> and <deny> . Within these two subtags are two optional attributes, users and roles . The users attributes represents any valid users, where user is a name derivable from the Principal class or Request.ServerVariables("AUTH_USER") , and if it is an NT logon name, it should be expressed as DOMAIN\USERNAME . In addition to this, there are two wildcards that can be used ”question mark ( ? ) and the asterisk ( * ). Setting the users value to * will affect all users; setting it to ? will affect anonymous users.

The next attribute available is roles. The roles attribute relates expressly to groups that have been created within the domain or machine. An example of this might be the Administrators group or VS Developers .

The allow element also has a verbs attribute. A verb in this case is an action that can be performed against the Web server. ASP.NET recognizes four verbs ” GET , POST , DEBUG , and HEAD .

Although not an incredible amount of options, the potential combinations here are endless. Creating allow and deny combinations do have a "pecking order" though; it is that of whichever rule comes first. ASP.NET will iterate through all of the allow and deny settings until it finds the first rule that matches the current user, and then that rule is applied.

For code samples and detailed information regarding using the authorization element, refer to Chapter 15, "Authorization: Control Who Is Accessing Your Site."

The <browserCaps> Element

While potentially overlooked as an aid in security, knowing what the client's browser capabilities are can help in programmatically determining what kind of security to use, as well as being useful for determining which content to provide.

This element provides a way to extract information from a browser from within the web.config file, similar to the functionality of the browscap.ini file; all of this information is also made available through the ASP.NET intrinsic Request object via the Browser class. Using browserCaps through the web.config file allows you to make runtime decisions before loading a page at all. For an example of use, look at the machine.config file in the .NET install directory. Note also that using this functionality requires some knowledge of regular expressions.

The first subtag available is <use> . use allows you to declare a variable name to the server variable you have requested . For example, Listing 20.2 shows the use element to get the server variable HOST_ADDR as a variable named HostAddress . This becomes useful when writing scripts that will parse this information or when you may be dealing with custom header information.

Listing 20.2 The browserCaps <use> Element
 <system.web>      ...configuration elements...      <browserCaps>           <use var="HOST_ADDR" as="HostAddress" />      </browserCaps>      ... more configuration elements... </system.web> 

As shown in Listing 20.2, use has two attributes ” var and as . The var attribute is the name of the server variable or header you want to retrieve, and as is what you intend to name this variable.

The next subtag is <filter> , which is just a container for the subtag <case> . This provides similar functionality to the switch statement or the select case statement. The filter element defines a container in which one or more cases are evaluated to determine what values to establish for certain variables you are using. If we look at the example in Listing 20.3, the HTTP_USER_AGENT header is queried and then that information is used to determine what the browser is capable of based on user knowledge.

Listing 20.3 The browserCaps <filter> Element
 <browserCaps>       <result type="System.Web.HttpBrowserCapabilities, System.Web" />       <use var="HTTP_USER_AGENT" />       browser=Unknown       version=0.0       majorversion=0       minorversion=0       frames=false       tables=false       cookies=false       backgroundsounds=false       <filter>          <case match="^Mozilla[^(]*\(compatible; MSIE             (?'ver'(?'major'\d+)(?'minor'\.\d+)(?'letters'\w*))             (?'extra'.*)">             browser=IE             version=${ ver}             majorver=${ major}             minorver=${ minor}             <case match="^2\." with="%{ version}">                tables=true                cookies=true                backgroundsounds=true                <case match="2\.5b" with="%{ version}">                   beta=true                </case>             </case>          </case>       </filter> </browsercaps> 

Again, notice how regular expressions have been used to parse the values of version , majorver , and minorver . The result subtag has an attribute of type that indicates the class that will be responsible for parsing all of this information. You can create a custom class that implements the System.Web.HttpBrowserCapabilities class or, as this sample shows, just use the prepackaged model. The class shown in this code sample is the same class from which the Request class derives its information. To gather the same information directly from within an .aspx file, look at the sample in Listing 20.4. This sample is available for download from the book's Web site.

Listing 20.4 Browser Information Through the Request Object
 HttpBrowserCapabilities bc = Request.Browser;  Response.Write("<p>Browser Capabilities:</p>");  Response.Write("Type = " + bc.Type + "<br>");  Response.Write("Name = " + bc.Browser + "<br>");  Response.Write("Version = " + bc.Version + "<br>");  Response.Write("Major Version = " + bc.MajorVersion + "<br>");  Response.Write("Minor Version = " + bc.MinorVersion + "<br>");  Response.Write("Platform = " + bc.Platform + "<br>");  Response.Write("Is Beta Version = " + bc.Beta + "<br>");  Response.Write("Is Crawler = " + bc.Crawler + "<br>");  Response.Write("Is AOL = " + bc.AOL + "<br>");  Response.Write("Is Win16 = " + bc.Win16 + "<br>");  Response.Write("Is Win32 = " + bc.Win32 + "<br>");  Response.Write("Does Frames = " + bc.Frames + "<br>");  Response.Write("Does Tables = " + bc.Tables + "<br>");  Response.Write("Does Cookies = " + bc.Cookies + "<br>");  Response.Write("Does VB Script = " + bc.VBScript + "<br>");  Response.Write("Does JavaScript = " + bc.JavaScript + "<br>");  Response.Write("Does Java Applets = " + bc.JavaApplets + "<br>");  Response.Write("Does ActiveX Controls = " + bc.ActiveXControls + "<br>");  Response.Write("CDF = " + bc.CDF + "<br>"); 

The <clientTarget> Element

The clientTarget element is there to allow you to create aliases for user agent information. For example, if you did not want to have the entire user agent string written to a custom log file, you could create an alias that called something much simpler. Consider the example in Listing 20.5.

Listing 20.5 <clientTarget> Element Snippet
 <clientTarget>          <add alias="ie5nt4" userAgent="Mozilla/4.0_ (compatible;MSIE 5.5;Windows NT 4. graphics/ccc.gif 0)" />          <add alias="ie52k" userAgent="Mozilla/4.0 _ (compatible;MSIE 5.5;Windows NT 5. graphics/ccc.gif 0)" /> </clientTarget> 

Under clientTarget are three subtags, add , clear , and remove .

The <add> element, as shown in Listing 20.5, has two required attributes ” alias and userAgent . The value of alias is whatever you want to name the alias, and userAgent is the actual user agent string.

The < clear> element removes all entries related to the parent element it has. For example, if you use the <clear> element within the clientTarget element, all entries made for clientTarget are removed. The <remove> element, which has one required attribute ( alias ), will remove only the alias or aliases for which it is directed.

The <compilation> Element

Using the compilation element allows you to specify parameters for the compilation settings that ASP.NET will use in an application. All of the attributes listed are optional.

First, we will check out the debug attribute. This attribute sets whether ASP.NET will use retail or debug assemblies. The main difference being that debug assemblies usually carry a heavier load because they contain debug symbols. The default value for debug is false , meaning that retail assemblies are used.

Next is the defaultLanguage attribute. As its name implies, defaultLanguage is used to specify the default language used to compile dynamic compilation files, such as .aspx . The default value is vb ; however, this is where the <compilers> and <compiler> subtags come in. Listing 20.6 shows how this transaction takes place.

Listing 20.6 <compiler> Snippet
 <compilation defaultLanguage="VB"          debug="false"          numRecompilesBeforeAppRestart="15">          <compilers>             <compiler language="VB;VBScript"                extension=".cls"                type="Microsoft.VB. VBCodeProvider,System" />             <compiler language="C#;Csharp"                extension=".cs"                type="Microsoft.CSharp. CSharpCodeProvider,System" />          </compilers> </compilation> 

To use a compiler, it must be defined. This does not mean that for every application you must enter custom parameters or define every compiler on the server for each application. This is here to provide flexibility for which the compiler gets called based on a file extension, very much in the same way that IIS allows you to map file types to ISAPI filters. In addition to this, the compiler element has two optional attributes ” warningLevel and compilerOptions . The compiler attributes shown in Listing 20.6 ( language , extension , and type ) are required.

The rest of the elements and attributes associated with the compilation element are not so tricky. In fact, there is one that will make code reviewers around the world elated. Now, you can force the use of explicit declarations from the web.config file. The explicit attribute is used for sites developed in Visual Basic and, if set to true (the default), developers working on the site will be required to declare every variable just as if they were using Option Explicit . The strict attribute, which links directly to the strict compiler option in Visual Basic, is also available in the compilation element.

The batch and batchTimeout attributes are used to determine whether batch processing is enabled and what the timeout for that process will be. batch uses true or false , and batchTimeout accepts a numeric value that represents the number of seconds that can expire before the batch aborts. Additionally, maxBatchGeneratedFileSize represents a numeric value specifying the maximum size of files generated during a batch in kilobytes. In somewhat of a misnomer, maxBatchFileSize actually determines the maximum number of pages that can be generated during a batch process.

Aptly named, the attribute of numRecompilesBeforeApprestart specifies the number of times that ASP.NET will attempt to recompile a page before restarting the application. From a security standpoint, monitoring this may tip you off to an attack if an application that has not changed in months suddenly starts restarting with no user intervention.

Finally, the <assemblies> subtag allows you specify additional resources that may be used during the compilation of your application. This works somewhat like adding a reference to an application. Under the assemblies subtag are the < add> , < remove> , and < clear /> subtags. These function the same as for the clientTarget element, except that the add subtag has a required attribute named assembly . When you add or remove an assembly, it is important to remember that you are setting the assembly parameter to the assembly's name and not the path to the .dll .

The <customErrors> Element

In IIS, you can configure custom error pages for response codes given by the Web server. For example, you can modify the default page for 404 “Not Found to be a special page on your site that can give some additional guidance to the user. In ASP.NET, there is the customErrors element that provides the same service.

The customErrors element has one required attribute, mode . There are three possible values for mode On , Off , and RemoteOnly . When set to On , custom errors are shown to the user; Off shows the detailed error message coming from the CLR or your code. If On is enabled, you can use the defaultRedirect to specify a particular URI for handling error messages or if you do not specify a defaultRedirect page, a generic page, the "friendly error message" page in Internet Explorer, will be displayed to the user. The other option is RemoteOnly . This displays the custom error pages to all visitors other than those from localhost or the local machine. This way, developers can see what the real error messages are without relying on recounts from end users.

The available <error> subtag has two optional attribute ” statusCode and redirect . The statusCode value represents the number associated with an HTTP response code, such as 404 or 500. The redirect value is there in case you want to send the user to a different page other than the one specified in the defaultRedirect attribute. For example, you may not want to send a user receiving a 404 error to the same page as a user getting a 403. Listing 20.7 shows a sample of this usage.

Listing 20.7 customErrors Snippet
 <customErrors defaultRedirect="myerror.htm"          mode="RemoteOnly">          <error statusCode="404"                redirect="NotFound.htm"/> <error statusCode="403"                redirect="Unauthorized.htm"/> </customErrors> 

The <globalization> Element

Again, the self-naming elements are abundant in .NET. In short, globalization allows you to configure the globalization settings for an application. All of the attributes are optional and are not dependent on each other at all.

requestEncoding allows you to set what the encoding of each request must be. This value, however, will be overridden should the request contain an Accept-Charset header. The default value is UTF-8 , but it can be any valid encoding definition, such as ISO-8859-1 . responseEncoding works the same way, only affecting the HTTP response. Unless you want plenty of headaches or have some truly valid reason, the requestEncoding and responseEncoding attributes should have the same value. The fileEncoding attribute allows you to extend this value to .aspx , .asmx , and .asax files as well.

The culture and uiCulture attributes are there to enable addition of a culture to incoming Web requests. Their values must be a valid culture string as accepted by the System.Globalization.CultureInfo class. Listing 20.8 shows a sample of preparing the Web server to receive requests in the "Spanish-Spain" culture.

Listing 20.8 globalization Snippet
 <globalization culture="es-ES" /> 

The <httpHandler> Element

For those of you familiar with the concept of an ISAPI filter, the httpHandler is not that far of a stretch. Basically, an assembly that implements IHttpHandler or IHttpHandlerFactory is announced here so that requests are handled by it first. The uses for this are endless, especially when it comes to custom logging, or scanning for malformed URL requests, such as the URLScan filter from Microsoft does.

httpHandler has three subtags ” <add> , <remove> , and <clear /> . As stated previously, the clear subtag serves only to clear any instances of anything related to the parent container ”in this case, httpHandler . When you add an httpHandler , you must also specify the verb(s) GET , POST , or PUT ; you want to watch the path or URL to monitor ( ex. *.aspx ) and the type attribute that defines the object's name. Optionally, you may set the validate attribute that will not load the assembly until a match is found. Consider the snippet in Listing 20.9.

Listing 20.9 httpHandler Snippet
 <httpHandlers>          <add verb="GET" path="*.aspx" type="MyHandler.New,MyHandler" />          <add verb="*" path="*.myNewFileExtension"_ type="MyHandler.Fin,MyHandler.dll" /> </httpHandlers> 

What's happening here is that we are now mapping the .aspx extension to go through the MyHandler assembly ”probably not the best idea, but used to get the point across. The next entry maps any document with the extension of .myNewFileExtension to the MyHandler.Fin assembly.

NOTE

Even though these settings may exist, IIS still commands the file extension mapping arena. As always, if you create a custom filter for a custom extension, that must be mapped separately in IIS.


The <httpModule> Element

While close to an httpHandler , the httpModule is more of a plug-in than a pre-processor. The sample shown in Listing 20.10 covers a lot of ground in relation to httpModule .

Listing 20.10 httpModule Snippet
 <httpModules>          <add type="System.Web.Caching.OutputCacheModule"                name="OutputCache" />          <add type="System.Web.SessionState.SessionStateModule"                name="Session" />          <add type="Selector, selector.dll"                name="Selector" /> </httpModules> 

In this example, modules are being added. The type attribute accepts the assembly's path, relative to the application's location on the server. The name attribute is how you refer to the assembly from your applicaton. As with httpHandler , there are the <remove> and <clear /> subtags as well. The remove element takes a parameter of name , which corresponds to the name attribute given an assembly when it was added. The clear element, as usual, removes all instances of all modules from the application.

The modules shown in Listing 20.10 illustrate some of the uses for httpModule classes. By definition, an httpModule class is one which implements IHttpmodule and handles events. The items shown in Listing 20.10 handle caching and session state. Custom modules could be created to implement a custom encryption scheme across an application or server.

The <httpRuntime> Element

The httpRuntime element brings a bit of the IIS metabase out into the open . While some of the attributes associated with this element are quite familiar to those used to administering IIS, others are more advanced and lean themselves more towards improving site performance. The attributes available are as follows :

  • appRequestQueueLimit ” This attribute defines the maximum number of requests that ASP.NET will queue for the application. This should only come into play if the application is not handling requests as fast as the requests are coming in. If and when this number is reached, the server will return a 503 “Server Too Busy response to clients until space is made available. This is a good place to handle this event with the customErrors element discussed previously in this chapter.

  • executionTimeout ” As in ASP, this number represents the maximum time allotted for a page to execute in seconds.

  • maxRequestLength ” This attribute, simply put, limits the number of bytes allowed in a file upload request. Use this number wisely because this is a very popular way for hackers to launch denial of service (DOS) attacks against Web servers.

  • minFreeLocalRequestFreeThreads ” The number specified in this attribute will ensure that ASP.NET keeps a minimum number of threads open not only for processing new requests, but also child requests that may spawn at the same time. You may want to use caution when setting this to prevent chance of attack through malicious code that would create an endless or recursive loop within the application ”leading to DOS. The main difference between this attribute and minFreeThreads is that minFreeThreads does not consider local or child requests. The minFreeThreads attribute keeps a minimum number of threads open for new requests coming into the server.

Using the attribute useFullyQualifiedRedirectUrl , if set to true , will cause all redirects to be the fully qualified address of the user being sent to. This may be necessary if you have mobile clients. If set to false , users will be sent relative links. The snippet in Listing 20.11 shows a sample of using these attributes together.

Listing 20.11 httpRuntime Snippet
 <httpRuntime maxRequestLength="4000"        appRequestQueueLimit="5000"         useFullyQualifiedRedirectUrl="true"         executionTimeout="45"        minFreeLocalRequestFreeThreads="100" /> 

The <identity> Element

The <identity> element controls under what user the application runs. It has three attributes ” impersonate , userName , and password . Listing 20.12 shows setting the impersonate value to true and having the application run as user Test with a password of p2s4w5r6d .

Listing 20.12 identity Element Snippet
 <identity impersonate="true" username="Test" password="p2s4w5r6d" /> 

Notice that the user information is not encrypted in any way. Even without this level of security, using this element can still serve to limit access of an application by allowing the anonymous Internet user to impersonate a local account, thus giving enhanced functionality without creating additional risk.

The <machineKey> Element

The machineKey element serves a vital purpose to sites using Forms authentication. It allows you to configure the keys used to encrypt and decrypt the data stored in user cookies. As an added feature, this element can be set at the machine ( machine.config ), site, and application levels, but does not change if set at the directory level ”such as trying to have different subdirectories in an application use different keys. Being able to set this at the machine and/or application level becomes important when establishing a Web farm because the keys are going to need to be consistent across all of the machines. If you are unfamiliar with generating truly random number sequences, Microsoft has provided the RNGCryptoServiceProvider class. As you may have guessed, the RNG is for Random Number Generation. Using the class to generate a key is rather simple, as shown in Listing 20.13. This code listing is available for download from the Sams Web site.

Listing 20.13 GetRNG Function
 public string GetRNG()     {    //Create a byte array to hold the numbers    byte[] bRNG = new Byte[64];    //Get an instance of the RNG Crypto Provider    RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();    //Call the GetNonZeroBytes method to get all non-zero results    rng.GetNonZeroBytes(bRNG);    //Convert the byte array to a string    String results = BitConverter.ToString(bRNG);    //return the string                       results = results.Replace("-", "");    return results;   } 

The results of this function executed from an .aspx page should look something like Listing 20.14.

Listing 20.14 GetRNG Results
 8DB4729D44C0B79AAB0897726B4CB3F982 D6AAC47DB649DB6F6BEE71CB08468254EF 3EA33AC6BD8B3F2BC0FA967E7257A7E7E4 1E2957D9624B9E04B1E3B6FD566B4D25C7 

This result is a much harder key to guess than pretty much anything you or I could come up with off the top of our heads.

The machineKey element has three required attributes ” validationKey , decryptionKey , and validation . Each of these attributes has a set number of options with not too much space to play, except if you manually set one of the key values.

The validationKey attribute can equal either AutoGenerate or a manually assigned value. If you are using a Web farm, as stated before, use the manually assigned value and generate it using something like the GetRNG function in Listing 20.13. Keep in mind that the key must be at least 40-characters (20 bytes) long and not more than 128- characters (64 bytes) long; Listing 20.14 demonstrates a 64-byte result. The default value for validationKey is AutoGenerate . The decryptionKey attribute must follow the same rules as validationKey because it is established to specify the encryption used for data validation. It may be confusing to see the word validation thrown around so much, especially considering that the next attribute is named validation . So after explaining what the validation attribute does, Listing 20.15 will demonstrate the use of this element. The validation attribute specifies which encryption algorithm will be used to validate the data coming in from the user cookies. Its value can be SHA1 , MD5 , or 3DES .

Listing 20.15 machineKey Element Snippet
 <machineKey  validationKey="AutoGenerate" decryptionKey="2964C6F5C2969FC203A226CD567A17D0FE5AAE8251E58907FF1AEAB04D291_ graphics/ccc.gif C8559418336DD9FE5311A32A6801B4DF8E5283A3878249E5FD03CE52238979A3D65BB1ABF graphics/ccc.gif 840A19C96B43ABBE254D1F514ED25E70CD3C0B6BC76E6CA8D7BE76F19DC7D226FD73C3F graphics/ccc.gif 32993E04CA072674D7B3C15BB61756FE59EE74D83432C34CB94"  validation="SHA1" /> 

What's happening in Listing 20.15 is that information going into the user cookie is encrypted using an automatically generated key. This data is then protected by a MAC (see earlier section on Forms authentication, "The <authentication> Element") using the decryptionKey . The validation attribute is setting which algorithm will be used to hash the information coming in to make sure it has not been tampered with.

The <pages> Element

The pages element allows you to define page specific items at an application level. In ASP 2.0/3.0, you could define certain items, such as enabling of session state, within the page or through the IIS MMC application. With ASP.NET, these settings can be controlled through the web.config file. Using the configuration file in this manner is somewhat similar to using a style sheet to control the way a site looks. The main benefit is that you can change the style in one place and have it affect the whole site.

The first attribute we will look at is the autoEventWireup setting. There are only two possible values for this ” true or false . Setting this attribute to true tells .NET that any page events ( Page_Load for example) are automatically enabled. This means that you can "assume" that if your code calls one of these events, it will be there. Setting autoEventWireup to false does not automatically map or enable page events.

The second attribute is buffer . Think of this exactly the same way you may think of Response.Buffer in ASP ”it's the exact same thing. The possible values for this attribute are true and false . As a quick reminder, buffering in this context is referring to whether or not ASP sends the page as it is being processed ( false ) or after the page has completely processed ( true ).

TIP

In ASP.NET, the buffer property of Page.Response , which inherits HttpResponse , has been deprecated. Current practices recommend using the BufferOutput property of the HttpResponse class.


Perhaps one of most improved options in ASP.NET brings us to the next attribute ” enableSessionState . Though claims of improved performance appear to be true , one of the overlooked features is the ReadOnly setting available for this attribute. In addition to true and false , ReadOnly allows you to specify that an application can read information stored in the session but cannot change it. From a security standpoint, this could save many headaches in corporate intranets using shared information across applications. It can also prevent certain spoofing techniques used by hackers who attempt to change session or cookie variables by interrupting the streams of data transferring between the client and server. This brings up the point again of why to use SSL if at all possible or applicable .

The fourth attribute available is enableViewState . This Boolean indicates whether a page maintains its view state after being sent to the client. As a refresher, view state allows ASP.NET to know whether a form is being sent to the client for the first time or it is being submitted.

In another reference to what could be called "server-side style sheeting," the pageBaseType attribute allows you to define a code-behind class that all .aspx pages will inherit by default. It seems to take server-side includes (SSI) to the next level because you do not need to add any code to the page you are working on to have the functionality provided for in the class. Also, unlike present technology for includes and style sheets, this functionality stays at the server, reducing the amount of non-browser related information sent to the client. The attribute of userControlBaseType works the same way, only in relation to a user control that all pages inherit by default.

The <securityPolicy> Element

The securityPolicy element allows you to specify a configuration file to associate with different named levels of security for an application. These named levels are Full , High , Low , and None . Only High and Low will allow you to specify a configuration file to use because Full indicates a full trust of the application and None signifies no trust level.

Under securityPolicy is one subtag ” <trustLevel> . The trustLevel element has two required attributes ” name and policyFile . The value of name must be one of the named values mentioned previously, and policyFile indicates the filename to use as the configuration for that level. Listing 20.16 shows a sample security configuration file. Listing 20.17 shows a snippet of using the securityPolicy element in a web.config file.

Listing 20.16 FullTrust Security Configuration File
 <configuration>    <mscorlib>       <security>          <policy>          <PolicyLevel version="1">             <SecurityClasses>               <SecurityClass Name="StrongNameMembershipCondition" Description="System. graphics/ccc.gif Security.Policy.StrongNameMembershipCondition, mscorlib, Version=1.0.3300.0, graphics/ccc.gif Culture=neutral, PublicKeyToken=b77a5c561934e089"/> <SecurityClass Name="UrlMembershipCondition" Description="System.Security.Policy. graphics/ccc.gif UrlMembershipCondition, mscorlib, Version=1.0.3300.0, Culture=neutral, graphics/ccc.gif PublicKeyToken=b77a5c561934e089"/>               <SecurityClass Name="SecurityPermission" Description="System.Security. graphics/ccc.gif Permissions.SecurityPermission, mscorlib, Version=1.0.3300.0, Culture=neutral, graphics/ccc.gif PublicKeyToken=b77a5c561934e089"/>             <SecurityClass Name="UnionCodeGroup" Description="System.Security Policy. graphics/ccc.gif UnionCodeGroup, mscorlib, Version=1.0.3300.0, Culture=neutral, graphics/ccc.gif PublicKeyToken=b77a5c561934e089"/>               <SecurityClass Name="IsolatedStorageFilePermission" Description="System. graphics/ccc.gif Security.Permissions.IsolatedStorageFilePermission , mscorlib, Version=1.0.3300.0, graphics/ccc.gif Culture=neutral, PublicKeyToken=b77a5c561934e089"/>               <SecurityClass Name="AllMembershipCondition" Description="System.Security. graphics/ccc.gif Policy.AllMembershipCondition, mscorlib, Version=1.0.3300.0, Culture=neutral, graphics/ccc.gif PublicKeyToken=b77a5c561934e089"/>               <SecurityClass Name="NamedPermissionSet" Description= "System.Security. graphics/ccc.gif NamedPermissionSet"/>               <SecurityClass Name="FirstMatchCodeGroup" Description="System.Security. graphics/ccc.gif Policy.FirstMatchCodeGroup, mscorlib, Version=1.0.3300.0, Culture=neutral, graphics/ccc.gif PublicKeyToken=b77a5c561934e089"/>             </SecurityClasses>             <NamedPermissionSets>                <PermissionSet class="NamedPermissionSet"                               version="1"                               Unrestricted="true"                               Name="FullTrust"                               Description="Allows full access to all resources"/>                <PermissionSet class="NamedPermissionSet"                             version="1"                             Name="SkipVerification"                             Description="Grants right to bypass the verifier">                   <IPermission class="SecurityPermission"                                version="1"                                Flags="SkipVerification"/>                </PermissionSet>                <PermissionSet class="NamedPermissionSet"                               version="1"                               Name="Execution"                               Description="Permits execution">                   <IPermission class="SecurityPermission"                                version="1"                                Flags="Execution"/>                </PermissionSet>                <PermissionSet class="NamedPermissionSet"                               version="1"                               Name="Nothing"                               Description="Denies all resources, including  the right to execute"/>                <PermissionSet class="NamedPermissionSet"                               version="1"                               Name="ASP.NET">                   <IPermission class="IsolatedStorageFilePermission"                                version="1"                                Allowed="DomainIsolationByUser"                                UserQuota="1048576"/>                   <IPermission class="SecurityPermission"                                version="1"                                Flags="Execution"/>                </PermissionSet>             </NamedPermissionSets>             <CodeGroup class="FirstMatchCodeGroup"                        version="1"                        PermissionSetName="Nothing">                <IMembershipCondition class="AllMembershipCondition"                                      version="1"/>                <CodeGroup class="UnionCodeGroup"                           version="1"                           PermissionSetName="ASP.NET">                   <IMembershipCondition class="UrlMembershipCondition"                                         version="1"                                         Url="$AppDirUrl$/*"/>                </CodeGroup>                <CodeGroup class="UnionCodeGroup"                           version="1"                           PermissionSetName="ASP.NET">                   <IMembershipCondition class="UrlMembershipCondition"                                         version="1"                                         Url="$CodeGen$/*"/>                </CodeGroup>                <CodeGroup class="UnionCodeGroup"                           version="1"                           PermissionSetName="FullTrust">                   <IMembershipCondition class="UrlMembershipCondition"                                         Url="$Gac$/*"                                         version="1"/>                </CodeGroup>                <CodeGroup class="UnionCodeGroup"                              version="1"                              PermissionSetName="FullTrust"                              Name="Microsoft_Strong_Name"                              Description="This code group grants code signed  with the Microsoft strong name full trust.">                      <IMembershipCondition class="StrongNameMembershipCondition"                                            version="1" PublicKeyBlob="0024000004800000940000000602000000240000525341310004000001000 10007D1FA57C4AED9F0A32E84AA0FAEFD0DE9E8FD6AEC8F87FB03766C834C99921EB23BE79AD 9D5DCC1DD9AD236132102900B723CF980957FC4E177108FC607774F29E8320E92EA05ECE4E82 1C0A5EFE8F1645C4C0C93C1AB99285D622CAA652C1DFAD63D745D6F2DE5F17E5EAF0FC4963D2 61C8A12436518206DC093344D5AD293"/>                </CodeGroup>                <CodeGroup class="UnionCodeGroup"                              version="1"                              PermissionSetName="FullTrust"                              Name="Ecma_Strong_Name"                              Description="This code group grants code signed       with the ECMA strong name full trust.">                <IMembershipCondition class="StrongNameMembershipCondition"                                            version="1"                           PublicKeyBlob="00000000000000000400000000000000"/>                </CodeGroup>             </CodeGroup>             <FullTrustAssemblies>                   <IMembershipCondition class="StrongNameMembershipCondition"                                         version="1"                               PublicKeyBlob="00000000000000000400000000000000"                                         Name="System"/>             </FullTrustAssemblies>          </PolicyLevel>          </policy>       </security>    </mscorlib> </configuration> 
Listing 20.17 securityPolicy Element Snippet
 <securityPolicy> <!--the value of policyFile for Full will always be "internal" -->    <trustLevel name="Full" policyFile="internal" />    <trustLevel name="High" policyFile="my_hightrust_web.config" />    <trustLevel name="Low"  policyFile="my_lowtrust_web.config" />    <trustLevel name="None" policyFile="noaccess.config" /> </securityPolicy> 

The <sessionState> Element

As mentioned earlier in the section, "The <pages> Element," the use of session state is not to be feared or ridiculed in ASP.NET. The sessionState element allows you to define where session information is stored. This is both an enhancement to functionality as well as administration, because currently in IIS 5, there is nowhere to configure such settings.

There is one required attribute, mode . The mode attribute must have one of the following values ” Off , Inproc , StateServer , or SQLServer . The rest of the attributes associated with this element are optional, depending on what mode 's value is. If you set the value of mode to Off , session state is disabled completely for that application. Setting it to Inproc specifies that session information is stored on the local server ”basically, the way it works in ASP. Additionally, at this point, you may want to configure the timeout attribute, which specifies the number of seconds of inactivity before the session times out. Also available is the cookieless attribute that, setting to true or false , indicates whether to use cookies to store session information.

Should you want to configure your application to store session information on a remote server, the StateServer value must be given to mode. After this is set, a stateConnectionString attribute must be added and given a value of the protocol, name, or IP address and port. For example, tcpip=192.168.0.2:42424 . For this to work, the ASP.NET State Service must be running on the remote machine. At the time of this writing, this is installed with the Enterprise Architect and Premium versions of .NET.

The final option is using SQL Server to manage session state. Setting mode to SQLServer requires that you also set the sqlConnectionString attribute to a valid SQL Server database connection string. To most developers, this is nothing new, but from a security standpoint, it raises an issue. Because the web.config file is not encrypted, the user information used to log in to SQL Server is available in plain text. By design, ASP.NET will not serve any file with the .config extension; however, it may still be possible for someone internally to get this information and use it for malicious purposes. If the application is running as a specific user or running as the currently logged-in user in an application using Windows authentication, you may be able to use "TRUSTED_CONNECTION=YES" in the connection string eliminating any specific user information. Use of this will depend on whether that user has privileges within SQL Server.

To establish the database to use for this option, locate the InstallSqlState.sql file. By default, this file should be located in the %WINDIR% \Microsoft.NET\Framework\[ version ] directory. Executing this file in SQL Server will create the ASPState database and associated stored procedures in the TempDB database. Listing 20.18 shows a complete web.config file that could be the basis for any ASP.NET Web site configured to use SQL Server to store session information. The complete code listing is available in the code downloads for this chapter on Sams Web site.

Listing 20.18 sessionState Enabled web.config File
 <?xml version="1.0" encoding="utf-8" ?> <configuration>  <system.web>   <compilation    defaultLanguage="c#"     debug="true"      />   <customErrors    mode="RemoteOnly"     />   <authentication    mode="Windows"     /> <!--Setting the identity to impersonate=true    requires the currently logged in user    to have an account on SQL Server  <identity    impersonate="true"     />   <sessionState    mode="SQLServer"    cookieless="true"    timeout="20"    sqlConnectionString="server=(local);TRUSTED_CONNECTION=YES"    />   <trace   enabled="false"   requestLimit="10"   pageOutput="false"   traceMode="SortByTime"   localOnly="true"   />   <globalization    requestEncoding="utf-8"    responseEncoding="utf-8"    />  </system.web> </configuration> 

The <trace> Element

The trace element allows you to define listeners that collect, route, and store messages generated during tracing an application. While an entire chapter could be devoted to tracing applications, this section offers to give an overview of what is available in .NET for configuring tracing at the application level through the web.config file.

The trace element only has one attribute ” autoflush . The autoflush attribute is a Boolean indicating whether the trace output buffer is automatically flushed. The default value is false .

Additionally, the trace element has one subtag, <listeners> , which allows you to add or remove different listeners to the tracing of the application, specify the type of listener, and specify the path to where the trace messages are logged.

The <trust> Element

Not to be confused with the trust settings in the securityPolicy element, the trust element allows you to trust applications other than your own. It uses the default security configuration files provided by .NET. For an example of one of these files, see Listing 20.17 earlier in this chapter.

The trust element carries a required attribute of level . As with the securityPolicy element, level may be one of four named values ” Full , High , Low , or None . These levels relate to the Code Access Security applied to the application. The optional attribute of originUrl allows you to specify from where the trusted request can come. Listing 20.19 shows a sample of trusting an outside application. For this example, we'll say that your company is YourCompany.com and you trust an application from SomeOtherCompany.com (both hopefully fictitious sites).

Listing 20.19 trust Element Snippet
 <trust level="High" originUrl="http://www.someothercompany.com/default.aspx" /> 

The <webServices> Element

In its simplest explanation, the webServices element allows you to configure the settings associated with Web Services created in ASP.NET. This section will assume a certain amount of knowledge regarding Web Services and Simple Object Access Protocol (SOAP).

NOTE

For an in depth understanding of SOAP, check out the online documentation at MSDN (http://msdn.microsoft.com/SOAP) or Applied SOAP: Implementing .NET XML Web Services by Kenn Scribner and Mark Stiver.


While the webServices element has no direct attributes, it does have six subtags, each having a rather direct purpose and explanation. The first subtag we will examine is the <protocols> element. The purpose of this element is to define which protocols ASP.NET can use to decrypt information sent from a client in an HTTP request. This is extremely important because the request can contain not only the Web Service's name, but also any parameters necessary for execution. Having the wrong protocols enabled will only serve to create application errors that can easily be prevented. The protocols element has no attributes, but it does have one subtag ” <add> . The add element has one required attribute of name . If a protocol is not defined here, it is not used. There is no need for a remove or clear element as with other elements listed previously. The name attribute of the add subtag may have one of four values. These values are the currently supported protocols by Microsoft for handling HTTP requests. They are HttpSoap , HttpPost , HttpGet , and Documentation . Note that the Documentation option is not indicative of a native HTTP standard protocol. Documentation allows direct requests to an .asmx file to be responded to with an ASP.NET-generated documentation page. This is what happens by default when you build a Web Service in Visual Studio.NET.

The next element to review is the serviceDescriptionFormatExtensionTypes subtag. This element has a subtag of <add> with a required attribute of type . The value of type must be the name of the class you want to use as a ServiceDescriptionFormatExtension . In short, a ServiceDescriptionFormatExtention allows you to add an extensibility element to a Web Service in addition to those defined by the Web Services Definition Language (WSDL).

Speaking of WSDL, the next element we will look at is the wsdlHelpGenerator subtag. This provides a container for the developer to enter a URI of a page that provides descriptive information regarding a Web Service. This page is accessed when a user attempts to navigate directly to the .asmx file, thus overriding the default generated page created when the Documentation protocol is enabled.

The next and final three elements available are related to SoapExtensions . A SoapExtension , other than inheriting the SoapExtension class, allows the developer to extend or monitor SOAP messages and modify them if necessary. Microsoft has provided an excellent code sample in the .NET documentation showing a SoapExtension that traces the SOAP messages in a request and logs the request and response output. The documentation URL for this sample is ms-help://MS.VSCC/MS.MSDNVS/cpref/html/frlrfSystemWebServicesProtocolsSoapExtensionClassTopic.htm . The soapExtensionTypes , soapExtensionReflectorTypes , and soapExtensionImporterTypes elements allow you to add specific classes to run under certain events. soapExtensionTypes allows you to define SoapExtensions that are called with every request to a Web Service. soapExtensionReflectorTypes is there to define any SoapExtensions you may want to call when a service description is generated for a Web Service, for example, when a user navigates directly to the .asmx file. Finally, soapExtensionImporterTypes allows you to define classes that will be called when a Web Service must call a proxy class or stub. This can occur under circumstances where COM+ compatibility is required from within a Web Service.

Using Custom Attributes and Settings

Here is where we will see a sample of the extensibility available in ASP.NET through the use of XML. You can use custom attributes from within the web.config file for just about any purpose. Two things to keep in mind are that every time one of these values is called, the web.config file must be read; this could lead to a performance question. The other is that this is a plain-text file, so make sure that you have set the ACL permissions correctly depending on your situation. Listing 20.20 shows a web.config file using a custom attribute of "welcomeMessage" .

Listing 20.20 web.config File with Custom Attribute
 <?xml version="1.0" encoding="utf-8" ?> <configuration>  <appSettings>   <add key="welcomeMessage" value="Welcome to ASP.NET " />  </appSettings> </configuration> 

Notice the use of the appSettings element to store a new key called "welcomeMessage" . This could just as easily be used to store a database connection string or parameters for a specific Web control on your page. Listing 20.21 shows how to access this value from your aspx.cs page. These samples are included in the code downloads available from the book's Web site.

Listing 20.21 Code Showing appSettings Value
 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.Web.Configuration; using System.Configuration; using System.Collections.Specialized; namespace Ch20CustomConfig {  /// <summary>  /// Summary description for WebForm1.  /// </summary>  public class WebForm1 : System.Web.UI.Page  {   private void Page_Load(object sender, System.EventArgs e)   {    Response.Write(ConfigurationSettings.AppSettings["welcomeMessage"]);   }   #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  } } 

What Listing 20.21 shows is just how simple it is to access your custom attributes stored in a web.config file. Using Windows Integrated authentication and the inherited User object, you could easily add the user's name to this message after he or she is authenticated.

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