Archive for March, 2008

Uncategorized The ViewState security

Comments Off

The ViewState mechanism

ViewState is the mechanism by which a .NET page maintains it’s state (information) between page post backs (e.g. the user will save data to her browser).

Introducing ViewState

The Http/Https protocol is stateless and text based, which means that state is not maintained between client requests by default and that the data exchanged between client and server are all clear text (or encoded text). ASP.NET provides several mechanisms to manage state in a more powerful and easier to utilize way than classic ASP.

Page level state is information maintained when an element on the web form page causes a subsequent request to the server for the same page ?€“ referred to as ‘postback’. This is appropriately called ViewState as the data involved is usually, though not necessarily, shown to the user directly within the page output.

The Control.ViewState property is associated with each server control in your web form and provides a dictionary object for retaining values between such multiple requests for the same page. This is the method that the page uses to preserve page and control property values between round trips.

When the page is processed, the current state of the page and controls is hashed into a string and saved in the page as a hidden field, that is if we talk simplistically. When the page is posted back to the server, the page parses the view state string at page initialization and restores property information in the page.

ViewState is enabled by default so if you view a web form page in your browser you will see a line similar to the following near the form definition in your rendered HTML:

value=“dDwxNDg5OTk5MzM7Oz7DblWpxMjE3ATl4Jx621QnCmJ2VQ==” />

When a page is re-loaded two methods pertaining to ViewState are called: LoadViewState and SaveViewState. Page level state is maintained automatically by ASP.NET but you can disable it, as necessary, by setting the EnableViewState property to false for either the controls whose state doesn’t need to be maintained or for the page as a whole. For the control:

< %@ Page EnableViewState=?€false?€ %>

You can validate that these work as claimed by analyzing the information presented if you turn on tracing for a page containing the above elements. You will see that on postback, and assuming ViewState is enabled, that the LoadViewState method is executed after the Init method of the Page class has been completed. SaveViewState is called after PreRender and prior to actual page rendering.

You can also explicitly save information in the ViewState using the State Bag dictionary collection, accessed as follows:

ViewState(key) = value

Which can then be accessed as follows:

Value = ViewState(key)

It is important to remember that page level state is only maintained between consecutive accesses to the same page. When you visit another page the information will not be accessible via the methods above. For this we need to look at other methods and objects for storing state information, typically session state if the information is required on a per user basis.

Postback and non-postback controls

Some server controls, for example the textbox control, post their values as part of the postback operation and are known as postback controls. For such postback controls ASP.NET retrieves their values one by one from the HTTP Request and copies them to control values whilst creating the HTTP Response. Traditionally, web developers had to write code to do all this but now ASP.NET handles these activities automatically. Importantly there are no extra storage overheads for ViewState in maintaining state for postback controls.

In addition ViewState also supports non-postback controls, e.g. Label controls. This is where the hidden fields are used to maintain state. When ASP.NET executes a page, it collects the values of all non-post back controls that are modified in code and formats them into a single base64-encoded string. This string is then stored in a hidden file in a control named __VIEWSTATE, as per the example above. The hidden field is a post back control and when the encoded string is processed by the web server ASP.NET decodes the string at page initialization and restores the controls values to the page.

What can you store in ViewState?

ViewState offers a substantial improvement over the two competing techniques for state management via the client: standard hidden fields and cookies, in that ViewState is not limited to the storage of simple values. You can use ViewState to store any object as long as it is serializable, and the standard VB.NET types are. Serialization is the process of storing an object’s data and other information necessary to reconstruct the object later.

Protecting ViewState

By default the ViewState of a page is unprotected. Although the values are not directly visible as in the case of querystring or hidden form fields, it would not be too difficult for a determined individual to decode the stored information. However, Microsoft has provided two mechanisms for increasing the security of ViewState.

Message Authentication Code (MAC)

A MAC does not protect from information disclosure. It instead protects from integrity attacks and authenticity (with properties similar to those of a digital signature,but not the same). In this technique the ViewState is encoded using a hash code (using the SHA1 which means that it is an HMAC) before it is sent to the client browsers. On post back ASP.NET checks the encoded ViewState to verify it has not been tampered with. This is called a massage authentication code and is simply enabled at the page level:

< %@ Page EnableViewStateMac=”true”%>

However, MAC is enabled by default in the machine.config file and should not be a concern unless someone has altered the default settings. But even if you do not use a default configuration or have used the default machine.config, while using the WebFormAuthentication MAC is enabled either way.
To be more specific of what a MAC is look at the current diagram:

MAC displayed

A cryptographic message authentication code (MAC) is a short piece of information used to authenticate a message. A MAC algorithm accepts as input a secret key and an arbitrary-length message to be authenticated, and outputs a MAC (sometimes known as a tag). The MAC value protects both a message’s integrity as well as its authenticity, by allowing verifiers (who also possess the secret key) to detect any changes to the message content.

A message integrity code (MIC) is different from a MAC in that a secret key is not used in its operation. Although the terms are sometimes used interchangeably, a MIC should always be encrypted during transmission if it is to be used as a reliable gauge of message integrity. On the other hand, a MAC, which uses a secret key, does not necessarily need to be encrypted to provide the same level of assurance. A given message will always produce the same MIC assuming the same algorithm is used to generate both. Conversely, the same message can only generate matching MACs if the same secret key is used with the same algorithms to generate both. MICs don’t use secret keys and, when taken on their own, are therefore a much less reliable gauge of message integrity.

While MAC functions are similar to cryptographic hash functions, they possess different security requirements. To be considered secure, a MAC function must resist existential forgery under chosen-plaintext attacks. This means that even if an attacker has access to an oracle which possesses the secret key and generates MACs for messages of the attacker’s choosing, he can “never” guess the MAC for any message that he has not yet asked the oracle about. (Here “never” means, “not without doing an infeasible amount of computation”).

MACs differ from digital signatures, as MAC values are both generated and verified using the same secret key. This implies that the sender and receiver of a message must agree on keys before initiating communications, as is the case with symmetric encryption. For the same reason, MACs do not provide the property of non-repudiation offered by signatures: any user who can verify a MAC is also capable of generating MACs for other messages. In contrast, a digital signature is generated using the private key of a key pair, which is asymmetric encryption. Since this private key is only accessible to its holder, a digital signature proves that a document was signed by none other than that holder. Thus, digital signatures do offer non-repudiation.

MAC algorithms can be constructed from other cryptographic primitives, such as cryptographic hash functions (as in the case of HMAC) or from block cipher algorithms (OMAC, CBC-MAC and PMAC).

Encoding and Encrypting the ViewState

When the ASP.NET page framework creates a hash for view state data, it uses a MAC key that is either auto-generated or specified in the Machine.config file. If the key is auto-generated, it is created based on the MAC address of the computer. The MAC address is the unique GUID value of the network adapter in the computer.

It can be difficult for malicious users to reverse-engineer the MAC key based on the value in the page and the view state. Thus, MAC encoding is typically a reliable way to determine whether anyone has tampered with the view-state data.

In general, the larger the MAC key that is used to generate the hash, the less likely it is that the hash value for different strings will be the same. When the key is auto-generated, ASP.NET uses SHA1 encoding to create a large key. However, in a Web-farm environment, the key must be the same across all of the servers. If the key is not the same, and the page is posted back to a different server than the one that created the page, the ASP.NET page framework will raise an exception. Therefore, in a Web farm environment, you should specify a key in the Machine.config file instead of allowing ASP.NET to auto-generate one. The longer the key, the more secure it is; but the longer the key is the more time it takes to create a hash, so it is important to weigh security needs versus performance needs.

You can instruct ASP.NET to encrypt the contents of ViewState using the Triple DES symmetric algorithm (see the .NET SDK documentation for more information) ?€“ a stronger encryption algorithm that makes it very difficult for anyone to decode the ViewState.

This encryption can only be applied at the machine.config level, as follows:

< %@ Page EnableViewStateMac=”true”%>

Reference: ASP.NET: Tips, Tutorial and Code Scott Mitchell et al.Sams

Reference: Developing and implementing web applications with VB.Net and VS.Net
Mike Gunderloy Que

Reference: Taking a Bite Out of ASP.NET ViewState Susan Warren

Reference:http://msdn.microsoft.com/netframework/downloads/samples/default.aspx?pull=/library/en-us/dnaspnet/html/asp11222001.asp

Reference:http://en.wikipedia.org/wiki/Message_authentication_code

Notice:This article was originally posted at http://www.dotnetjohn.com/articles.aspx?articleid=71, and I am providing you with an altered version.

Uncategorized When using ASP.NET Validator Controls…

Comments Off

What is an ASP .NET Control Validator

It’s not often I like to display my ignorance in public but in this case it’s worth it. I’ve been using ASP.NET Validator controls for a while now with the knowledge that they provided me with an easy way to do both client-side and server-side validation in one step. I never bothered to get to deeply involved in the documentation about them because I thought how difficult can they possibly be to use. Well the truth is not difficult at all, if you know how to use them. The implicit client-side validation that they cause fooled me into believing that the validation occured the same way on the server-side as well. In other words, a page will not submit until the data is verified. Then I read this today in Fritz Onion’s Essential ASP.NET book [1]:

“As soon as you place a validation control on a page, it is imperative that you check the IsValid flag of the Page class before using any of the data posted by the client. It is a common misconception that if validation fails on a page, the code for that page will not execute. On the contrary, the only thing that happens when server-side validation fails is that the IsValid flag of the Page class is set to false, and each validation control that failed renters itself as a visible span so that the error indicator shows up when the page is redisplayed to the user.”

I was under that misconception. Well sort of. I thought that the page would execute but as soon as an invalid control was hit, the page would rerender to the user and the proper messages would be displayed. Fritz Onion explains that if the client browser does not support JavaScript or a malicious user removes your JavaScript, no client side validation will occur and therefore you must ensure that IsValid == true on the server-side. Please also be congnizant of the fact that you must wait until the Page class calls it’s Validate() method, which occurs after the Page.Load event fires, or explicitly call Validate() on the page yourself prior to checking the Page.IsValid property [1].

VB .NET page processing

Figure: Way VB.NET is executed [2].

As shown in Figure, there is direct interaction between the two sections of the page. XHTML code makes a call to the script portion of the page, often times supplying data for processing. The script code processes this and possibly other input data to generate output information. This output is then placed in the XHTML section of the page where it is viewable when the page is returned to the user [2].

So if we assume that someone would write a login page and this someone would like to use some Validator Controls then the code would look something like this:

The ASP.NET part of the code would look like this:

? If Page.IsValid And dataReader.Read() Then
? ? ? ? ? ? ?
If dataReader(“pass”).ToString = uPass.Text And dataReader(“user”).ToString = uName.Text Then
? ? ? ? ? ? ? ? ? Return True
? ? ? ? ? ? ? Else
? ? ? ? ? ? ? ? ? Return False
? ? ? ? ? ? ? ? End If
? ? Else
? ? ? ? ? ? Return False
? ? End If

The html part of the code would look something like that:

<html>
Some Code ….
? ? <form name=”.cookie” runat=”server”>
Some Code ….
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? <td>
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? Username:</td>
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? <td>
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? <asp:TextBox id=“uName” runat=”server”>
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
</asp:TextBox>
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? </td>
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? <td>
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? <asp:RequiredFieldValidator id=“Requiredfieldvalidator1″
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? runat=“server”
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ErrorMessage=“*”
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? Display=“Static”
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ControlToValidate=“uName”>
? ? ? ? ? ? ? ? ? ? ? ? </asp:RequiredFieldValidator>

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? </td>
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? </tr>
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? <tr>
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? <td>
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? Password:
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? </td>

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? <td>
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? <asp:TextBox id=“uPass”
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? runat=“server”
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? TextMode=“Password”>
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? </asp:TextBox>

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? </td>
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? <td>
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? <asp:RequiredFieldValidator id=“Requiredfieldvalidator2″
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? runat=“server”
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ErrorMessage=“*”
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? Display=“Static”
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ControlToValidate=“uPass”>
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? </asp:RequiredFieldValidator>

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? </td>
Some Code ….
? ? ? </form>
Some Code ….
? </body>
</html>

Code Example: Using the IsPageValid .NET to write a login page (This is not secure coding? ).

Now the ASP.NET code will actually properly enforce the control validation elements to do properly the user input validation.

The? TextBox Control

When using a TextBox for data entry a risk is that users may not enter necessary or appropriate data for script processing. Suppose, for instance, a script performs some type of arithmetic processing on entered data. If the user fails to enter a data value or fails to enter a numeric value, a script error occurs, aborting page processing and causing embarassment for the programmer. It is always a good idea, then, to validate user input prior to activating a script that processes that input data [2].

There are several ways to validate user input depending on the type of data needed for script processing. The most common requirement is for the mere existence of an input value. Some value, any value, is expected in the TextBox before a script can carry out its processing. In other cases, an input value must be of a particular data type. A numeric value must be entered if arithmetic processing is to occur, or a value within a particular range of values may be expected [2].

For common types of data validation, ASP.NET provides a set of validation controls. These validators can test for missing values, comparison values, values within a range, and other forms of data to ensure that proper data is supplied to processing scripts. These controls are associated with TextBox controls and perform their tests automatically when Button, LinkButton, or ImageButton controls are clicked to call subprograms for processing. If a validation test is not met, the validator displays an error message to call attention to this fact, and the user is given the chance to reenter valid data in the associated TextBox [2].

The <asp:RequiredFieldValidator> Control

The most common type of validation test is for a missing value. The <asp:RequiredFieldValidator> control tests a TextBox for a missing value and issues an error message if this is the case. Importantly, the subprogram that processes the TextBox value is not activated by its button click until data is entered into the TextBox. The general format for a RequiredFieldValidator is shown above [2].

Reference [1]: http://weblogs.asp.net/sibrahim/archive/2003/06/15/8723.aspx

Reference [2]: http://it.maconstate.edu/tutorials/ASPNET20/

?

?

?